public class DrawerAdapter extends ArrayAdapter<String> {
    private final Context context;
    private final ArrayList<String> values;
    private RelativeLayout l;
    MainActivity m;
    Futils futils=new Futils();
    IconUtils icons;
    Float[] color;
    private SparseBooleanArray myChecked = new SparseBooleanArray();
    HashMap<String,Float[]> colors=new HashMap<String,Float[]>();

    public void toggleChecked(int position) {
        toggleChecked(false);
        myChecked.put(position, true);
        notifyDataSetChanged();
    }

    public void toggleChecked(boolean b) {

        for (int i = 0; i < values.size(); i++) {
            myChecked.put(i, b);
        }
        notifyDataSetChanged();
    }
    void putColor(String x,float a,float b,float c){colors.put(x,new Float[]{a,b,c});}
    void putColors(){
        putColor("#F44336",0.956862f,0.2627450f,0.21176470f);
        putColor("#e91e63",0.91372549f,0.11764706f,0.38823529f);
        putColor("#9c27b0",0.61176471f,0.15294118f,0.69019608f);
        putColor("#673ab7",0.40392157f,0.22745098f,0.71764706f);
        putColor("#3f51b5",0.24705882f,0.31764706f,0.70980392f);
        putColor("#2196F3",0.12941176f,0.58823529f,0.952941176470f);
        putColor("#03A9F4",0.01176470f,0.66274509f,0.9568627450f);
        putColor("#00BCD4",0.0f,0.73725490f,0.831372549f);
        putColor("#009688",0.0f,0.58823529f,0.53333f);
        putColor("#4CAF50",0.298039f,0.68627450f,0.31372549f);
        putColor("#8bc34a",0.54509804f,0.76470588f,0.29019608f);
        putColor("#FFC107",1.0f,0.7568627450f,0.0274509f);
        putColor("#FF9800",1.0f,0.596078f,0.0f);
        putColor("#FF5722",1.0f,0.341176470f,0.1333333f);
        putColor("#795548",0.4745098f,0.3333f,0.28235294f);
        putColor("#212121",0.12941176f,0.12941176f,0.12941176f);
        putColor("#607d8b",0.37647059f,0.49019608f,0.54509804f);
        putColor("#004d40",0.0f, 0.301960f, 0.250980f);

    }
    public DrawerAdapter(Context context, ArrayList<String> values, MainActivity m, SharedPreferences Sp) {
        super(context, R.layout.rowlayout, values);

        this.context = context;
        this.values = values;

        for (int i = 0; i < values.size(); i++) {
            myChecked.put(i, false);
        }
        icons = new IconUtils(Sp, m);
        this.m = m;
        putColors();
        color=colors.get(m.fabskin);
        if(color==null) {
            color=colors.get("#e91e63");
        }
    }
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.drawerrow, parent, false);
        TextView textView = (TextView) rowView.findViewById(R.id.firstline);
        final ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
        l = (RelativeLayout) rowView.findViewById(R.id.second);
        if(m.theme1 == 0) {
            l.setBackgroundResource(R.drawable.safr_ripple_white);
        } else {
            l.setBackgroundResource(R.drawable.safr_ripple_black);
        }
        l.setOnClickListener(new View.OnClickListener() {

            public void onClick(View p1) {
                m.selectItem(position, false);
            }
            // TODO: Implement this method

        });
        l.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                // not to remove the first bookmark (storage)
                if (position>=m.val.size()) {

                    if (m.theme1 == 0)
                        imageView.setImageResource(R.drawable.ic_action_cancel_light);
                    else
                        imageView.setImageResource(R.drawable.ic_action_cancel);
                    imageView.setClickable(true);

                    imageView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            m.selectItem(position, true);
                        }
                    });
                }

                // return true to denote no further processing
                return true;
            }
        });

        float[] src = {

                color[0], 0, 0, 0, 0,
                0, color[1], 0, 0, 0,
                0, 0,  color[2],0, 0,
                0, 0, 0, 1, 0
        };
        ColorMatrix colorMatrix = new ColorMatrix(src);
        ColorMatrixColorFilter colorMatrixColorFilter = new ColorMatrixColorFilter(colorMatrix);
        if(values.get(position).equals("/storage/emulated/0"))
            textView.setText(futils.getString(context,R.string.storage));
        else if(values.get(position).equals("/")){
            textView.setText(R.string.rootdirectory);
        }
        else {
            textView.setText(new File(values.get(position)).getName());
        }

        if(myChecked.get(position)){
            if(m.theme1==0)
            rowView.setBackgroundColor(Color.parseColor("#ffeeeeee"));
            else rowView.setBackgroundColor(Color.parseColor("#ff424242"));
            imageView.setColorFilter(colorMatrixColorFilter);
            //textView.setTypeface(Typeface.DEFAULT_BOLD);
            textView.setTextColor(Color.parseColor(m.fabskin));

            imageView.setImageResource(R.drawable.folder_drawer_white);
            //if(m.theme1==0)
            imageView.setColorFilter(colorMatrixColorFilter);
        }
        else
        {
            if(m.theme1==0) {
                textView.setTextColor(m.getResources().getColor(android.R.color.black));
            }
            else
            {
                textView.setTextColor(m.getResources().getColor(android.R.color.white));
            }
            imageView.setImageResource(R.drawable.folder_drawer);
        }

        return rowView;
    }
} public class TabHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "explorer.db";
    private static final String TABLE_TAB = "tab";

    public static final String COLUMN_TAB_NO = "tab_no";
    public static final String COLUMN_LABEL = "label";
    public static final String COLUMN_PATH = "path";
    public static final String COLUMN_HOME = "home";
    public TabHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, DATABASE_NAME, factory, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String CREATE_TAB_TABLE = "CREATE TABLE " + TABLE_TAB + "("
                +  COLUMN_TAB_NO
                + " INTEGER PRIMARY KEY,"
                + COLUMN_PATH + " TEXT,"+COLUMN_HOME+" TEXT" + ")";
        sqLiteDatabase.execSQL(CREATE_TAB_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_TAB);
        onCreate(sqLiteDatabase);
    }

    public void addTab(Tab tab) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(COLUMN_TAB_NO, tab.getTab());
        contentValues.put(COLUMN_PATH, tab.getPath());
        contentValues.put(COLUMN_HOME, tab.getHome());
        SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
        sqLiteDatabase.insert(TABLE_TAB, null, contentValues);
        sqLiteDatabase.close();
    }
 public void clear(){
     try {
         SQLiteDatabase sqLiteDatabase = getWritableDatabase();
         sqLiteDatabase.delete(TABLE_TAB,COLUMN_TAB_NO+" = ?",new String[]{""+1});
         sqLiteDatabase.delete(TABLE_TAB, COLUMN_TAB_NO + " = ?", new String[]{"" + 2});
     sqLiteDatabase.close();
     } catch (NumberFormatException e) {
         e.printStackTrace();
     }


 }
    public Tab findTab(int tabNo) {
        String query = "Select * FROM " + TABLE_TAB + " WHERE " + COLUMN_TAB_NO + "= \"" + tabNo + "\"";
        SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
        Cursor cursor = sqLiteDatabase.rawQuery(query, null);
        Tab tab = new Tab();
        if (cursor.moveToFirst()) {
            cursor.moveToFirst();
            tab.setTab(Integer.parseInt(cursor.getString(0)));
            tab.setPath(cursor.getString(1));
            tab.setHome(cursor.getString(2));
            cursor.close();
        } else {
            tab = null;
        }
        sqLiteDatabase.close();
        return tab;
    }

    public List<Tab> getAllTabs() {
        List<Tab> tabList = new ArrayList<Tab>();
        // Select all query
        String query = "Select * FROM " + TABLE_TAB;

        SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
        Cursor cursor = sqLiteDatabase.rawQuery(query, null);
        // Looping through all rows and adding them to list
        if (cursor.moveToFirst()) {
            do {
                Tab tab = new Tab();
                tab.setTab((cursor.getInt(cursor.getColumnIndex(COLUMN_TAB_NO))));
                tab.setPath(cursor.getString(cursor.getColumnIndex(COLUMN_PATH)));
                tab.setHome(cursor.getString(cursor.getColumnIndex(COLUMN_HOME)));
                //Adding them to list
                tabList.add(tab);
            } while (cursor.moveToNext());
        }sqLiteDatabase.close();
        return tabList;
    }
    public void close(){
        try {
            getWritableDatabase().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
} public class AppsList extends ListFragment {
    Futils utils = new Futils();
    AppsList app = this;
    AppsAdapter adapter;

    SharedPreferences Sp;
    public boolean selection = false;
    public ActionMode mActionMode;
    public ArrayList<ApplicationInfo> c = new ArrayList<ApplicationInfo>();
    ListView vl;
    public IconHolder ic;
    ArrayList<Layoutelements> a = new ArrayList<Layoutelements>();
    public int theme1;
    private MainActivity mainActivity;
    private String fabSkin;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(false);
        ic=new IconHolder(getActivity(),true,true);
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setRetainInstance(true);
        mainActivity=(MainActivity)getActivity();
        mainActivity.toolbar.setTitle(utils.getString(getActivity(), R.string.apps));
        mainActivity.tabsSpinner.setVisibility(View.GONE);
        mainActivity.floatingActionButton.setVisibility(View.GONE);
        mainActivity.buttonBarFrame.setVisibility(View.GONE);
        mainActivity.supportInvalidateOptionsMenu();
        fabSkin = mainActivity.fabskin;
        vl=getListView();
            Sp = PreferenceManager.getDefaultSharedPreferences(getActivity());

        ListView vl = getListView();
        int theme=Integer.parseInt(Sp.getString("theme","0"));
        theme1 = theme==2 ? PreferenceUtils.hourOfDay() : theme;
        vl.setDivider(null);
        if (vl.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) vl.getLayoutParams();
            p.setMargins(0, getToolbarHeight(getActivity()), 0, 0);
            vl.requestLayout();
        }
        if(theme1==1)getActivity().getWindow().getDecorView().setBackgroundColor(getResources().getColor(R.color.holo_dark_background));
         if(savedInstanceState==null)new LoadListTask().execute();
        else{
        c=savedInstanceState.getParcelableArrayList("c");
        a=savedInstanceState.getParcelableArrayList("list");
            adapter = new AppsAdapter(getActivity(), R.layout.rowlayout, a, app, c);
            setListAdapter(adapter);
            vl.setSelectionFromTop(savedInstanceState.getInt("index"), savedInstanceState.getInt("top"));

        }
    }
    public static int getToolbarHeight(Context context) {
        final TypedArray styledAttributes = context.getTheme().obtainStyledAttributes(
                new int[]{android.R.attr.actionBarSize});
        int toolbarHeight = (int) styledAttributes.getDimension(0, 0);
        styledAttributes.recycle();

        return toolbarHeight;
    }
    @Override
    public void onResume() {
        super.onResume();
    }

    public void onLongItemClick(final int position) {
        final MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity());
        if(theme1==1)
            builder.theme(Theme.DARK);
        builder.items(new String[]{utils.getString(getActivity(), R.string.open),utils.getString(getActivity(), R.string.backup), utils.getString(getActivity(), R.string.uninstall),
                utils.getString(getActivity(), R.string.properties),utils.getString(getActivity(), R.string.play),utils.getString(getActivity(),R.string.share)})
                .itemsCallback(new MaterialDialog.ListCallback() {

                    @Override
                    public void onSelection(MaterialDialog materialDialog, View view, int i, CharSequence s) {
                        switch (i) {
                            case 0:
                                Intent i1 = app.getActivity().getPackageManager().getLaunchIntentForPackage(c.get(position).packageName);
                                if (i1!= null)
                                    app.startActivity(i1);
                                else
                                    Toast.makeText(app.getActivity(),utils.getString(getActivity(),R.string.not_allowed), Toast.LENGTH_LONG).show();
                                break;

                            case 1:
                                Toast.makeText(getActivity(), utils.getString(getActivity(), R.string.copyingapk) + Environment.getExternalStorageDirectory().getPath() + "/app_backup", Toast.LENGTH_LONG).show();
                                ApplicationInfo info = c.get(position);
                                File f = new File(info.publicSourceDir);
                                ArrayList<String> a = new ArrayList<String>();
                                //a.add(info.publicSourceDir);
                                File dst = new File(Environment.getExternalStorageDirectory().getPath() + "/app_backup");
                                if(!dst.exists() || !dst.isDirectory())dst.mkdirs();
                                Intent intent = new Intent(getActivity(), CopyService.class);
                                //Toast.makeText(getActivity(), f.getParent(), Toast.LENGTH_LONG).show();

                                if (Build.VERSION.SDK_INT == 21) {
                                    a.add(f.getParent());
                                } else {
                                    a.add(f.getPath());
                                }
                                intent.putExtra("FILE_PATHS", a);
                                intent.putExtra("COPY_DIRECTORY", dst.getPath());
                                getActivity().startService(intent);
                                break;
                            case 2:
                                ArrayList<Layoutelements> arrayList = new ArrayList<Layoutelements>();
                                ApplicationInfo info1 = c.get(position);
                                ArrayList<Integer> arrayList1 = new ArrayList<Integer>();
                                arrayList1.add(position);
                                final File f1 = new File(info1.publicSourceDir);
                                //arrayList.add(utils.newElement(Icons.loadMimeIcon(getActivity(), f1.getPath(), false), f1.getPath(), null, null, utils.getSize(f1),"", false));
                                //utils.deleteFiles(arrayList, null, arrayList1);
                                if ((info1.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                                    // system package
                                    if(Sp.getBoolean("rootmode",false)) {
                                        MaterialDialog.Builder builder1 = new MaterialDialog.Builder(getActivity());
                                        if(theme1==1)
                                            builder1.theme(Theme.DARK);
                                        builder1.content(utils.getString(getActivity(), R.string.unin_system_apk))
                                                .title(utils.getString(getActivity(), R.string.warning))
                                                .negativeText(utils.getString(getActivity(), R.string.no))
                                                .positiveText(utils.getString(getActivity(), R.string.yes))
                                                .negativeColor(Color.parseColor(fabSkin))
                                                .positiveColor(Color.parseColor(fabSkin))
                                                .callback(new MaterialDialog.ButtonCallback() {
                                                    @Override
                                                    public void onNegative(MaterialDialog materialDialog) {

                                                        materialDialog.cancel();
                                                    }

                                                    @Override
                                                    public void onPositive(MaterialDialog materialDialog) {

                                                        ArrayList<File> files = new ArrayList<File>();
                                                        if (Build.VERSION.SDK_INT >= 21) {
                                                            String parent = f1.getParent();
                                                            if (!parent.equals("app") && !parent.equals("priv-app"))
                                                                files.add(new File(f1.getParent()));
                                                            else files.add(f1);
                                                        } else {
                                                            files.add(f1);
                                                        }
                                                        new DeleteTask(getActivity().getContentResolver(), getActivity()).execute(files);
                                                    }
                                                }).build().show();
                                    } else {
                                        Toast.makeText(getActivity(),utils.getString(getActivity(), R.string.enablerootmde),Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    unin(c.get(position).packageName);
                                }
                                break;
                            case 3:
                                startActivity(new Intent(
                                        android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                                        Uri.parse("package:" + c.get(position).packageName)));
                                break;
                            case 4:
                                Intent intent1 = new Intent(Intent.ACTION_VIEW);
                                intent1.setData(Uri.parse("market://details?id=" + c.get(position).packageName));
                                startActivity(intent1);
                                break;
                            case 5:
                                ArrayList<File> arrayList2=new ArrayList<File>();
                                arrayList2.add(new File(c.get(position).publicSourceDir));
                                utils.shareFiles(arrayList2,getActivity());
                        }
                    }
                }).title(a.get(position).getTitle()).build()
                .show();
    }

    @Override
    public void onSaveInstanceState(Bundle b) {
        super.onSaveInstanceState(b);
        if(vl!=null){
        b.putParcelableArrayList("c",c);
        b.putParcelableArrayList("list",a);
        int index = vl.getFirstVisiblePosition();
        View vi = vl.getChildAt(0);
        int top = (vi == null) ? 0 : vi.getTop();
        b.putInt("index", index);
        b.putInt("top", top);
    }}
    class LoadListTask extends AsyncTask<Void, Void, ArrayList<Layoutelements>> {

        protected ArrayList<Layoutelements> doInBackground(Void[] p1) {
            try {PackageManager p=getActivity().getPackageManager();
                List<ApplicationInfo> all_apps = p.getInstalledApplications(PackageManager.GET_META_DATA);


                for (ApplicationInfo object : all_apps) {


                    c.add(object);



                }
                Collections.sort(c, new AppsSorter(p));
                for (ApplicationInfo object:c)
                a.add(new Layoutelements(getActivity().getResources().getDrawable(R.drawable.ic_doc_apk_grid), object.loadLabel(getActivity().getPackageManager()).toString(), object.publicSourceDir,"","",utils.readableFileSize(new File(object.publicSourceDir).length()),false,"",false));

            } catch (Exception e) {
                //Toast.makeText(getActivity(), "" + e, Toast.LENGTH_LONG).show();
            }//ArrayAdapter<String> b=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,a);
            // TODO: Implement this method

            return a;
        }


        public LoadListTask() {

        }

        @Override
        protected void onPreExecute() {

        }


        @Override
        // Once the image is downloaded, associates it to the imageView
        protected void onPostExecute(ArrayList<Layoutelements> bitmap) {
            if (isCancelled()) {
                bitmap = null;

            }
            try {
                if (bitmap != null) {


                    adapter = new AppsAdapter(getActivity(), R.layout.rowlayout, bitmap, app, c);
                    setListAdapter(adapter);

                }
            } catch (Exception e) {
            }

        }
    }  // copy the .apk file to wherever

    public boolean unin(String pkg) {

        try {
            Intent intent = new Intent(Intent.ACTION_DELETE);
            intent.setData(Uri.parse("package:" + pkg));
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(getActivity(), "" + e, Toast.LENGTH_SHORT).show();
            e.printStackTrace();
            return false;
        }
        return true;
    }
} public class Main extends android.support.v4.app.Fragment {
    public File[] file;
    public ArrayList<Layoutelements> list;
    public ArrayList<SmbFile> smbFiles;
    public Recycleradapter adapter;
    public Futils utils;
    public boolean selection;
    public boolean results = false,smbMode=false;
    public ActionMode mActionMode;
    public SharedPreferences Sp;
    public Drawable folder,apk,darkimage,darkvideo;
    Resources res;
    public LinearLayout buttons;
    public int sortby, dsort, asc;

    public String home, current = Environment.getExternalStorageDirectory().getPath();
    Shortcuts sh;
    HashMap<String, Bundle> scrolls = new HashMap<String, Bundle>();
    Main ma = this;
    public HistoryManager history,hidden;
    IconUtils icons;
    public boolean rootMode,showHidden,circularImages,showPermissions,showSize,showLastModified;
    View footerView;
    public LinearLayout pathbar;
    public CountDownTimer timer;
    private View rootView;
    public android.support.v7.widget.RecyclerView  listView;
    public boolean gobackitem,islist,showThumbs,coloriseIcons,showDividers;
    public IconHolder ic;
    public MainActivity mainActivity;
    public boolean showButtonOnStart = false;
    public String skin, fabSkin,iconskin;
    public int skinselection;
    public int theme;
    public int theme1;
    public float[] color;
    public ColorMatrixColorFilter colorMatrixColorFilter;
    public Animation animation,animation1;
    public String year,goback;
    ArrayList<String> hiddenfiles;
    String Intentpath,itemsstring;
    int no;
    TabHandler tabHandler;
    boolean savepaths;
    LinearLayoutManager mLayoutManager;
    GridLayoutManager mLayoutManagerGrid;
    public SwipeRefreshLayout mSwipeRefreshLayout;
    boolean addheader=false;
    StickyRecyclerHeadersDecoration headersDecor;
    DividerItemDecoration dividerItemDecoration;
    public int paddingTop;
    int mToolbarHeight,hidemode;
    View mToolbarContainer;
    public int skin_color,icon_skin_color;
    boolean SmbAnonym=false;
    String smbUser,smbPass;
    public String smbPath;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mainActivity=(MainActivity)getActivity();
        no=getArguments().getInt("no", 1);
        home=getArguments().getString("home");
        current=getArguments().getString("lastpath");
        tabHandler=new TabHandler(getActivity(),null,null,1);
        Sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        savepaths=Sp.getBoolean("savepaths", true);
        skin = Sp.getString("skin_color", "#3f51b5");
        fabSkin = Sp.getString("fab_skin_color", "#e91e63");
        iconskin=Sp.getString("icon_skin_color", skin);
        skin_color=Color.parseColor(skin);
        icon_skin_color=Color.parseColor(iconskin);
        sh = new Shortcuts(getActivity());
        islist = Sp.getBoolean("view", true);
        Calendar calendar = Calendar.getInstance();
        year=(""+calendar.get(Calendar.YEAR)).substring(2, 4);
        theme=Integer.parseInt(Sp.getString("theme", "0"));
        theme1 = theme==2 ? PreferenceUtils.hourOfDay() : theme;
        hidemode=Sp.getInt("hidemode", 0);
        showPermissions=Sp.getBoolean("showPermissions", false);
        showSize=Sp.getBoolean("showFileSize",false);
        showDividers=Sp.getBoolean("showDividers",true);
        gobackitem=Sp.getBoolean("goBack_checkbox", false);
        circularImages=Sp.getBoolean("circularimages",true);
        showLastModified=Sp.getBoolean("showLastModified",true);
        icons = new IconUtils(Sp, getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.main_frag, container, false);
        listView = (android.support.v7.widget.RecyclerView) rootView.findViewById(R.id.listView);
        if(getArguments()!=null)
        Intentpath=getArguments().getString("path");
        animation = AnimationUtils.loadAnimation(getActivity(), R.anim.load_list_anim);
        animation1 = AnimationUtils.loadAnimation(getActivity(), R.anim.fab_newtab);
        mToolbarContainer=getActivity().findViewById(R.id.lin);
        buttons = (LinearLayout) getActivity().findViewById(R.id.buttons);
        pathbar = (LinearLayout) getActivity().findViewById(R.id.pathbar);
        showThumbs=Sp.getBoolean("showThumbs", true);
        ic=new IconHolder(getActivity(),showThumbs,!islist);
        res = getResources();
        goback=res.getString(R.string.goback);
        itemsstring=res.getString(R.string.items);
        apk=res.getDrawable(R.drawable.ic_doc_apk_grid);
        if(theme1==1) {

            mainActivity.getWindow().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.holo_dark_background)));
        } else {

            if(islist)  mainActivity.getWindow().setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.background_light)));

        } listView.setHasFixedSize(true);
        mLayoutManager=new LinearLayoutManager(getActivity());
        int columns=Integer.parseInt(Sp.getString("columns","3"));
        mLayoutManagerGrid=new GridLayoutManager(getActivity(),columns);
        if (islist) {
            listView.setLayoutManager(mLayoutManager);
        } else {
            listView.setLayoutManager(mLayoutManagerGrid);
        }
        mToolbarContainer.setBackgroundColor(skin_color);
     //   listView.setPadding(listView.getPaddingLeft(), paddingTop, listView.getPaddingRight(), listView.getPaddingBottom());
        return rootView;
    }public int dpToPx(int dp) {
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
        return px;
    }
    public static int getToolbarHeight(Context context) {
        final TypedArray styledAttributes = context.getTheme().obtainStyledAttributes(
                new int[]{android.R.attr.actionBarSize});
        int toolbarHeight = (int) styledAttributes.getDimension(0, 0);
        styledAttributes.recycle();

        return toolbarHeight;
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(false);
        mainActivity = (MainActivity) getActivity();
        utils = new Futils();
        String x=getSelectionColor();
        skinselection=Color.parseColor(x);
        color=calculatevalues(x);
        ColorMatrix colorMatrix = new ColorMatrix(calculatefilter(color));
        colorMatrixColorFilter = new ColorMatrixColorFilter(colorMatrix);
        history = new HistoryManager(getActivity(), "Table1");
        hidden = new HistoryManager(getActivity(), "Table2");
        hiddenfiles=hidden.readTable();
        rootMode = Sp.getBoolean("rootmode", false);
        showHidden=Sp.getBoolean("showHidden",false);
        coloriseIcons=Sp.getBoolean("coloriseIcons",false);
        if(islist){
            folder = res.getDrawable(R.drawable.ic_grid_folder_new);}
        else{folder = res.getDrawable(R.drawable.ic_grid_folder1);}
        folder = res.getDrawable(R.drawable.ic_grid_folder_new);
        getSortModes();
        darkimage=res.getDrawable(R.drawable.ic_doc_image_dark);
        darkvideo=res.getDrawable(R.drawable.ic_doc_video_dark);
        this.setRetainInstance(false);
        File f;
        if(savepaths)
            f=new File(current);
        else f=new File(home);
        mainActivity.initiatebbar();

        // use a linear layout manager
        footerView=getActivity().getLayoutInflater().inflate(R.layout.divider, null);
           mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.activity_main_swipe_refresh_layout);

        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadlist(new File(current),false);
            }
        });
        mToolbarHeight=getToolbarHeight(getActivity());
        paddingTop = (mToolbarHeight) + dpToPx(72);
        if(hidemode==2)mToolbarHeight=paddingTop;
        mToolbarContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                    mToolbarContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
                else {
                    mToolbarContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
                paddingTop=mToolbarContainer.getHeight();

                if(hidemode!=2)mToolbarHeight=mainActivity.toolbar.getHeight();
            }

        });
        mSwipeRefreshLayout.setColorSchemeColors(Color.parseColor(fabSkin));
        mSwipeRefreshLayout.setProgressViewOffset(true, paddingTop, paddingTop + dpToPx(72));

        if (savedInstanceState == null){
            if(Intentpath!=null) {
                File file1=new File(Intentpath);
                if(file1.isDirectory()) {

                    loadlist(file1,false);
                }
                else {
                    utils.openFile(file1, mainActivity);
                    loadlist(f,false);
                }
            } else {

                loadlist(f, false);
            }
        } else {
            Bundle b = new Bundle();
            String cur = savedInstanceState.getString("current");
            if (cur != null) {
                b.putInt("index", savedInstanceState.getInt("index"));
                b.putInt("top", savedInstanceState.getInt("top"));
                scrolls.put(cur, b);
                retreiveSmbFromSavedInstance(savedInstanceState);
                list = savedInstanceState.getParcelableArrayList("list");
                if (savedInstanceState.getBoolean("results")) {
                    try {
                        createViews(list, true, new File(current));
                        ((TextView) ma.pathbar.findViewById(R.id.pathname)).setText(ma.utils.getString(ma.getActivity(), R.string.searchresults));
                        results = true;
                    } catch (Exception e) {
                    }
                }else{
                    createViews(list, true, new File(cur));
                }
                if (savedInstanceState.getBoolean("selection")) {

                    for (int i : savedInstanceState.getIntegerArrayList("position")) {
                        adapter.toggleChecked(i);
                    }
                }
            }
        }
     }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        int index;
        View vi;
        if(listView!=null){
            if (islist) {

                index = (mLayoutManager).findFirstVisibleItemPosition();
                vi = listView.getChildAt(0);
            } else {
                index =  (mLayoutManagerGrid).findFirstVisibleItemPosition();
                vi = listView.getChildAt(0);
            }
            int top = (vi == null) ? 0 : vi.getTop();
            outState.putInt("index", index);
            outState.putInt("top", top);
            outState.putParcelableArrayList("list", list);
            outState.putString("current", current);
            outState.putBoolean("selection", selection);
            if (selection) {
                outState.putIntegerArrayList("position", adapter.getCheckedItemPositions());
            }
            if(results){
                outState.putBoolean("results", results);
            }
            if(smbMode)
                addSmbToSavedInstance(outState,smbUser,smbPass,smbFiles,SmbAnonym);
        }}

    public void home() {
        ma.loadlist(new File(ma.home), false);
    }



    public void onListItemClicked(int position, View v) {
        if (results) {
            String path = list.get(position).getDesc();
            if(selection)adapter.toggleChecked(position);
            else{

            final File f = new File(path);
            if (list.get(position).isDirectory()) {

                loadlist(f, false);
                results = false;
            } else {
                if (mainActivity.mReturnIntent) {
                    returnIntentResults(f);
                } else
                utils.openFile(f, (MainActivity) getActivity());
            }}
        }else if(smbMode){
            if(selection)adapter.toggleChecked(position);
            else{Toast.makeText(getActivity(),"Go",Toast.LENGTH_LONG).show();
                    loadSmblist(smbFiles.get(position), false);}
        } else if (selection == true) {
            if(!list.get(position).getSize().equals(goback)){
                adapter.toggleChecked(position);
            }else{selection = false;
                if(mActionMode!=null)
                    mActionMode.finish();
                mActionMode = null;}

        } else {
            if(!list.get(position).getSize().equals(goback)){

                String path;
                Layoutelements l=list.get(position);

                if(!l.hasSymlink()){

                    path= l.getDesc();
                }
                else {

                    path=l.getSymlink();
                }

                final File f = new File(path);

                if (l.isDirectory()) {

                    computeScroll();
                    loadlist(f, false);
                } else {
                    if (mainActivity.mReturnIntent) {
                        returnIntentResults(f);
                    } else {

                        utils.openFile(f, (MainActivity) getActivity());
                    }
                }

            } else {

                goBackItemClick();

            }
        }
    }

    private void returnIntentResults (File file) {
        mainActivity.mReturnIntent = false;

        Intent intent = new Intent();
        if (mainActivity.mRingtonePickerIntent) {

            Log.d("pickup", "ringtone");
            Uri uri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());

            intent.putExtra(android.media.RingtoneManager.EXTRA_RINGTONE_PICKED_URI, uri);
            getActivity().setResult(getActivity().RESULT_OK, intent);
            getActivity().finish();
        } else {

            Log.d("pickup", "file");
            intent.setData(Uri.fromFile(file));
            getActivity().setResult(getActivity().RESULT_OK, intent);
            getActivity().finish();
        }
    }

    public void loadlist(final File f, boolean back) {
        if(mActionMode!=null){mActionMode.finish();}
        new LoadList(back, ma).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, f);

        try {
            animation = AnimationUtils.loadAnimation(getActivity(), R.anim.load_list_anim);
        } catch (Exception e) {
            e.printStackTrace();
        }

        listView.setAnimation(animation);
    }
    public void loadSmblist(final SmbFile f, boolean back) {
        if(mActionMode!=null){mActionMode.finish();}
        new LoadSmbList(back, ma).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, f);

        try {
            animation = AnimationUtils.loadAnimation(getActivity(), R.anim.load_list_anim);
        } catch (Exception e) {
            e.printStackTrace();
        }

        listView.setAnimation(animation);
    }

    @SuppressWarnings("unchecked")
    public void loadsearchlist(ArrayList<String[]> f) {

        new LoadSearchList(ma).execute(f);

    }


    public void createViews(ArrayList<Layoutelements> bitmap, boolean back, File f) {
        try {
            if (bitmap != null) {
                if(gobackitem)
                if (!f.getPath().equals("/")) {
                    if (bitmap.size() == 0 || !bitmap.get(0).getSize().equals(goback))
                        bitmap.add(0, utils.newElement(res.getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha), "..", "", "", goback,false, true,""));
                }
                adapter = new Recycleradapter(ma,
                        bitmap, ma.getActivity());
                mSwipeRefreshLayout.setRefreshing(false);
                try {    listView.setAdapter(adapter);
                    if(!addheader && islist){
                       listView.removeItemDecoration(dividerItemDecoration);
                        listView.removeItemDecoration(headersDecor);
                        addheader=true;}
                    if(addheader && islist){
                            dividerItemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST,showDividers);
                            listView.addItemDecoration(dividerItemDecoration);

                    headersDecor = new StickyRecyclerHeadersDecoration(adapter);
                    listView.addItemDecoration(headersDecor);addheader=false;}
                    results = false;
                    current = f.getPath();
                    if (back) {
                        if (scrolls.containsKey(current)) {
                            Bundle b = scrolls.get(current);
                            if(islist)
                            mLayoutManager.scrollToPositionWithOffset(b.getInt("index"),b.getInt("top"));
                        else    mLayoutManagerGrid.scrollToPositionWithOffset(b.getInt("index"),b.getInt("top"));
                        }
                    }
                    //floatingActionButton.show();
                    mainActivity.updatepaths();
                    listView.setOnScrollListener(new HidingScrollListener(mToolbarHeight,hidemode) {

                        @Override
                        public void onMoved(int distance) {
                            mToolbarContainer.setTranslationY(-distance);
                        }

                        @Override
                        public void onShow() {
                            mToolbarContainer.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
                        }

                        @Override
                        public void onHide() {
                            mToolbarContainer.findViewById(R.id.lin).animate().translationY(-mToolbarHeight).setInterpolator(new AccelerateInterpolator(2)).start();
                        }

                    });
                    if (buttons.getVisibility() == View.VISIBLE) mainActivity.bbar(this);

                    mainActivity.updateDrawer(current);
                    mainActivity.updatepager();

                    } catch (Exception e) {
                }
            } else {//Toast.makeText(getActivity(),res.getString(R.string.error),Toast.LENGTH_LONG).show();
                loadlist(new File(current), true);
            }
        } catch (Exception e) {
        }

    }


    public ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
        private void hideOption(int id, Menu menu) {
            MenuItem item = menu.findItem(id);
            item.setVisible(false);
        }

        private void showOption(int id, Menu menu) {
            MenuItem item = menu.findItem(id);
            item.setVisible(true);
        }
        public void initMenu(Menu menu) {
            /*menu.findItem(R.id.cpy).setIcon(icons.getCopyDrawable());
            menu.findItem(R.id.cut).setIcon(icons.getCutDrawable());
            menu.findItem(R.id.delete).setIcon(icons.getDeleteDrawable());
            menu.findItem(R.id.all).setIcon(icons.getAllDrawable());*/
        }
        View v;
        // called when the action mode is created; startActionMode() was called
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // Inflate a menu resource providing context menu items
            MenuInflater inflater = mode.getMenuInflater();
            v=getActivity().getLayoutInflater().inflate(R.layout.actionmode,null);
            try {
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
                v.setMinimumWidth(getActivity().findViewById(R.id.tab_spinner).getWidth());
            } catch (Exception e) {
                e.printStackTrace();
            }
            mode.setCustomView(v);
            mainActivity.setPagingEnabled(false);
            // assumes that you have "contexual.xml" menu resources
            inflater.inflate(R.menu.contextual, menu);
            initMenu(menu);
            hideOption(R.id.addshortcut,menu);
            hideOption(R.id.sethome, menu);
            hideOption(R.id.rename, menu);
            hideOption(R.id.share, menu);
            hideOption(R.id.about, menu);
            hideOption(R.id.openwith, menu);
            hideOption(R.id.ex, menu);
            if(mainActivity.mReturnIntent)
            showOption(R.id.openmulti,menu);
            //hideOption(R.id.setringtone,menu);
            mode.setTitle(utils.getString(getActivity(), R.string.select));
            /*if(Build.VERSION.SDK_INT<19)
                getActivity().findViewById(R.id.action_bar).setVisibility(View.GONE);*/
           // rootView.findViewById(R.id.buttonbarframe).setBackgroundColor(res.getColor(R.color.toolbar_cab));
            ObjectAnimator anim = ObjectAnimator.ofInt(getActivity().findViewById(R.id.buttonbarframe), "backgroundColor", skin_color, res.getColor(R.color.holo_dark_action_mode));
            anim.setDuration(0);
            anim.setEvaluator(new ArgbEvaluator());
            anim.start();
            if (Build.VERSION.SDK_INT >= 21) {

                Window window = getActivity().getWindow();
                if(mainActivity.colourednavigation)
                    window.setNavigationBarColor(res.getColor(android.R.color.black));
            }
            return true;
        }

        // the following method is called each time
        // the action mode is shown. Always called after
        // onCreateActionMode, but
        // may be called multiple times if the mode is invalidated.
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            ArrayList<Integer> positions = adapter.getCheckedItemPositions();
            TextView textView1 = (TextView) v.findViewById(R.id.item_count);
            textView1.setText(positions.size() + "");
            textView1.setOnClickListener(null);
            hideOption(R.id.openmulti,menu);
            if(mainActivity.mReturnIntent)
                if(Build.VERSION.SDK_INT>=16)
            showOption(R.id.openmulti, menu);
            //tv.setText(positions.size());
            if(!results)
            {hideOption(R.id.openparent,menu);
                if (positions.size() == 1) {
                showOption(R.id.addshortcut,menu);
                showOption(R.id.permissions, menu);

                showOption(R.id.openwith, menu);
                showOption(R.id.about, menu);
                showOption(R.id.share,menu);
                showOption(R.id.rename, menu);

                File x = new File(list.get(adapter.getCheckedItemPositions().get(0))

                        .getDesc());

                if (x.isDirectory()) {
                    hideOption(R.id.openwith,menu);
                    showOption(R.id.sethome, menu);
                    hideOption(R.id.share,menu);
                    hideOption(R.id.openmulti, menu);
                } else if (x.getName().toLowerCase().endsWith(".zip") || x.getName().toLowerCase().endsWith(".jar") || x.getName().toLowerCase().endsWith(".apk") || x.getName().toLowerCase().endsWith(".rar")|| x.getName().toLowerCase().endsWith(".tar")|| x.getName().toLowerCase().endsWith(".tar.gz")) {

                    showOption(R.id.ex, menu);

                    if(mainActivity.mReturnIntent)
                        if(Build.VERSION.SDK_INT>=16)
                    showOption(R.id.openmulti,menu);
                }
            } else {
                try {
                    if(mainActivity.mReturnIntent)
                        if(Build.VERSION.SDK_INT>=16)showOption(R.id.openmulti,menu);
                    for (int c : adapter.getCheckedItemPositions()) {
                        File x = new File(list.get(c).getDesc());
                        if (x.isDirectory()) {
                            hideOption(R.id.share, menu);
                            hideOption(R.id.openmulti,menu);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                hideOption(R.id.ex, menu);

                hideOption(R.id.sethome, menu);

                hideOption(R.id.openwith, menu);

                //hideOption(R.id.setringtone, menu);

                hideOption(R.id.permissions, menu);

                hideOption(R.id.about, menu);

            }}else {
                if (positions.size() == 1) {
                    showOption(R.id.addshortcut,menu);
                    showOption(R.id.permissions, menu);
                    showOption(R.id.openparent,menu);
                    showOption(R.id.openwith, menu);
                    showOption(R.id.about, menu);
                    showOption(R.id.share,menu);
                    showOption(R.id.rename, menu);

                    File x = new File(list.get(adapter.getCheckedItemPositions().get(0))

                            .getDesc());

                    if (x.isDirectory()) {
                        hideOption(R.id.openwith,menu);
                        showOption(R.id.sethome, menu);
                        hideOption(R.id.share,menu);
                        hideOption(R.id.openmulti,menu);
                    } else if (x.getName().toLowerCase().endsWith(".zip") || x.getName().toLowerCase().endsWith(".jar") || x.getName().toLowerCase().endsWith(".apk") || x.getName().toLowerCase().endsWith(".rar")|| x.getName().toLowerCase().endsWith(".tar")|| x.getName().toLowerCase().endsWith(".tar.gz")) {

                        showOption(R.id.ex, menu);

                        if(mainActivity.mReturnIntent)
                            if(Build.VERSION.SDK_INT>=16)
                                showOption(R.id.openmulti,menu);
                    }
                } else {
                    hideOption(R.id.openparent,menu);

                    if(mainActivity.mReturnIntent)
                        if(Build.VERSION.SDK_INT>=16)
                            showOption(R.id.openmulti,menu);
                    try {
                        for (int c : adapter.getCheckedItemPositions()) {
                            File x = new File(list.get(c).getDesc());
                            if (x.isDirectory()) {
                                hideOption(R.id.share, menu);
                                hideOption(R.id.openmulti,menu);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    hideOption(R.id.ex, menu);

                    hideOption(R.id.sethome, menu);

                    hideOption(R.id.openwith, menu);

                    //hideOption(R.id.setringtone, menu);

                    hideOption(R.id.permissions, menu);

                    hideOption(R.id.about, menu);

                }
            }

            return false; // Return false if nothing is done
        }

        // called when the user selects a contextual menu item
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            computeScroll();
            ArrayList<Integer> plist = adapter.getCheckedItemPositions();
            switch (item.getItemId()) {
                case R.id.openmulti:
                    if(Build.VERSION.SDK_INT>=16){
                    Intent intentresult=new Intent();
                    ArrayList<Uri> resulturis=new ArrayList<Uri>();
                        for(int k:plist){
                            try {
                                resulturis.add(Uri.fromFile(new File(list.get(k).getDesc())));
                            } catch (Exception e) {

                            }
                        }
                    final ClipData clipData = new ClipData(
                            null, new String[]{"*/*"}, new ClipData.Item(resulturis.get(0)));
                    for (int i = 1; i < resulturis.size(); i++) {
                        clipData.addItem(new ClipData.Item(resulturis.get(i)));
                    }
                    intentresult.setClipData(clipData);
                    mode.finish();
                    getActivity().setResult(getActivity().RESULT_OK, intentresult);
                    getActivity().finish();}
                    return true;
                case R.id.sethome:
                    int pos = plist.get(0);
                        home = list.get(pos).getDesc();
                    Toast.makeText(getActivity(),
                            utils.getString(getActivity(), R.string.newhomedirectory) + " " + list.get(pos).getTitle(),
                            Toast.LENGTH_LONG).show();
                    mainActivity.updatepaths();
                    mode.finish();
                    return true;
                case R.id.about:
                    String x;
                        x=list.get((plist.get(0))).getDesc();
                    utils.showProps(new File(x), ma,rootMode);
                    mode.finish();
                    return true;
                /*case R.id.setringtone:
                    File fx;
                    if(results)
                        fx=new File(slist.get((plist.get(0))).getDesc());
                        else
                        fx=new File(list.get((plist.get(0))).getDesc());

                    ContentValues values = new ContentValues();
                    values.put(MediaStore.MediaColumns.DATA, fx.getAbsolutePath());
                    values.put(MediaStore.MediaColumns.TITLE, "Amaze");
                    values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
                    //values.put(MediaStore.MediaColumns.SIZE, fx.);
                    values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
                    values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
                    values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
                    values.put(MediaStore.Audio.Media.IS_ALARM, false);
                    values.put(MediaStore.Audio.Media.IS_MUSIC, false);

                    Uri uri = MediaStore.Audio.Media.getContentUriForPath(fx.getAbsolutePath());
                    Uri newUri = getActivity().getContentResolver().insert(uri, values);
                    try {
                        RingtoneManager.setActualDefaultRingtoneUri(getActivity(), RingtoneManager.TYPE_RINGTONE, newUri);
                        //Settings.System.putString(getActivity().getContentResolver(), Settings.System.RINGTONE, newUri.toString());
                        Toast.makeText(getActivity(), "Successful" + fx.getAbsolutePath(), Toast.LENGTH_LONG).show();
                    } catch (Throwable t) {

                        Log.d("ringtone", "failed");
                    }
                    return true;*/
                case R.id.delete:
                        utils.deleteFiles(list,ma, plist);


                    return true;
                case R.id.share:
                    ArrayList<File> arrayList=new ArrayList<File>();
                        for(int i:plist){
                            arrayList.add(new File(list.get(i).getDesc()));
                        }
                    utils.shareFiles(arrayList,getActivity());
                    return true;
                case R.id.openparent:
                    loadlist(new File(list.get(plist.get(0)).getDesc()).getParentFile(),false);
                    return true;
                case R.id.all:
                    if (adapter.areAllChecked(current)) {
                        adapter.toggleChecked(false,current);
                    } else {
                        adapter.toggleChecked(true,current);
                    }
                    mode.invalidate();

                    return true;
                case R.id.rename:

                    final ActionMode m = mode;
                    final File f;
                      f= new File(list.get(
                            (plist.get(0))).getDesc());
                    View dialog = getActivity().getLayoutInflater().inflate(
                            R.layout.dialog, null);
                    MaterialDialog.Builder a = new MaterialDialog.Builder(getActivity());
                    final EditText edit = (EditText) dialog
                            .findViewById(R.id.newname);
                    edit.setText(f.getName());
                    a.customView(dialog, true);
                    if(theme1==1)
                        a.theme(Theme.DARK);
                    a.title(utils.getString(getActivity(), R.string.rename));

                    a.callback(new MaterialDialog.ButtonCallback() {
                        @Override
                        public void onPositive(MaterialDialog materialDialog) {

                            boolean b = utils.rename(f, edit.getText()
                                    .toString(),rootMode);
                            m.finish();
                            updateList();
                            if (b) {
                                Toast.makeText(getActivity(),
                                        utils.getString(getActivity(), R.string.renamed),
                                        Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(getActivity(),
                                        utils.getString(getActivity(), R.string.renameerror),
                                        Toast.LENGTH_LONG).show();

                            }
                        }

                        @Override
                        public void onNegative(MaterialDialog materialDialog) {

                            materialDialog.cancel();
                        }
                    });
                    a.positiveText(R.string.save);
                    a.negativeText(R.string.cancel);
                    a.positiveColor(Color.parseColor(fabSkin));
                    a.negativeColor(Color.parseColor(fabSkin));
                    a.build().show();
                    mode.finish();
                    return true;
                case R.id.hide:
                        for (int i1 = 0; i1 < plist.size(); i1++) {
                            hide(list.get(plist.get(i1)).getDesc());
                        }
                    updateList();mode.finish();
                    return true;
                case R.id.book:
                      for (int i1 = 0; i1 < plist.size(); i1++) {
                            try {
                                sh.addS(new File(list.get(plist.get(i1)).getDesc()));
                            } catch (Exception e) {
                            }
                        }
                    mainActivity.updateDrawer();
                    Toast.makeText(getActivity(), utils.getString(getActivity(), R.string.bookmarksadded), Toast.LENGTH_LONG).show();
                    mode.finish();
                    return true;
                case R.id.ex:
                    Intent intent = new Intent(getActivity(), ExtractService.class);
                    intent.putExtra("zip", list.get((plist.get(0))).getDesc());
                    getActivity().startService(intent);
                    mode.finish();
                    return true;
                case R.id.cpy:
                    mainActivity.MOVE_PATH=null;
                    ArrayList<String> copies = new ArrayList<String>();
                    for (int i2 = 0; i2 < plist.size(); i2++) {
                    copies.add(list.get(plist.get(i2)).getDesc());
                    }
                    mainActivity.COPY_PATH = copies;
                    mainActivity.supportInvalidateOptionsMenu();
                    mode.finish();
                    return true;
                case R.id.cut:
                    mainActivity.COPY_PATH=null;
                    ArrayList<String> copie = new ArrayList<String>();
                    for (int i3 = 0; i3 < plist.size(); i3++) {
                    copie.add(list.get(plist.get(i3)).getDesc());
                    }
                    mainActivity.MOVE_PATH = copie;
                    mainActivity.supportInvalidateOptionsMenu();
                    mode.finish();
                    return true;
                case R.id.compress:
                    ArrayList<String> copies1 = new ArrayList<String>();
                    for (int i4 = 0; i4 < plist.size(); i4++) {
                    copies1.add(list.get(plist.get(i4)).getDesc());}
                    utils.showNameDialog((MainActivity) getActivity(), copies1, current);
                    mode.finish();
                    return true;
                case R.id.openwith:
                    utils.openunknown(new File(list.get((plist.get(0))).getDesc()), getActivity(), true);
                    return true;
                case R.id.permissions:
                    utils.setPermissionsDialog(list.get(plist.get(0)),ma);
                    mode.finish();
                    return true;
                case R.id.addshortcut:
                    addShortcut(list.get(plist.get(0)));
                    mode.finish();return true;
                default:
                    return false;
            }
        }

        // called when the user exits the action mode
        public void onDestroyActionMode(ActionMode mode) {
            mActionMode = null;
            selection = false;
            if(!results)adapter.toggleChecked(false, current);
            else adapter.toggleChecked(false);
            mainActivity.setPagingEnabled(true);
            ObjectAnimator anim = ObjectAnimator.ofInt(getActivity().findViewById(R.id.buttonbarframe), "backgroundColor", res.getColor(R.color.holo_dark_action_mode), skin_color);
            anim.setDuration(0);
            anim.setEvaluator(new ArgbEvaluator());
            anim.start();
            if (Build.VERSION.SDK_INT >= 21) {

                Window window = getActivity().getWindow();
                if(mainActivity.colourednavigation)window.setNavigationBarColor(mainActivity.skinStatusBar);
            }
        }
    };

    public void computeScroll() {
        View vi = listView.getChildAt(0);
        int top = (vi == null) ? 0 : vi.getTop();
        int index;if(islist)
        index= mLayoutManager.findFirstVisibleItemPosition();
        else index=mLayoutManagerGrid.findFirstVisibleItemPosition();
        Bundle b = new Bundle();
        b.putInt("index", index);
        b.putInt("top", top);
        scrolls.put(current, b);
    }

    public void goBack() {
        File f = new File(current);
        if (!results) {
            if(selection){
            System.out.println("adapter checked false");
                adapter.toggleChecked(false);}
            else{
            if(current.equals("/") || current.equals(home))
                mainActivity.exit();
                else if (utils.canGoBack(f) ) {
                loadlist(f.getParentFile(), true);
            }else mainActivity.exit();}
        } else {
            loadlist(f, true);
        }
    }
    public void goBackItemClick() {
        File f = new File(current);
        if (!results) {
            if(selection){
                adapter.toggleChecked(false);}
            else{
                if(current.equals("/"))
                    mainActivity.exit();
                else if (utils.canGoBack(f) ) {
                    loadlist(f.getParentFile(), true);
                }else mainActivity.exit();}
        } else {
            loadlist(f, true);
        }
    }
    private BroadcastReceiver receiver2 = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            updateList();
        }
    };
    public void updateList(){
        computeScroll();
        ic.cleanup();
        loadlist(new File(current), true);}

    public void getSortModes() {
        int t = Integer.parseInt(Sp.getString("sortby", "0"));
        if (t <= 3) {
            sortby = t;
            asc = 1;
        } else if (t > 3) {
            asc = -1;
            sortby = t - 4;
        }
        dsort = Integer.parseInt(Sp.getString("dirontop", "0"));

    }

    @Override
    public void onResume() {
        super.onResume();
        (getActivity()).registerReceiver(receiver2, new IntentFilter("loadlist"));
    }

    @Override
    public void onPause() {
        super.onPause();
        (getActivity()).unregisterReceiver(receiver2);
    }
    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        tabHandler.close();
        if(history!=null)
            history.end();
        if(hidden!=null)
            hidden.end();
    }
    @Override
    public void onStart() {
        super.onStart();
        history = new HistoryManager(getActivity(), "Table1");
    }

    public ArrayList<Layoutelements> addToSmb(SmbFile[] mFile) throws SmbException {
        Log.e("Connected",mFile.length+"");
        ArrayList<Layoutelements> a = new ArrayList<Layoutelements>();
        smbFiles=new ArrayList<SmbFile>();
        for (int i = 0; i < mFile.length; i++) {
            smbFiles.add(mFile[i]);
                if (mFile[i].isDirectory()) {
                    a.add(new Layoutelements(folder,mFile[i].getName(), mFile[i].getPath(),"","","",false,"",true));
                } else {
                    try {
                        a.add(new Layoutelements(Icons.loadMimeIcon(getActivity(), mFile[i].getPath(),!islist),mFile[i].getName(), mFile[i].getPath(),"","",utils.readableFileSize(mFile[i].length()), false, "",false));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }}
            }
        Log.e("Connected",a.size()+"Size");
        return a;
    }
    public ArrayList<Layoutelements> addTo(ArrayList<String[]> mFile) {
        ArrayList<Layoutelements> a = new ArrayList<Layoutelements>();
        for (int i = 0; i < mFile.size(); i++) {
            String[] ele=mFile.get(i);
            File f=new File(ele[0]);
            String size="";
            if(!hiddenfiles.contains(ele[0])){
                if (isDirectory(ele)) {
                    if(!ele[5].trim().equals("") && !ele[5].toLowerCase().trim().equals("null"))size=ele[5]+" "+itemsstring;
                    else size="";
                    a.add(utils.newElement(folder, f.getPath(),mFile.get(i)[2],mFile.get(i)[1],size,true,false,ele[4]));

                } else {

                    try {
                        if(!ele[5].trim().equals("") && !ele[5].toLowerCase().trim().equals("null"))size=utils.readableFileSize(Long.parseLong(ele[5]));
                        else size="";
                    } catch (NumberFormatException e) {
                        //e.printStackTrace();
                    }
                    try {
                        a.add(utils.newElement(Icons.loadMimeIcon(getActivity(), f.getPath(),!islist), f.getPath(),mFile.get(i)[2],mFile.get(i)[1],size,false,false,ele[4]));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }}
            }
        }
        return a;
    }

    public boolean isDirectory(String[] path){
        if(rootMode)
            if(path[1].length()!=0)return new File(path[0]).isDirectory();
               else return path[3].equals("-1");
        else
            return new File(path[0]).isDirectory();
    }


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


    }

    void addSmbToSavedInstance(Bundle savedInstance, String user, String pass, ArrayList<SmbFile> list, boolean anonym) {
        savedInstance.putBoolean("SmbMode", smbMode);
        savedInstance.putString("SmbPath",smbPath);
        if (!anonym) {
            savedInstance.putString("SmbUser", user);
            savedInstance.putString("SmbPass", pass);
            savedInstance.putBoolean("SmbAnonym", false);
        } else savedInstance.putBoolean("SmbAnonym", true);
        ArrayList<String> stringArrayList = new ArrayList<>();
        for (SmbFile smbFile : list) {
            stringArrayList.add(smbFile.getPath());
        }
        savedInstance.putStringArrayList("SmbFileList", stringArrayList);
    }

    void retreiveSmbFromSavedInstance(Bundle savedInstance) {
        smbMode = savedInstance.getBoolean("SmbMode");
        if (!smbMode) return;
        smbPath=savedInstance.getString("SmbPath");
        SmbAnonym = savedInstance.getBoolean("SmbAnonym");
        ArrayList<String> stringArrayList = savedInstance.getStringArrayList("SmbFileList");
        smbFiles=new ArrayList<SmbFile>();
        try {
            if(SmbAnonym) {
             for(String a:stringArrayList)
                 smbFiles.add( new SmbFile(a,NtlmPasswordAuthentication.ANONYMOUS));
            }else{
                NtlmPasswordAuthentication auth1 = new NtlmPasswordAuthentication(
                        null,smbUser= savedInstance.getString("SmbUser"),smbPass=savedInstance.getString("SmbPass"));
                for(String a:stringArrayList)
                    smbFiles.add( new SmbFile(a,auth1));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
       public SmbFile connectingWithSmbServer(String[] auth,boolean anonym) {
        try {
            String yourPeerIP=auth[0];
            String path = "smb://" + yourPeerIP;
            smbPath=path;
            SmbFile smbFile;
            if(anonym){
                SmbAnonym=true;
               smbFile = new SmbFile(path,NtlmPasswordAuthentication.ANONYMOUS);
            }
            else {
                SmbAnonym=false;
                smbUser=auth[1];
                smbPass=auth[2];
                NtlmPasswordAuthentication auth1 = new NtlmPasswordAuthentication(
                        null, auth[1], auth[2]);
                 smbFile = new SmbFile(path, auth1);
            }return smbFile;
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Connected", e.getMessage());
            return null;
        }
    }
    public void updatehiddenfiles(){
        hiddenfiles=hidden.readTable();
    }
    public void initPoppyViewListeners(View poppy){
/*
        ImageView imageView = ((ImageView)poppy.findViewById(R.id.overflow));
        showPopup(imageView);
        final ImageView homebutton=(ImageView)poppy.findViewById(R.id.home);
        homebutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                home();if(mActionMode!=null){mActionMode.finish();}
            }
        });
        ImageView imageView1 = ((ImageView)poppy.findViewById(R.id.search));
        imageView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                search();
                if (mActionMode != null) {
                    mActionMode.finish();
                }
            }
        });*/
    }

    public void hide(String path){
        hidden.addPath(path);
        hiddenfiles=hidden.readTable();
        if(new File(path).isDirectory()){
            File f1 = new File(path + "/" + ".nomedia");
            if (!f1.exists()) {
                try {
                    boolean b = f1.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }    }
            utils.scanFile(path,getActivity());}

    }

    public  void restartPC(final Activity activity) {
        if (activity == null)
            return;
        final int enter_anim = android.R.anim.fade_in;
        final int exit_anim = android.R.anim.fade_out;
        activity.overridePendingTransition(enter_anim, exit_anim);
        activity.finish();
        activity.overridePendingTransition(enter_anim, exit_anim);
        Intent i=new Intent(getActivity(),MainActivity.class);
        i.putExtra("restart",true);
        i.setAction(Intent.ACTION_MAIN);
        activity.startActivity(i);
    }

    public String getSelectionColor(){

        String[] colors = new String[]{
                "#F44336","#74e84e40",
                "#e91e63","#74ec407a",
                "#9c27b0","#74ab47bc",
                "#673ab7","#747e57c2",
                "#3f51b5","#745c6bc0",
                "#2196F3","#74738ffe",
                "#03A9F4","#7429b6f6",
                "#00BCD4","#7426c6da",
                "#009688","#7426a69a",
                "#4CAF50","#742baf2b",
                "#8bc34a","#749ccc65",
                "#FFC107","#74ffca28",
                "#FF9800","#74ffa726",
                "#FF5722","#74ff7043",
                "#795548","#748d6e63",
                "#212121","#79bdbdbd",
                "#607d8b","#7478909c",
                "#004d40","#740E5D50"
        };
        return colors[ Arrays.asList(colors).indexOf(skin)+1];
    }

    public float[] calculatefilter(float[] values){
        float[] src= {

                values[0], 0, 0, 0, 0,
                0, values[1], 0, 0, 0,
                0, 0,  values[2],0, 0,
                0, 0, 0, 1, 0
        };
        return src;
    }
    public float[] calculatevalues(String color){
        int c=Color.parseColor(color);
        float r=(float)Color.red(c)/255;
        float g=(float)Color.green(c)/255;
        float b=(float)Color.blue(c)/255;
        return new float[]{r,g,b};
    }private void addShortcut(Layoutelements path) {
        //Adding shortcut for MainActivity
        //on Home screen
        Intent shortcutIntent = new Intent(getActivity().getApplicationContext(),
                MainActivity.class);
        shortcutIntent.putExtra("path", path.getDesc());
        shortcutIntent.setAction(Intent.ACTION_MAIN);

        Intent addIntent = new Intent();
        addIntent
                .putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, new File(path.getDesc()).getName());

        addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                Intent.ShortcutIconResource.fromContext(getActivity(),
                        R.drawable.ic_launcher));

        addIntent
                .setAction("com.android.launcher.action.INSTALL_SHORTCUT");
        getActivity().sendBroadcast(addIntent);
    }
} public class ProcessViewer extends Fragment {

    LinearLayout rootView;
    Futils utils = new Futils();
    ArrayList<Integer> CopyIds = new ArrayList<Integer>();
    ArrayList<Integer> CancelledCopyIds = new ArrayList<Integer>();
    ArrayList<Integer> ExtractIds = new ArrayList<Integer>();
    ArrayList<Integer> CancelledExtractIds = new ArrayList<Integer>();
    ArrayList<Integer> ZipIds = new ArrayList<Integer>();
    ArrayList<Integer> CancelledZipIds = new ArrayList<Integer>();
    SharedPreferences Sp;
    IconUtils icons;
    MainActivity mainActivity;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = (ViewGroup) inflater.inflate(R.layout.processparent,
                container, false);
        setRetainInstance(false);


        mainActivity = (MainActivity) getActivity();
        if(mainActivity.theme1==1)
            root.setBackgroundResource(getResources().getColor(R.color.holo_dark_background));
        rootView = (LinearLayout) root.findViewById(R.id.secondbut);
        //((MainActivity)getActivity()).getSupportActionBar().setTitle(utils.getString(getActivity(),R.string.processes));
        mainActivity.toolbar.setTitle(utils.getString(getActivity(), R.string.processes));
        mainActivity.tabsSpinner.setVisibility(View.GONE);
        mainActivity.floatingActionButton.setVisibility(View.GONE);

        Sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        icons = new IconUtils(Sp, getActivity());
        mainActivity.supportInvalidateOptionsMenu();
        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
       (getActivity()).registerReceiver(Copy_Receiver, new IntentFilter("copy"));
       (getActivity()).registerReceiver(Extract_Receiver, new IntentFilter("EXTRACT_CONDITION"));
       (getActivity()).registerReceiver(Zip_Receiver, new IntentFilter("ZIPPING"));
    }

    @Override
    public void onPause() {
        super.onPause();
       (getActivity()).unregisterReceiver(Copy_Receiver);
       (getActivity()).unregisterReceiver(Extract_Receiver);
       (getActivity()).unregisterReceiver(Zip_Receiver);
        rootView.removeAllViewsInLayout();
        CopyIds.clear();
        CancelledCopyIds.clear();
        ExtractIds.clear();
        CancelledExtractIds.clear();
        ZipIds.clear();
        CancelledZipIds.clear();
    }

    private BroadcastReceiver Copy_Receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            // TODO Auto-generated method stub
          PendingResult pendingResult=  goAsync();
            Bundle b = arg1.getExtras();
            if (b != null) {
                int id = b.getInt("id");
                final Integer id1 = new Integer(id);
                if (!CancelledCopyIds.contains(id1)) {
                    if (CopyIds.contains(id1)) {

                        boolean completed = b.getBoolean("COPY_COMPLETED", false);
                        View process = rootView.findViewWithTag("copy" + id);
                        if (completed) {
                            rootView.removeViewInLayout(process);
                            CopyIds.remove(CopyIds.indexOf(id1));
                        } else {
                            String name = b.getString("name");
                            int p1 = b.getInt("p1");
                            int p2 = b.getInt("p2");
                            long total = b.getLong("total");
                            long done = b.getLong("done");
                            boolean move = b.getBoolean("move", false);
                            String text = utils.getString(getActivity(), R.string.copying) + "\n" + name + "\n" + utils.readableFileSize(done) + "/" + utils.readableFileSize(total) + "\n" + p1 + "%";
                            if (move) {
                                text = utils.getString(getActivity(), R.string.moving) + "\n" + name + "\n" + utils.readableFileSize(done) + "/" + utils.readableFileSize(total) + "\n" + p1 + "%";
                            }
                            ((TextView) process.findViewById(R.id.progressText)).setText(text);
                            ProgressBar p = (ProgressBar) process.findViewById(R.id.progressBar1);
                            p.setProgress(p1);
                            p.setSecondaryProgress(p2);
                        }
                    } else {
                        View root = getActivity().getLayoutInflater().inflate(R.layout.processrow, null);
                        root.setTag("copy" + id);
                        ImageButton cancel = (ImageButton) root.findViewById(R.id.delete_button);
                        Drawable icon = icons.getCopyDrawable();
                        boolean move = b.getBoolean("move", false);
                        if (move) {
                            icon = icons.getCutDrawable();
                        }
                        if(mainActivity.theme1==1)cancel.setImageResource(R.drawable.ic_action_cancel);
                        ((ImageView) root.findViewById(R.id.progressImage)).setImageDrawable(icon);
                        cancel.setOnClickListener(new View.OnClickListener() {

                            public void onClick(View p1) {
                                Toast.makeText(getActivity(), utils.getString(getActivity(), R.string.stopping),Toast.LENGTH_LONG).show();
                                Intent i = new Intent("copycancel");
                                i.putExtra("id", id1);
                                getActivity().sendBroadcast(i);
                                rootView.removeView(rootView.findViewWithTag("copy" + id1));

                                CopyIds.remove(CopyIds.indexOf(id1));
                                CancelledCopyIds.add(id1);
                                // TODO: Implement this method
                            }
                        });

                        String name = b.getString("name");
                        int p1 = b.getInt("p1");
                        int p2 = b.getInt("p2");

                        String text = utils.getString(getActivity(), R.string.copying) + "\n" + name;
                        if (move) {
                            text = utils.getString(getActivity(), R.string.moving) + "\n" + name;
                        }
                        ((TextView) root.findViewById(R.id.progressText)).setText(text);
                        ProgressBar p = (ProgressBar) root.findViewById(R.id.progressBar1);
                        p.setProgress(p1);
                        p.setSecondaryProgress(p2);
                        CopyIds.add(id1);
                        rootView.addView(root);
                    }
                }
            pendingResult.finish();}
        }
    };
    private BroadcastReceiver Extract_Receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            // TODO Auto-generated method stub
            PendingResult pendingResult=goAsync();
            Bundle b = arg1.getExtras();
            if (b != null) {
                final int id = b.getInt("id");

                if (!CancelledExtractIds.contains(id)) {
                    if (ExtractIds.contains(id)) {

                        boolean completed = b.getBoolean("extract_completed", false);
                        boolean indefinite=b.getBoolean("indefinite",false);
                        View process = rootView.findViewWithTag("extract" + id);
                        if (completed) {
                            rootView.removeViewInLayout(process);
                            ExtractIds.remove(ExtractIds.indexOf(id));
                        } else {
                            String name = b.getString("name");
                            int p1 = b.getInt("p1",0);
                            long p3=b.getLong("total");
                            long p2=b.getLong("done");
                            ProgressBar p = (ProgressBar) process.findViewById(R.id.progressBar1);
                            if (p1 <= 100) {
                                ((TextView) process.findViewById(R.id.progressText)).setText(utils.getString(getActivity(), R.string.extracting) + "\n" + name + "\n" + p1 + "%"+"\n"+utils.readableFileSize(p2)+"/"+utils.readableFileSize(p3));

                                p.setProgress(p1);
                                if(indefinite && !p.isIndeterminate())p.setIndeterminate(true);
                            }
                        }
                    } else {
                        View root = getActivity().getLayoutInflater().inflate(R.layout.processrow, null);
                        root.setTag("extract" + id);
                        ((ImageView) root.findViewById(R.id.progressImage)).setImageDrawable(getResources().getDrawable(R.drawable.ic_doc_compressed_black));
                        ImageButton cancel = (ImageButton) root.findViewById(R.id.delete_button);
                        if(mainActivity.theme1==1)cancel.setImageResource(R.drawable.ic_action_cancel);
                        cancel.setOnClickListener(new View.OnClickListener() {

                            public void onClick(View p1) {
                              Toast.makeText(getActivity(), utils.getString(getActivity(), R.string.stopping), Toast.LENGTH_LONG).show();
                                Intent i = new Intent("excancel");
                                i.putExtra("id", id);
                                getActivity().sendBroadcast(i);
                                rootView.removeView(rootView.findViewWithTag("extract" + id));

                                ExtractIds.remove(ExtractIds.indexOf(id));
                                CancelledExtractIds.add(id);
                                // TODO: Implement this method
                            }
                        });

                        String name = b.getString("name");
                        int p1 = b.getInt("p1",0);


                        ((TextView) root.findViewById(R.id.progressText)).setText(utils.getString(getActivity(), R.string.extracting) + "\n" + name);
                        ProgressBar p = (ProgressBar) root.findViewById(R.id.progressBar1);
                        p.setProgress(p1);
                        ExtractIds.add(id);
                        rootView.addView(root);
                    }
                }
            pendingResult.finish();}
        }
    };
    private BroadcastReceiver Zip_Receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            // TODO Auto-generated method stub
            PendingResult pendingResult=goAsync();
            Bundle b = arg1.getExtras();

            if (b != null) {
                final int id = b.getInt("id");

                if (!CancelledZipIds.contains(id)) {
                    if (ZipIds.contains(id)) {

                        boolean completed = b.getBoolean("ZIP_COMPLETED", false);
                        View process = rootView.findViewWithTag("zip" + id);
                        if (completed) {
                            rootView.removeViewInLayout(process);
                            ZipIds.remove(ZipIds.indexOf(id));
                        } else {
                            String name = b.getString("name");
                            int p1 = b.getInt("ZIP_PROGRESS");

                            ProgressBar p = (ProgressBar) process.findViewById(R.id.progressBar1);
                            if (p1 <= 100) {
                                ((TextView) process.findViewById(R.id.progressText)).setText(utils.getString(getActivity(), R.string.zipping) + "\n" + name + "\n" + p1 + "%");

                                p.setProgress(p1);
                            }
                        }
                    } else {
                        View root = getActivity().getLayoutInflater().inflate(R.layout.processrow, null);
                        root.setTag("zip" + id);
                        ((ImageView) root.findViewById(R.id.progressImage)).setImageDrawable(getResources().getDrawable(R.drawable.ic_doc_compressed_black));
                        ImageButton cancel = (ImageButton) root.findViewById(R.id.delete_button);
                        if(mainActivity.theme1==1)cancel.setImageResource(R.drawable.ic_action_cancel);
                        cancel.setOnClickListener(new View.OnClickListener() {

                            public void onClick(View p1) {
                                Toast.makeText(getActivity(), utils.getString(getActivity(), R.string.stopping), Toast.LENGTH_LONG).show();
                                Intent i = new Intent("zipcancel");
                                i.putExtra("id", id);
                                getActivity().sendBroadcast(i);
                                rootView.removeView(rootView.findViewWithTag("zip" + id));

                                ZipIds.remove(ZipIds.indexOf(id));
                                CancelledZipIds.add(id);
                                // TODO: Implement this method
                            }
                        });

                        String name = b.getString("name");
                        int p1 = b.getInt("ZIP_PROGRESS");


                        ((TextView) root.findViewById(R.id.progressText)).setText(utils.getString(getActivity(), R.string.zipping) + "\n" + name);
                        ProgressBar p = (ProgressBar) root.findViewById(R.id.progressBar1);
                        p.setProgress(p1);

                        ZipIds.add(id);
                        rootView.addView(root);
                    }
                }
          pendingResult.finish();  }
        }
    };
} public class RarViewer extends Fragment {

    String s;
    public File f;
    public ArrayList<File> files;
    public Boolean results,selection=false;
    public String current;
    public Futils utils=new Futils();
    public String skin,iconskin,year;public RarAdapter zipAdapter;
    public ActionMode mActionMode;public int skinselection;
    public boolean coloriseIcons,showSize,showLastModified,gobackitem;
    SharedPreferences Sp;
    RarViewer zipViewer=this;
    public ArrayList<FileHeader> wholelist=new ArrayList<FileHeader>();
    public     ArrayList<FileHeader> elements = new ArrayList<FileHeader>();
    public MainActivity mainActivity;
    public RecyclerView listView;
    public Archive archive;
    View rootView;boolean addheader=true;
    public SwipeRefreshLayout swipeRefreshLayout;
    StickyRecyclerHeadersDecoration headersDecor;
    LinearLayoutManager mLayoutManager;
    DividerItemDecoration dividerItemDecoration;

    boolean showDividers;
    public int paddingTop;
    int mToolbarHeight,hidemode;
    View mToolbarContainer;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.main_frag, container, false);
        mainActivity = (MainActivity) getActivity();
        listView = (RecyclerView) rootView.findViewById(R.id.listView);
        mainActivity=(MainActivity)getActivity();
        mainActivity.supportInvalidateOptionsMenu();
        swipeRefreshLayout=(SwipeRefreshLayout)rootView.findViewById(R.id.activity_main_swipe_refresh_layout);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

        TextView textView = (TextView) mainActivity.pathbar.findViewById(R.id.fullpath);

        mainActivity.pathbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);
        s = getArguments().getString("path");
        f = new File(s);
        listView.setVisibility(View.VISIBLE);
        Sp = PreferenceManager.getDefaultSharedPreferences(getActivity());


        listView.setVisibility(View.VISIBLE);
        mLayoutManager=new LinearLayoutManager(getActivity());
        listView.setLayoutManager(mLayoutManager);
        if (mainActivity.theme1 == 1)
            rootView.setBackgroundColor(getResources().getColor(R.color.holo_dark_background));
        else

            listView.setBackgroundColor(getResources().getColor(android.R.color.background_light));

        gobackitem = Sp.getBoolean("goBack_checkbox", true);
        coloriseIcons = Sp.getBoolean("coloriseIcons", false);
        Calendar calendar = Calendar.getInstance();
        showSize = Sp.getBoolean("showFileSize", false);
        showLastModified = Sp.getBoolean("showLastModified", true);
        showDividers=Sp.getBoolean("showDividers",true);
        year = ("" + calendar.get(Calendar.YEAR)).substring(2, 4);
        skin = Sp.getString("skin_color", "#3f51b5");
        iconskin=Sp.getString("icon_skin_color",skin);
        String x = getSelectionColor();
        skinselection = Color.parseColor(x);
        files = new ArrayList<File>();
        loadlist(f.getPath());
        mToolbarContainer=getActivity().findViewById(R.id.lin);
        hidemode=Sp.getInt("hidemode",0);
        try{mainActivity.toolbar.setTitle(f.getName());}catch (Exception e){
        mainActivity.toolbar.setTitle(getResources().getString(R.string.zip_viewer));}
        mainActivity.tabsSpinner.setVisibility(View.GONE);

        mainActivity.fabHideAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.fab_hide);
        mainActivity.floatingActionButton.setAnimation(mainActivity.fabHideAnim);
        mainActivity.floatingActionButton.animate();
        mainActivity.floatingActionButton.setVisibility(View.GONE);

        mainActivity.supportInvalidateOptionsMenu();
        mToolbarHeight=getToolbarHeight(getActivity());
        paddingTop = (mToolbarHeight) + dpToPx(72);
        if(hidemode==2)mToolbarHeight=paddingTop;
        mToolbarContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                    mToolbarContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
                else {
                    mToolbarContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
                paddingTop=mToolbarContainer.getHeight();

                if(hidemode!=2)mToolbarHeight=mainActivity.toolbar.getHeight();
            }

        });
    }
    public int dpToPx(int dp) {
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
        return px;
    }
    public static int getToolbarHeight(Context context) {
        final TypedArray styledAttributes = context.getTheme().obtainStyledAttributes(
                new int[]{android.R.attr.actionBarSize});
        int toolbarHeight = (int) styledAttributes.getDimension(0, 0);
        styledAttributes.recycle();

        return toolbarHeight;
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mainActivity.supportInvalidateOptionsMenu();
        //mainActivity.floatingActionButton.show();

        // needed to remove any extracted file from cache, when onResume was not called
        // in case of opening any unknown file inside the rar
        // bug : only deletes most recent openUnknown file from cache
        if (files.size()==1) {

            new DeleteTask(getActivity().getContentResolver(),  getActivity(), this).execute(files);
        }
    }
    public String getSelectionColor(){

        String[] colors = new String[]{
                "#F44336","#74e84e40",
                "#e91e63","#74ec407a",
                "#9c27b0","#74ab47bc",
                "#673ab7","#747e57c2",
                "#3f51b5","#745c6bc0",
                "#2196F3","#74738ffe",
                "#03A9F4","#7429b6f6",
                "#00BCD4","#7426c6da",
                "#009688","#7426a69a",
                "#4CAF50","#742baf2b",
                "#8bc34a","#749ccc65",
                "#FFC107","#74ffca28",
                "#FF9800","#74ffa726",
                "#FF5722","#74ff7043",
                "#795548","#748d6e63",
                "#212121","#79bdbdbd",
                "#607d8b","#7478909c",
                "#004d40","#740E5D50"
        };
        return colors[ Arrays.asList(colors).indexOf(skin)+1];
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("path",current);
        outState.putString("file",f.getPath());
    }
    public ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
        private void hideOption(int id, Menu menu) {
            MenuItem item = menu.findItem(id);
            item.setVisible(false);
        }

        private void showOption(int id, Menu menu) {
            MenuItem item = menu.findItem(id);
            item.setVisible(true);
        }
        View v;
        // called when the action mode is created; startActionMode() was called
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // Inflate a menu resource providing context menu items
            MenuInflater inflater = mode.getMenuInflater();
            v=getActivity().getLayoutInflater().inflate(R.layout.actionmode,null);
            mode.setCustomView(v);
            // assumes that you have "contexual.xml" menu resources
            inflater.inflate(R.menu.contextual, menu);
            hideOption(R.id.cpy, menu);
            hideOption(R.id.cut,menu);
            hideOption(R.id.delete,menu);
            hideOption(R.id.addshortcut,menu);
            hideOption(R.id.sethome, menu);
            hideOption(R.id.rename, menu);
            hideOption(R.id.share, menu);
            hideOption(R.id.about, menu);
            hideOption(R.id.openwith, menu);
            showOption(R.id.all,menu);
            hideOption(R.id.book, menu);
            hideOption(R.id.compress, menu);
            hideOption(R.id.permissions, menu);
            hideOption(R.id.hide, menu);
            mode.setTitle(utils.getString(getActivity(), R.string.select));
            ObjectAnimator anim = ObjectAnimator.ofInt(mainActivity.findViewById(R.id.buttonbarframe), "backgroundColor", Color.parseColor(skin), getResources().getColor(R.color.holo_dark_action_mode));
            anim.setDuration(0);
            anim.setEvaluator(new ArgbEvaluator());
            anim.start();
            if (Build.VERSION.SDK_INT >= 21) {

                Window window = getActivity().getWindow();
                if(mainActivity.colourednavigation)window.setNavigationBarColor(getResources().getColor(android.R.color.black));  }
            if(Build.VERSION.SDK_INT<19)
                getActivity().findViewById(R.id.action_bar).setVisibility(View.GONE);
            return true;
        }

        // the following method is called each time
        // the action mode is shown. Always called after
        // onCreateActionMode, but
        // may be called multiple times if the mode is invalidated.
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            ArrayList<Integer> positions = zipAdapter.getCheckedItemPositions();
            ((TextView) v.findViewById(R.id.item_count)).setText(positions.size() + "");

            return false; // Return false if nothing is done
        }

        // called when the user selects a contextual menu item
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
                case R.id.all:zipAdapter.toggleChecked(true,"");
                    mode.invalidate();
                    return true;
                case R.id.ex:
                    try {
                        Toast.makeText(getActivity(), new Futils().getString(getActivity(), R.string.extracting), Toast.LENGTH_SHORT).show();
                        FileOutputStream fileOutputStream;
                            for(int i:zipAdapter.getCheckedItemPositions()) {
                                if(!elements.get(i).isDirectory()){File f1=new File(f.getParent() +
                                        "/" + elements.get(i).getFileNameString().trim().replaceAll("\\\\","/"));
                                if(!f1.getParentFile().exists())f1.getParentFile().mkdirs();
                                fileOutputStream = new FileOutputStream(f1);
                                archive.extractFile(elements.get(i), fileOutputStream);
                            }else{
                                    String name=elements.get(i).getFileNameString().trim();
                                    Log.d("rarViewer", " parent " + name);
                                    for(FileHeader v:archive.getFileHeaders()){
                                        if(v.getFileNameString().trim().contains(name+"\\") ||
                                                v.getFileNameString().trim().equals(name)) {
                                            File f2 = new File(f.getParent() +
                                                    "/" + v.getFileNameString().trim().replaceAll("\\\\", "/"));
                                            if (v.isDirectory()) f2.mkdirs();
                                            else {
                                                if (!f2.getParentFile().exists())
                                                    f2.getParentFile().mkdirs();
                                                fileOutputStream = new FileOutputStream(f2);
                                                archive.extractFile(v, fileOutputStream);
                                            }
                                        }

                                    }
                                }
                            }
                    } catch (Exception e) {
                        e.printStackTrace();}
                    mode.finish();
                    return true;
            }
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {
            if(zipAdapter!=null)zipAdapter.toggleChecked(false,"");
            selection=false;
            ObjectAnimator anim = ObjectAnimator.ofInt(mainActivity.findViewById(R.id.buttonbarframe), "backgroundColor", getResources().getColor(R.color.holo_dark_action_mode), Color.parseColor(skin));
            anim.setDuration(0);
            anim.setEvaluator(new ArgbEvaluator());
            anim.start();
            if (Build.VERSION.SDK_INT >= 21) {

                Window window = getActivity().getWindow();
                if(mainActivity.colourednavigation)window.setNavigationBarColor(mainActivity.skinStatusBar);
            }mActionMode=null;}
    };
    @Override
    public void onResume() {
        super.onResume();
        if (files.size()==1) {

            new DeleteTask(getActivity().getContentResolver(),  getActivity(), this).execute(files);
        }
    }
    public boolean cangoBack(){
        if(current==null || current.trim().length()==0)
            return false;
        else return true;
    }
    public void goBack() {
String path;
        try {
            path= current.substring(0,current.lastIndexOf("\\"));
        } catch (Exception e) {
            path="";
        }
        new RarHelperTask(this,path).execute(f);
    }
    public void refresh(){
        new RarHelperTask(this,current).execute(f);
    }
    public void bbar(){
        mainActivity.updatePath(current,false);
    }
    public void createviews(ArrayList<FileHeader> zipEntries,String dir){
        zipViewer.zipAdapter = new RarAdapter(zipViewer.getActivity(), zipEntries, zipViewer);
        zipViewer.listView.setAdapter(zipViewer.zipAdapter);
        if(!addheader ){
             listView.removeItemDecoration(dividerItemDecoration);
            listView.removeItemDecoration(headersDecor);
            addheader=true;
        }
        if(addheader ) {
                dividerItemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST,showDividers);
                listView.addItemDecoration(dividerItemDecoration);

            headersDecor = new StickyRecyclerHeadersDecoration(zipAdapter);
            listView.addItemDecoration(headersDecor);
            addheader=false;
        }
        listView.setOnScrollListener(new HidingScrollListener(mToolbarHeight,hidemode) {

            @Override
            public void onMoved(int distance) {
                mToolbarContainer.setTranslationY(-distance);
            }

            @Override
            public void onShow() {
                mToolbarContainer.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
            }

            @Override
            public void onHide() {
                mToolbarContainer.findViewById(R.id.lin).animate().translationY(-mToolbarHeight).setInterpolator(new AccelerateInterpolator(2)).start();
            }

        });
        zipViewer.current = dir;
        zipViewer.bbar();
        swipeRefreshLayout.setRefreshing(false);
    }
    public void loadlist(String path){
        File f=new File(path);
        new RarHelperTask(this,"").execute(f);

    }
} public class TabFragment extends android.support.v4.app.Fragment {

    public  List<Fragment> fragments = new ArrayList<Fragment>();
    public ScreenSlidePagerAdapter mSectionsPagerAdapter;
    Futils utils = new Futils();
    public CustomViewPager mViewPager;
    SharedPreferences Sp;
    String path;
    public int currenttab;
    MainActivity mainActivity;
    TabSpinnerAdapter tabSpinnerAdapter;
    public ArrayList<String> tabs=new ArrayList<String>();
    public int theme1;
    private Animation hideAnimation, showAnimation;
    View buttons;
    View mToolBarContainer;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.tabfragment,
                container, false);
        mToolBarContainer=getActivity().findViewById(R.id.lin);
        Sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        int theme=Integer.parseInt(Sp.getString("theme","0"));
        theme1 = theme==2 ? PreferenceUtils.hourOfDay() : theme;
        mViewPager = (CustomViewPager) rootView.findViewById(R.id.pager);
        if (getArguments() != null){
            path = getArguments().getString("path");
        }
        buttons=getActivity().findViewById(R.id.buttons);
        mainActivity = ((MainActivity)getActivity());
        mainActivity.supportInvalidateOptionsMenu();
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            public void onPageScrolled(int p1, float p2, int p3) {

            }

            public void onPageSelected(int p1) {
               mToolBarContainer.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();

                currenttab=p1;
                mainActivity.supportInvalidateOptionsMenu();
                try {
                    updateSpinner();
                } catch (Exception e) {
                   // e.printStackTrace();
                }
                String name=fragments.get(p1).getClass().getName();
                if(name.contains("Main")){
                    Main ma = ((Main) fragments.get(p1));
                    tabHandler = new TabHandler(getActivity(), null, null, 1);
                    if (ma.current != null) {
                        try {
                            mainActivity.updateDrawer(ma.current);
                            mainActivity.updatePath(ma.current,true);
                        if(buttons.getVisibility()==View.VISIBLE){
                            mainActivity.bbar(ma);
                        }
                        } catch (Exception e) {
                            //       e.printStackTrace();5
                        }
                    }
                }

            }

            public void onPageScrollStateChanged(int p1) {
                // TODO: Implement this method
            }
        });
        if (savedInstanceState == null) {
            int l=Sp.getInt("currenttab",1);
            mSectionsPagerAdapter = new ScreenSlidePagerAdapter(
                    getActivity().getSupportFragmentManager());
            TabHandler tabHandler=new TabHandler(getActivity(),null,null,1);
            List<Tab> tabs1=tabHandler.getAllTabs();
            int i=tabs1.size();
            if(i==0) {
                addTab(new Tab(1,"","/","/"),1,"");
                addTab(new Tab(2,"",mainActivity.list.get(0),mainActivity.list.get(0)),2,"");
            }
            else{
                if(path!=null && path.length()!=0){
                    Tab tab=tabHandler.findTab(l+1);
                    tab.setPath(path);
                    addTab(tab,l+1,"");
                    int k;
                    if(l==0)k=2;
                    else k=1;
                    addTab(tabHandler.findTab(k),k,"");
                }
                else
                {   addTab(tabHandler.findTab(1),1,"");
                 addTab(tabHandler.findTab(2),2,"");
            }}



            mViewPager.setAdapter(mSectionsPagerAdapter);

                try {
                    mViewPager.setCurrentItem(l,true);
                } catch (Exception e) {
                    e.printStackTrace();
                }

        } else {
            fragments.clear();
            tabs= savedInstanceState.getStringArrayList("tabs");
            for(int i=0;i<tabs.size();i++){
                try {
                    fragments.add(i, getActivity().getSupportFragmentManager().getFragment(savedInstanceState, "tab"+i));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            mSectionsPagerAdapter = new ScreenSlidePagerAdapter(
                    getActivity().getSupportFragmentManager());

            mViewPager.setAdapter(mSectionsPagerAdapter);
            int pos1=savedInstanceState.getInt("pos",0);
            mViewPager.setCurrentItem(pos1);
            mSectionsPagerAdapter.notifyDataSetChanged();

        }
        Main main = ((Main) fragments.get(currenttab));
        main.showButtonOnStart=true;

        return rootView;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
    }
    @Override
    public void onDestroyView(){
        Sp.edit().putInt("currenttab",currenttab).apply();
        super.onDestroyView();
        try {
            tabHandler.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    TabHandler tabHandler;

    public void updatepaths() {

        tabHandler = new TabHandler(getActivity(), null, null, 1);
        int i=1;
        ArrayList<String> items=new ArrayList<String>();

        // Getting old path from database before clearing

        tabHandler.clear();
        for(Fragment fragment:fragments) {
            if(fragment.getClass().getName().contains("Main")){
                Main m=(Main)fragment;
                items.add(m.current);
                tabHandler.addTab(new Tab(i,m.current,m.current,m.home));
                i++;
            }
        }
        try {
            tabSpinnerAdapter=new TabSpinnerAdapter(mainActivity.getSupportActionBar().getThemedContext(), R.layout.rowlayout,items,mainActivity.tabsSpinner,this);
            mainActivity.tabsSpinner.setAdapter(tabSpinnerAdapter);
            mainActivity.tabsSpinner.setSelection(mViewPager.getCurrentItem());
        } catch (Exception e) {
            e.printStackTrace();
        }
        mainActivity.updatePath(tabHandler.findTab(currenttab+1).getPath(),true);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        try {
            int i = 0;
            if (fragments != null && fragments.size() !=0) {
                for (Fragment fragment : fragments) {
                    getActivity().getSupportFragmentManager().putFragment(outState, "tab" + i, fragment);
                    i++;
                }
                outState.putStringArrayList("tabs", tabs);
                outState.putInt("pos", mViewPager.getCurrentItem());
            }
            Sp.edit().putInt("currenttab",currenttab).commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {

        @Override
        public int getItemPosition (Object object)
        {int index = fragments.indexOf ((Fragment)object);
            if (index == -1)
                return POSITION_NONE;
            else
                return index;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            try {
                String name=fragments.get(position).getClass().getName();
                if(name.contains("Main")){
                Main ma = ((Main) fragments.get(position));
                if (ma.results) {
                    return utils.getString(getActivity(), R.string.searchresults);
                } else {
                    if (ma.current.equals("/")) {
                        return "Root";
                    } else {
                        return new File(ma.current).getName();
                    }
                }}else if(name.contains("ZipViewer")) {
                    ZipViewer ma = ((ZipViewer) fragments.get(position));

                    try {
                        return ma.f.getName();
                    } catch (Exception e) {
                        return "ZipViewer";
                      //  e.printStackTrace();
                    }

                }
                return fragments.get(position).getClass().getName();
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
        }

        public int getCount() {
            // TODO: Implement this method
            return fragments.size();
        }

        public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
            super(fm);
        }

        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            android.support.v4.app.Fragment f;
            f = fragments.get(position);
            return f;
        }
    }

    public void addTab(Tab text,int pos,String path) {
        android.support.v4.app.Fragment main = new Main();
        Bundle b = new Bundle();
        if (path != null && path.trim().length() != 0) {
            b.putString("path", path);

        }
        b.putString("lastpath",text.getPath());
        b.putString("home", text.getHome());
        b.putInt("no", pos);
        main.setArguments(b);
        fragments.add(main);
        tabs.add(main.getClass().getName());
        mSectionsPagerAdapter.notifyDataSetChanged();
        mViewPager.setOffscreenPageLimit(4);
    }
    public Fragment getTab() {
        return fragments.get(mViewPager.getCurrentItem());
    }
    public Fragment getTab1() {
        Fragment man = ( fragments.get(mViewPager.getCurrentItem()));
        return man;
    }
    public void updateSpinner(){

        ArrayList<String> items=new ArrayList<String>();
        items.add(((Main)fragments.get(0)).current);
        items.add(((Main)fragments.get(1)).current);
        tabSpinnerAdapter=new TabSpinnerAdapter(mainActivity.getSupportActionBar().getThemedContext(), R.layout.rowlayout,items,mainActivity.tabsSpinner,this);
        mainActivity.tabsSpinner.setAdapter(tabSpinnerAdapter);
        mainActivity.tabsSpinner.setSelection(mViewPager.getCurrentItem());
    }
} public class ZipViewer extends Fragment {

    String s;
    public File f;
    public ArrayList<File> files;
    public Boolean results,selection=false;
    public String current;
    public Futils utils=new Futils();
    public String skin,iconskin,year;public ZipAdapter zipAdapter;
    public ActionMode mActionMode;public int skinselection;
    public boolean coloriseIcons,showSize,showLastModified,gobackitem;
SharedPreferences Sp;
    ZipViewer zipViewer=this;
    public ArrayList<ZipObj> wholelist=new ArrayList<ZipObj>();
public     ArrayList<ZipObj> elements = new ArrayList<ZipObj>();
    public MainActivity mainActivity;
    public RecyclerView listView;
    View rootView;
    boolean addheader=true;
    public SwipeRefreshLayout swipeRefreshLayout;
    StickyRecyclerHeadersDecoration headersDecor;
    LinearLayoutManager mLayoutManager;
    DividerItemDecoration dividerItemDecoration;
    boolean showDividers;
    public int paddingTop;
    int mToolbarHeight,hidemode;
    View mToolbarContainer;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.main_frag, container, false);
        mainActivity = (MainActivity) getActivity();
        listView = (RecyclerView) rootView.findViewById(R.id.listView);
        swipeRefreshLayout=(SwipeRefreshLayout)rootView.findViewById(R.id.activity_main_swipe_refresh_layout);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

        TextView textView = (TextView) mainActivity.pathbar.findViewById(R.id.fullpath);
        mainActivity.pathbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });

        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);
        Sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        s = getArguments().getString("path");
        f = new File(s);

        mToolbarContainer=getActivity().findViewById(R.id.lin);
        hidemode=Sp.getInt("hidemode", 0);
        listView.setVisibility(View.VISIBLE);
        mLayoutManager=new LinearLayoutManager(getActivity());
        listView.setLayoutManager(mLayoutManager);

        mainActivity.supportInvalidateOptionsMenu();
        if (mainActivity.theme1 == 1)
            rootView.setBackgroundColor(getResources().getColor(R.color.holo_dark_background));
        else

            listView.setBackgroundColor(getResources().getColor(android.R.color.background_light));

        gobackitem = Sp.getBoolean("goBack_checkbox", true);
        coloriseIcons = Sp.getBoolean("coloriseIcons", false);
        Calendar calendar = Calendar.getInstance();
        showSize = Sp.getBoolean("showFileSize", false);
        showLastModified = Sp.getBoolean("showLastModified", true);
        showDividers=Sp.getBoolean("showDividers",true);
        year = ("" + calendar.get(Calendar.YEAR)).substring(2, 4);
        skin = Sp.getString("skin_color", "#3f51b5");
        iconskin=Sp.getString("icon_skin_color",skin);
        mainActivity.findViewById(R.id.buttonbarframe).setBackgroundColor(Color.parseColor(skin));

        String x = getSelectionColor();
        skinselection = Color.parseColor(x);
        files = new ArrayList<File>();
        if (savedInstanceState == null)
            loadlist(f.getPath());
        else {
            wholelist = savedInstanceState.getParcelableArrayList("wholelist");
            elements = savedInstanceState.getParcelableArrayList("elements");
            current = savedInstanceState.getString("path");
            f = new File(savedInstanceState.getString("file"));
            createviews(elements, current);
        }
        mainActivity.tabsSpinner.setVisibility(View.GONE);

        mainActivity.fabHideAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.fab_hide);
        mainActivity.floatingActionButton.setAnimation(mainActivity.fabHideAnim);
        mainActivity.floatingActionButton.animate();
        mainActivity.floatingActionButton.setVisibility(View.GONE);

        try{mainActivity.toolbar.setTitle(f.getName());}catch (Exception e){
            mainActivity.toolbar.setTitle(getResources().getString(R.string.zip_viewer));}
        mainActivity.supportInvalidateOptionsMenu();
        mToolbarHeight=getToolbarHeight(getActivity());
        paddingTop = (mToolbarHeight) + dpToPx(72);
        if(hidemode==2)mToolbarHeight=paddingTop;
        mToolbarContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                    mToolbarContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
                else {
                    mToolbarContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
                paddingTop=mToolbarContainer.getHeight();

                if(hidemode!=2)mToolbarHeight=mainActivity.toolbar.getHeight();
            }

        });

    }

    public int dpToPx(int dp) {
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
        return px;
    }
    public static int getToolbarHeight(Context context) {
        final TypedArray styledAttributes = context.getTheme().obtainStyledAttributes(
                new int[]{android.R.attr.actionBarSize});
        int toolbarHeight = (int) styledAttributes.getDimension(0, 0);
        styledAttributes.recycle();

        return toolbarHeight;
    }
    public String getSelectionColor(){

        String[] colors = new String[]{
                "#F44336","#74e84e40",
                "#e91e63","#74ec407a",
                "#9c27b0","#74ab47bc",
                "#673ab7","#747e57c2",
                "#3f51b5","#745c6bc0",
                "#2196F3","#74738ffe",
                "#03A9F4","#7429b6f6",
                "#00BCD4","#7426c6da",
                "#009688","#7426a69a",
                "#4CAF50","#742baf2b",
                "#8bc34a","#749ccc65",
                "#FFC107","#74ffca28",
                "#FF9800","#74ffa726",
                "#FF5722","#74ff7043",
                "#795548","#748d6e63",
                "#212121","#79bdbdbd",
                "#607d8b","#7478909c",
                "#004d40","#740E5D50"
        };
        return colors[ Arrays.asList(colors).indexOf(skin)+1];
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelableArrayList("wholelist",wholelist);
        outState.putParcelableArrayList("elements",elements);
        outState.putString("path",current);
        outState.putString("file",f.getPath());
    }
    public ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
        private void hideOption(int id, Menu menu) {
            MenuItem item = menu.findItem(id);
            item.setVisible(false);
        }

        private void showOption(int id, Menu menu) {
            MenuItem item = menu.findItem(id);
            item.setVisible(true);
        }
        View v;
        // called when the action mode is created; startActionMode() was called
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // Inflate a menu resource providing context menu items
            MenuInflater inflater = mode.getMenuInflater();
            v=getActivity().getLayoutInflater().inflate(R.layout.actionmode,null);
            mode.setCustomView(v);
            // assumes that you have "contexual.xml" menu resources
            inflater.inflate(R.menu.contextual, menu);
            hideOption(R.id.cpy, menu);
            hideOption(R.id.cut,menu);
            hideOption(R.id.delete,menu);
            hideOption(R.id.addshortcut,menu);
            hideOption(R.id.sethome, menu);
            hideOption(R.id.rename, menu);
            hideOption(R.id.share, menu);
            hideOption(R.id.about, menu);
            hideOption(R.id.openwith, menu);
            showOption(R.id.all,menu);
            hideOption(R.id.book, menu);
            hideOption(R.id.compress, menu);
            hideOption(R.id.permissions, menu);
            hideOption(R.id.hide, menu);
            mode.setTitle(utils.getString(getActivity(), R.string.select));
            ObjectAnimator anim = ObjectAnimator.ofInt(mainActivity.findViewById(R.id.buttonbarframe), "backgroundColor", Color.parseColor(skin), getResources().getColor(R.color.holo_dark_action_mode));
            anim.setDuration(0);
            anim.setEvaluator(new ArgbEvaluator());
            anim.start();
            if (Build.VERSION.SDK_INT >= 21) {

                Window window = getActivity().getWindow();
                if(mainActivity.colourednavigation)window.setNavigationBarColor(getResources().getColor(android.R.color.black));
            }
            if(Build.VERSION.SDK_INT<19)
                getActivity().findViewById(R.id.action_bar).setVisibility(View.GONE);
            return true;
        }

        // the following method is called each time
        // the action mode is shown. Always called after
        // onCreateActionMode, but
        // may be called multiple times if the mode is invalidated.
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            ArrayList<Integer> positions = zipAdapter.getCheckedItemPositions();
            ((TextView) v.findViewById(R.id.item_count)).setText(positions.size() + "");

            return false; // Return false if nothing is done
        }

        // called when the user selects a contextual menu item
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
                case R.id.all:zipAdapter.toggleChecked(true,"");
         mode.invalidate();
                    return true;
                case R.id.ex:
                    try {Toast.makeText(getActivity(), new Futils().getString(getActivity(),R.string.extracting),Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(getActivity(), ExtractService.class);
                        ArrayList<String> a=new ArrayList<String>();
                        for(int i:zipAdapter.getCheckedItemPositions()){
                            a.add(elements.get(i).getName());
                        }
                       intent.putExtra("zip",f.getPath());
                        intent.putExtra("entries1",true);
                        intent.putExtra("entries",a);
                        getActivity().startService(intent);
                    } catch (Exception e) {
                        e.printStackTrace();}
                    mode.finish();
                    return true;}return false;}

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {
        if(zipAdapter!=null)zipAdapter.toggleChecked(false,"");
            selection=false;
        ObjectAnimator anim = ObjectAnimator.ofInt(mainActivity.findViewById(R.id.buttonbarframe), "backgroundColor", getResources().getColor(R.color.holo_dark_action_mode), Color.parseColor(skin));
        anim.setDuration(0);
        anim.setEvaluator(new ArgbEvaluator());
        anim.start();
        if (Build.VERSION.SDK_INT >= 21) {

            Window window = getActivity().getWindow();
            if(mainActivity.colourednavigation)window.setNavigationBarColor(mainActivity.skinStatusBar);
        }mActionMode=null;}
    };
    @Override
    public void onDestroyView() {
        super.onDestroyView();
    mainActivity.supportInvalidateOptionsMenu();

        // needed to remove any extracted file from cache, when onResume was not called
        // in case of opening any unknown file inside the zip
        // bug : only deletes most recent openUnknown file from cache
        if (files.size()==1) {

            new DeleteTask(getActivity().getContentResolver(),  getActivity(), this).execute(files);
        }
    }
        @Override
    public void onResume() {
        super.onResume();
        if (files.size()==1) {

            new DeleteTask(getActivity().getContentResolver(),  getActivity(), this).execute(files);
        }
    }

public boolean cangoBack(){
    if(current==null || current.trim().length()==0)
    return false;
    else return true;
}
    public void goBack() {

        new ZipHelperTask(this, new File(current).getParent()).execute(f);
    }
    void refresh(){
        new ZipHelperTask(this, current).execute(f);
    }
    public void bbar(){
        mainActivity.updatePath(current,false);

    }
    public void createviews(ArrayList<ZipObj> zipEntries,String dir){
        zipViewer.zipAdapter = new ZipAdapter(zipViewer.getActivity(), zipEntries, zipViewer);
        zipViewer.listView.setAdapter(zipViewer.zipAdapter);
        if(!addheader ){
            listView.removeItemDecoration(dividerItemDecoration);
            listView.removeItemDecoration(headersDecor);
            addheader=true;
        }
        if(addheader ) {
            dividerItemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST,showDividers);
            listView.addItemDecoration(dividerItemDecoration);

            headersDecor = new StickyRecyclerHeadersDecoration(zipAdapter);
            listView.addItemDecoration(headersDecor);
            addheader=false;
        }
        listView.setOnScrollListener(new HidingScrollListener(mToolbarHeight,hidemode) {

            @Override
            public void onMoved(int distance) {
                mToolbarContainer.setTranslationY(-distance);
            }

            @Override
            public void onShow() {
                mToolbarContainer.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
            }

            @Override
            public void onHide() {
                mToolbarContainer.findViewById(R.id.lin).animate().translationY(-mToolbarHeight).setInterpolator(new AccelerateInterpolator(2)).start();
            }

        });
        zipViewer.current = dir;
        zipViewer.bbar();
        swipeRefreshLayout.setRefreshing(false);
    }
    public void loadlist(String path){
        File f=new File(path);
        new ZipHelperTask(this,"").execute(f);

    }
} public class CopyService extends Service {
    HashMap<Integer, Boolean> hash = new HashMap<Integer, Boolean>();
    Notification notification;
    boolean rootmode;
    NotificationManager mNotifyManager;
    NotificationCompat.Builder mBuilder;
    @Override
    public void onCreate() {
        SharedPreferences Sp=PreferenceManager.getDefaultSharedPreferences(this);
        rootmode=Sp.getBoolean("rootmode",false);
        registerReceiver(receiver3, new IntentFilter("copycancel"));
    }
    boolean foreground=true;
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Bundle b = new Bundle();
        ArrayList<String> files = intent.getStringArrayListExtra("FILE_PATHS");
        String FILE2 = intent.getStringExtra("COPY_DIRECTORY");
        mNotifyManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        b.putInt("id", startId);
        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.setAction(Intent.ACTION_MAIN);
        notificationIntent.putExtra("openprocesses",true);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        mBuilder = new NotificationCompat.Builder(c);
        mBuilder.setContentIntent(pendingIntent);
        mBuilder.setContentTitle(getResources().getString(R.string.copying))

                .setSmallIcon(R.drawable.ic_content_copy_white_36dp);
        if(foreground){
            startForeground(Integer.parseInt("456"+startId),mBuilder.build());
        foreground=false;
        }
        b.putBoolean("move",intent.getBooleanExtra("move",false));
        b.putString("FILE2", FILE2);
        b.putStringArrayList("files", files);
        new Doback().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, b);
        hash.put(startId, true);
        // If we get killed, after returning from here, restart
        return START_REDELIVER_INTENT;
    }
    // Binder given to clients

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */


    public void onDestroy() {
        this.unregisterReceiver(receiver3);
    }

    public class Doback extends AsyncTask<Bundle, Void, Integer> {
        ArrayList<String> files;
        boolean move;
        public Doback() {
        }

        protected Integer doInBackground(Bundle... p1) {
            String FILE2 = p1[0].getString("FILE2");
            int id = p1[0].getInt("id");
            files = p1[0].getStringArrayList("files");
            move=p1[0].getBoolean("move");
            new copy().execute(id, files, FILE2,move);

            // TODO: Implement this method
            return id;
        }

        @Override
        public void onPostExecute(Integer b) {
            publishResults(false);
            publishResults("", 0, 0, b, 0, 0, true,move);
            stopSelf(b);

        }

    }

    private void publishResults(String a, int p1, int p2, int id, long total, long done, boolean b,boolean move) {
        if(hash.get(id)) {

            mBuilder.setProgress(100, p1, false);
            mBuilder.setOngoing(true);
            int title=R.string.copying;
            if(move)title=R.string.moving;
            mBuilder.setContentTitle(utils.getString(c,title));
            mBuilder.setContentText(new File(a).getName()+" "+utils.readableFileSize(done)+"/"+utils.readableFileSize(total));
            int id1=Integer.parseInt("456"+id);
            mNotifyManager.notify(id1,mBuilder.build());
            if(p1==100 || total==0){
                mBuilder.setContentTitle("Copy completed");
                if(move)
                mBuilder.setContentTitle("Move Completed");
                mBuilder.setContentText("");
                mBuilder.setProgress(0,0,false);
                mBuilder.setOngoing(false);
                mNotifyManager.notify(id1,mBuilder.build());
            publishCompletedResult(a,id1);
            }
            Intent intent = new Intent("copy");
            intent.putExtra("name", a);
            intent.putExtra("total", total);
            intent.putExtra("done", done);
            intent.putExtra("id", id);
            intent.putExtra("p1", p1);
            intent.putExtra("p2", p2);
            intent.putExtra("move", move);
            intent.putExtra("COPY_COMPLETED", b);
            sendBroadcast(intent);
        }else publishCompletedResult(a,Integer.parseInt("456"+id));}
    public void publishCompletedResult(String a,int id1){
        try {
            mNotifyManager.cancel(id1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    Context c = this;

    private void publishResults(boolean b) {
        Intent intent = new Intent("run");
        intent.putExtra("run", b);
        sendBroadcast(intent);

    }

    class copy {
        public copy() {
        }

        long totalBytes = 0L, copiedBytes = 0L;
        int lastpercent=0;
        public void execute(int id, final ArrayList<String> files,final String FILE2,final boolean move) {
            if (new File(FILE2).canWrite() && new File(files.get(0)).canRead()) {
                try{
                    for (int i = 0; i < files.size(); i++) {
                        File f1 = new File(files.get(i));
                        if (f1.isDirectory()) {
                            totalBytes = totalBytes + new Futils().folderSize(f1);
                        } else {
                            totalBytes = totalBytes + f1.length();
                        }
                    }}catch(Exception e){}
                for (int i = 0; i < files.size(); i++) {
                    File f1 = new File(files.get(i));
                    try {

                       if(hash.get(id)) copyFiles((f1), new File(FILE2, f1.getName()), id, move);
                        else {stopSelf(id);}
                    } catch (Exception e) {
                        System.out.println("amaze " + e);
                        publishResults("" + e, 0, 0, id, 0, 0, false, move);
                        stopSelf(id);
                    }

                }
                if (move) {
                    boolean b = hash.get(id);
                    if (b) new DeleteTask(getContentResolver(),  c).execute(utils.toFileArray(files));
                }
                Intent intent = new Intent("loadlist");
                sendBroadcast(intent);
            } else if (rootmode) {
                boolean m=true;
                for (int i = 0; i < files.size(); i++) {
                    boolean b=RootTools.copyFile(getCommandLineString(files.get(i)),getCommandLineString(FILE2),true,true);
                    if(!b && files.get(i).contains("/0/"))b=RootTools.copyFile(getCommandLineString(files.get(i).replace("/0/","/legacy/")),getCommandLineString(FILE2),true,true);
                    if(!b)m=false;
                    utils.scanFile(FILE2+"/"+new File(files.get(i)).getName(), c);
                }
                if(move  && m){new DeleteTask(getContentResolver(),c).execute(utils.toFileArray(files));}

                Intent intent = new Intent("loadlist");
                sendBroadcast(intent);

            }else {
                    System.out.println("Not Allowed");
                }
            }
        private static final String UNIX_ESCAPE_EXPRESSION = "(\\(|\\)|\\[|\\]|\\s|\'|\"|`|\\{|\\}|&|\\\\|\\?)";

        private  String getCommandLineString(String input) {
            return input.replaceAll(UNIX_ESCAPE_EXPRESSION, "\\\\$1");
        }

        private void copyFiles(File sourceFile, File targetFile, int id,boolean move) throws IOException {
            if (sourceFile.isDirectory()) {
                if (!targetFile.exists()) targetFile.mkdirs();

                String[] filePaths = sourceFile.list();

                for (String filePath : filePaths) {
                    File srcFile = new File(sourceFile, filePath);
                    File destFile = new File(targetFile, filePath);

                    copyFiles(srcFile, destFile, id,move);
                }
            } else {
                long size = sourceFile.length(), fileBytes = 0l;
                // txtDetails.append("Copying " + sourceFile.getAbsolutePath() + " ... ");
                BufferedInputStream in = new BufferedInputStream(new FileInputStream(sourceFile));
                OutputStream out;
                try {
                out= new FileOutputStream(targetFile);
}catch (Exception e){out=new MediaFile(c,targetFile).write(size);}

                byte[] buffer = new byte[20480];

                int length;
                //copy the file content in bytes
                while ((length = in.read(buffer)) > 0) {
                    boolean b = hash.get(id);
                    if (b) {
                        out.write(buffer, 0, length);
                        copiedBytes += length;
                        fileBytes += length;
                        int p=(int) ((copiedBytes / (float) totalBytes) * 100);
                        if(lastpercent!=p || lastpercent==0) {
                            publishResults(sourceFile.getName(), p, (int) ((fileBytes / (float) size) * 100), id, totalBytes, copiedBytes, false, move);
                            publishResults(true);
                        }lastpercent=p;
                    }else {publishCompletedResult(sourceFile.getName(),Integer.parseInt("456"+id));
                        in.close();
                        out.close();
                        stopSelf(id);
                    }
                    //	System.out.println(sourceFile.getName()+" "+id+" " +Math.round(copiedBytes*100/totalBytes)+"  "+Math.round(fileBytes*100/size));
                }


                in.close();
                out.close();

                utils.scanFile(targetFile.getPath(), c);
            }
        }
    }
    Futils utils = new Futils();
    private BroadcastReceiver receiver3 = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            hash.put(intent.getIntExtra("id", 1), false);

        }
    };

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }
} public class SearchService extends IntentService {
boolean rootMode,showHidden;
    SharedPreferences Sp;
    public SearchService() {
        super("SearchService");

    }
    public void publishProgress(int l){
        Intent i=new Intent("searchresults");
        i.putExtra("paths",l);
        if (run)LocalBroadcastManager.getInstance(this).sendBroadcast(i);
    }
    public void publishProgress(ArrayList<String[]> a){
        Intent i=new Intent("loadsearchresults");
       ArrayList<String> b=new ArrayList<String>();
        ArrayList<String> c=new ArrayList<String>();
        ArrayList<String> d=new ArrayList<String>();
        ArrayList<String> f=new ArrayList<String>();
        for(String[] e:a){
            b.add(e[0]);
            c.add(e[1]);
            d.add(e[2]);
            f.add(e[3]);
        }
        i.putExtra("b",b);
        i.putExtra("c",c);
        i.putExtra("d",d);
        i.putExtra("f",f);
        LocalBroadcastManager.getInstance(this).sendBroadcast(i);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Sp= PreferenceManager.getDefaultSharedPreferences(this);
        rootMode = Sp.getBoolean("rootmode", false);
        showHidden=Sp.getBoolean("showHidden",false);
        LocalBroadcastManager.getInstance(this).registerReceiver(RECIEVER,new IntentFilter("searchcancel"));
        publishProgress(0);
        ArrayList<String[]> arrayList=getSearchResult(new File(intent.getStringExtra("path")), intent.getStringExtra("text"));
        publishProgress(arrayList);
        stopSelf();
    }
    @Override
            public void onDestroy(){
        super.onDestroy();
        LocalBroadcastManager.getInstance(this)
.unregisterReceiver(RECIEVER);    }
    ArrayList<String[]> lis = new ArrayList<String[]>();
    boolean run=true;
    public ArrayList<String[]> getSearchResult(File f, String text) {
        lis.clear();
        search(f, text);
        return lis;
    }

    private BroadcastReceiver RECIEVER = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("Cancelled");
            run=false;
        }
    };
    public void search(File file, String text) {
        if (file.isDirectory()) {
              ArrayList<String[]> f= RootHelper.getFilesList(file.getPath(), rootMode, showHidden, false);
            // do you have permission to read this directory?
            if(run)
            for (String[] x : f) {
                File temp=new File(x[0]);
                if (run) {
                    if (temp.isDirectory()) {
                        if (temp.getName().toLowerCase()
                                .contains(text.toLowerCase())) {
                            lis.add(x);
                        publishProgress(lis.size());
                        }
                  if(run)      search(temp, text);

                    } else {
                        if (temp.getName().toLowerCase()
                                .contains(text.toLowerCase())) {
                            lis.add(x);
                            publishProgress(lis.size());
                        }
                    }}
            }
        } else {
            System.out
                    .println(file.getAbsoluteFile() + "Permission Denied");
        }
    }
} public class Futils {

    private Toast studioCount;

    public Futils() {
    }

    public void scanFile(String path, Context c) {
        System.out.println(path + " " + Build.VERSION.SDK_INT);
        if (Build.VERSION.SDK_INT >= 19) {
            MediaScannerConnection.scanFile(c, new String[]{path}, null, new MediaScannerConnection.OnScanCompletedListener() {

                @Override
                public void onScanCompleted(String path, Uri uri) {
                    System.out.println("SCAN COMPLETED: " + path);

                }
            });
        } else {
            Uri contentUri = Uri.fromFile(new File(path));
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, contentUri);
            c.sendBroadcast(mediaScanIntent);
        }
    }

    public String getString(Context c, int a) {
        return c.getResources().getString(a);
    }

    public void shareFiles(ArrayList<File> a, Context c) {
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
        ArrayList<Uri> uris = new ArrayList<Uri>();
        boolean b = true;
        for (File f : a) {
            uris.add(Uri.fromFile(f));
        }
        String mime = MimeTypes.getMimeType(a.get(0));
        if (a.size() > 1)
            for (File f : a) {
                if (!mime.equals(MimeTypes.getMimeType(f))) {
                    b = false;
                }
            }
        if (mime.equals(null) || mime.equals("application/vnd.android.package-archive"))
            mime = "*/*";
        if (b) sendIntent.setType(mime);
        else sendIntent.setType("*/*");

        sendIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
        try {
            c.startActivity(sendIntent);
        } catch (Exception e) {
            sendIntent.setType("*/*");
            c.startActivity(sendIntent);
            e.printStackTrace();
        }
    }

    public String readableFileSize(long size) {
        if (size <= 0)
            return "0 B";
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.##").format(size
                / Math.pow(1024, digitGroups))
                + "" + units[digitGroups];
    }

    public String getFileExtension(String url) {
        try {
            int a = url.lastIndexOf(".");
            int b = url.length();
            return url.substring(a, b);
        } catch (Exception e) {
            return "";
        }

    }

    private boolean isSelfDefault(File f, Context c){
        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(f), MimeTypes.getMimeType(f));
        String s="";
        ResolveInfo rii = c.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
        if (rii !=  null && rii.activityInfo != null) s = rii.activityInfo.packageName;
        if (s.equals("com.amaze.filemanager") || rii==null) return true;
        else return false;
    }

    public void openunknown(File f, Context c, boolean forcechooser) {
        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);

        String type = MimeTypes.getMimeType(f);
        if(type!=null && type.trim().length()!=0 && !type.equals("*/*"))
        {intent.setDataAndType(Uri.fromFile(f), type);
        Intent startintent;
        if (forcechooser) startintent=Intent.createChooser(intent, c.getResources().getString(R.string.openwith));
        else startintent=intent;
        try {
            c.startActivity(startintent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        Toast.makeText(c,R.string.noappfound,Toast.LENGTH_SHORT).show();
        openWith(f,c);
        }}else{openWith(f, c);}

    }

    public void openWith(final File f,final Context c) {
        MaterialDialog.Builder a=new MaterialDialog.Builder(c);
        a.title(getString(c, R.string.openas));
        String[] items=new String[]{getString(c,R.string.text),getString(c,R.string.image),getString(c,R.string.video),getString(c,R.string.audio),getString(c,R.string.database),getString(c,R.string.other)};
        a.items(items).itemsCallback(new MaterialDialog.ListCallback() {
            @Override
            public void onSelection(MaterialDialog materialDialog, View view, int i, CharSequence charSequence) {
                Intent intent = new Intent();
                intent.setAction(android.content.Intent.ACTION_VIEW);
                switch (i) {
                    case 0:
                        intent.setDataAndType(Uri.fromFile(f), "text/*");
                        break;
                    case 1:
                        intent.setDataAndType(Uri.fromFile(f), "image/*");
                        break;
                    case 2:
                        intent.setDataAndType(Uri.fromFile(f), "video/*");
                        break;
                    case 3:
                        intent.setDataAndType(Uri.fromFile(f), "audio/*");
                        break;
                    case 4: intent = new Intent(c, DbViewer.class);
                        intent.putExtra("path", f.getPath());
                        break;
                    case 5:
                        intent.setDataAndType(Uri.fromFile(f), "*/*");
                        break;
                }
                try {
                    c.startActivity(intent);
                } catch (Exception e) {
                    Toast.makeText(c,R.string.noappfound,Toast.LENGTH_SHORT).show();
                    openWith(f,c);
                }
            }
        });
        a.build().show();
    }public String getSize(File f) {
        long i =f.length();

        return readableFileSize(i);

    }

    public String getSize(String[] array,boolean showsize) {
        if(showsize) {
            String sym = array[1];
            long i;
            if (sym != null && sym.length() != 0) {
                i = new File(array[1]).length();
            } else
                i = new File(array[0]).length();

            return readableFileSize(i);
        }else return "";
    }

    public void deleteFiles(ArrayList<Layoutelements> a, final Main b, List<Integer> pos) {
        final MaterialDialog.Builder c = new MaterialDialog.Builder(b.getActivity());
        c.title(getString(b.getActivity(), R.string.confirm));
        final ContentResolver contentResolver=b.getActivity().getContentResolver();
        String names = "";
        final ArrayList<File> todelete = new ArrayList<File>();
        for (int i = 0; i < pos.size(); i++) {
            String path = a.get(pos.get(i)).getDesc();
            todelete.add(new File(path));
            names = names + "\n" + (i + 1) + ". " + new File(path).getName();
        }
        c.content(getString(b.getActivity(), R.string.questiondelete) + names);

        c.positiveColor(Color.parseColor(b.fabSkin));
        c.negativeColor(Color.parseColor(b.fabSkin));
        if(b.theme1==1)
            c.theme(Theme.DARK);
        c.negativeText(getString(b.getActivity(), R.string.no));
        c.positiveText(getString(b.getActivity(), R.string.yes));

        c.callback(new MaterialDialog.ButtonCallback() {
            @Override
            public void onPositive(MaterialDialog materialDialog) {
                Toast.makeText(b.getActivity(), getString(b.getActivity(), R.string.deleting), Toast.LENGTH_LONG).show();
                new DeleteTask(b.getActivity().getContentResolver(), b.getActivity()).execute(todelete);
            }

            @Override
            public void onNegative(MaterialDialog materialDialog) {

                //materialDialog.cancel();
            }
        });
        c.build().show();
    }

    public String count(File f,Resources root,boolean showSize) {
        if(showSize)try {
            Integer i=RootHelper.getCount(f);
            if(i!=null){return i+" "+root.getString(R.string.items);}
            else{return "";}

        } catch (Exception e) {
            return "";
        }else{return "";}
    }
    public boolean canGoBack(File f) {
        try {
            f.getParentFile().listFiles();
            return true;
        } catch (NullPointerException e) {
            return false;
        }
    }


    public String getdate(File f) {

        SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy | KK:mm a");
        return (sdf.format(f.lastModified())).toString();
    }
    public String getdate(long f,String form,String year) {

        SimpleDateFormat sdf = new SimpleDateFormat(form);
        String date=(sdf.format(f)).toString();
        if(date.substring(date.length()-2,date.length()).equals(year))
            date=date.substring(0,date.length()-6);
        return date;
    }

    public int calculateInSampleSize(BitmapFactory.Options options,
                                     int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and
            // keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    public void showProps(final File f, final Main c,boolean root) {
        String date = getString(c.getActivity(), R.string.date) + getdate(f);
        String items = getString(c.getActivity(), R.string.totalitems)+" calculating", size = getString(c.getActivity(), R.string.size)+" calculating", name, parent;
        name = getString(c.getActivity(), R.string.name) + f.getName();
        parent = getString(c.getActivity(), R.string.location) + f.getParent();
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c.getActivity());
        String fabskin = sp.getString("fab_skin_color", "#e91e63");
        MaterialDialog.Builder a = new MaterialDialog.Builder(c.getActivity());
        a.title(getString(c.getActivity(), R.string.properties));
        if(c.theme1==1)
            a.theme(Theme.DARK);
        a.positiveText(R.string.copy_path);
        a.negativeText(getString(c.getActivity(), R.string.copy) + " md5");
        a.neutralText(R.string.cancel);
        a.positiveColor(Color.parseColor(fabskin)).negativeColor(Color.parseColor(fabskin)).neutralColor(Color.parseColor(fabskin));
        a.callback(new MaterialDialog.ButtonCallback() {
            @Override
            public void onPositive(MaterialDialog materialDialog) {

                c.mainActivity.copyToClipboard(c.getActivity(), f.getPath());
                Toast.makeText(c.getActivity(), c.getResources().getString(R.string.pathcopied), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNegative(MaterialDialog materialDialog) {
            }
        });
        MaterialDialog materialDialog=a.build();
        materialDialog.show();
        new GenerateMD5Task(materialDialog, f, name, parent, size, items, date,c.getActivity()).execute(f.getPath());
    }

    public void showProps(final File f, final Context c,int theme1) {
        String date = getString(c, R.string.date) + getdate(f);
        String items = getString(c, R.string.totalitems)+" calculating", size = getString(c, R.string.size)+" calculating", name, parent;
        name = getString(c, R.string.name) + f.getName();
        parent = getString(c, R.string.location) + f.getParent();
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c);
        String fabskin = sp.getString("fab_skin_color", "#e91e63");
        MaterialDialog.Builder a = new MaterialDialog.Builder(c);
        a.title(getString(c, R.string.properties));
        if(theme1==1)
            a.theme(Theme.DARK);
        a.positiveText(R.string.copy_path);
        a.negativeText(getString(c, R.string.copy) + " md5");
        a.neutralText(R.string.cancel);
        a.positiveColor(Color.parseColor(fabskin)).negativeColor(Color.parseColor(fabskin)).neutralColor(Color.parseColor(fabskin));
        a.callback(new MaterialDialog.ButtonCallback() {
            @Override
            public void onPositive(MaterialDialog materialDialog) {

                copyToClipboard(c, f.getPath());
                Toast.makeText(c, c.getResources().getString(R.string.pathcopied), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNegative(MaterialDialog materialDialog) {
            }
        });

        MaterialDialog materialDialog=a.build();
        materialDialog.show();
        new GenerateMD5Task(materialDialog, f, name, parent, size, items, date,c).execute(f.getPath());
    }
    public boolean copyToClipboard(Context context, String text) {
        try {
            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
                    .getSystemService(context.CLIPBOARD_SERVICE);
            android.content.ClipData clip = android.content.ClipData
                    .newPlainText("Path copied to clipboard", text);
            clipboard.setPrimaryClip(clip);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static long folderSize(File directory) {
        long length = 0;
        try {
            for (File file:directory.listFiles()) {

                if (file.isFile())
                    length += file.length();
                else
                    length += folderSize(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return length;
    }

    public Bundle getPaths(String path, Context c) {
        ArrayList<String> names = new ArrayList<String>();
        ArrayList<String> paths = new ArrayList<String>();
        Bundle b = new Bundle();
        while (path.contains("/")) {

            paths.add(path);
            names.add(path.substring(1 + path.lastIndexOf("/"), path.length()));
            path = path.substring(0, path.lastIndexOf("/"));
        }
        names.remove("");
        paths.remove("/");
        names.add("root");
        paths.add("/");
        // Toast.makeText(c,paths.get(0)+"\n"+paths.get(1)+"\n"+paths.get(2),Toast.LENGTH_LONG).show();
        b.putStringArrayList("names", names);
        b.putStringArrayList("paths", paths);
        return b;
    }
    public boolean deletedirectory(File f){
        boolean b=true;
        for(File file:f.listFiles()){
            boolean c;
            if(file.isDirectory()){c=deletedirectory(file);}
            else {c=file.delete();}
            if(!c)b=false;

        }if(b)b=f.delete();
        return b;
    }
    public boolean deletefiles(File f) {

        // make sure directory exists
        if (!f.exists()) {

            System.out.println("Directory does not exist.");
            return false;

        } else {

            try {
                if(f.isDirectory())
                    return deletedirectory(f);
                    else
                return f.delete();

            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

    }

    public boolean rename(File f, String name,boolean root) {
        String newname = f.getParent() + "/" + name;
        if(f.getParentFile().canWrite()){
            return f.renameTo(new File(newname));}
        else if(root) {
            RootTools.remount(f.getPath(),"rw");
            RootHelper.runAndWait("mv " + f.getPath() + " " + newname, true);
            RootTools.remount(f.getPath(),"ro");
        }return true;
    }

    public boolean canListFiles(File f) {
        try {
            if (f.canRead() && f.isDirectory())
                return true;
            else
                return false;
        } catch (Exception e) {
            return false;
        }
    }

    public void openFile(final File f, final MainActivity m) {
        boolean defaultHandler = isSelfDefault(f, m);
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(m);
        if (defaultHandler && f.getName().toLowerCase().endsWith(".zip") || f.getName().toLowerCase().endsWith(".jar") || f.getName().toLowerCase().endsWith(".rar")|| f.getName().toLowerCase().endsWith(".tar")|| f.getName().toLowerCase().endsWith(".tar.gz")) {
            showArchiveDialog(f, m);
        } else if(f.getName().toLowerCase().endsWith(".apk")) {
            showPackageDialog(f, m);
        } else if (defaultHandler && f.getName().toLowerCase().endsWith(".db")) {
            Intent intent = new Intent(m, DbViewer.class);
            intent.putExtra("path", f.getPath());
            m.startActivity(intent);
        }  else if (Icons.isAudio(f.getPath())) {
            final int studio_count = sharedPreferences.getInt("studio", 0);
            Uri uri = Uri.fromFile(f);
            final Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "audio/*");

            if (studio_count!=0) {
                new CountDownTimer(studio_count, 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        int sec = (int)millisUntilFinished/1000;
                        if (studioCount!=null)
                            studioCount.cancel();
                        studioCount = Toast.makeText(m, sec + "", Toast.LENGTH_LONG);
                        studioCount.show();
                    }

                    @Override
                    public void onFinish() {
                        if (studioCount!=null)
                            studioCount.cancel();
                        studioCount = Toast.makeText(m, "Opening..", Toast.LENGTH_LONG);
                        studioCount.show();
                        m.startActivity(intent);
                    }
                }.start();
            } else
                m.startActivity(intent);
        } else {
            try {
                openunknown(f, m, false);
            } catch (Exception e) {
                Toast.makeText(m, getString(m, R.string.noappfound),Toast.LENGTH_LONG).show();
                openWith(f, m);
            }
        }
    }
public void showPackageDialog(final File f,final MainActivity m){
    MaterialDialog.Builder mat=new MaterialDialog.Builder(m);
    mat.title(R.string.packageinstaller).content(R.string.pitext).positiveText(R.string.install).negativeText(R.string.view).neutralText(R.string.cancel).callback(new MaterialDialog.ButtonCallback() {
        @Override
        public void onPositive(MaterialDialog materialDialog) {
            openunknown(f,m,false);
        }

        @Override
        public void onNegative(MaterialDialog materialDialog) {
            m.openZip(f.getPath());
        }
    });
    mat.positiveColor(Color.parseColor(m.fabskin));
    mat.neutralColor(Color.parseColor(m.fabskin));
    mat.negativeColor(Color.parseColor(m.fabskin));
    if(m.theme1==1)mat.theme(Theme.DARK);
    mat.build().show();

}
    public void showArchiveDialog(final File f,final MainActivity m){
        MaterialDialog.Builder mat=new MaterialDialog.Builder(m);
        mat.title(R.string.archive).content(R.string.archtext).positiveText(R.string.extract).negativeText(R.string.view).neutralText(R.string.cancel).callback(new MaterialDialog.ButtonCallback() {
            @Override
            public void onPositive(MaterialDialog materialDialog) {
                Intent intent = new Intent(m, ExtractService.class);
                intent.putExtra("zip",f.getPath());
                m.startService(intent);
            }

            @Override
            public void onNegative(MaterialDialog materialDialog) {
                //m.addZipViewTab(f.getPath());
                if(f.getName().toLowerCase().endsWith(".rar"))
                    m.openRar(f.getPath());
                else
                    m.openZip(f.getPath());
            }
        });
        mat.positiveColor(Color.parseColor(m.fabskin));
        mat.neutralColor(Color.parseColor(m.fabskin));
        mat.negativeColor(Color.parseColor(m.fabskin));
        if(m.theme1==1)mat.theme(Theme.DARK);
        MaterialDialog b=mat.build();

        if(!f.getName().toLowerCase().endsWith(".rar") && !f.getName().toLowerCase().endsWith(".jar") && !f.getName().toLowerCase().endsWith(".apk") && !f.getName().toLowerCase().endsWith(".zip"))
            b.getActionButton(DialogAction.NEGATIVE).setEnabled(false);
                b.show();

    }
    public Layoutelements newElement(Drawable i, String d,String permissions,String symlink,String size,boolean directorybool,boolean b,String date) {
        Layoutelements item = new Layoutelements(i, new File(d).getName(), d,permissions,symlink,size,b,date,directorybool);
        return item;
    }

    public ArrayList<File> toFileArray(ArrayList<String> a) {
        ArrayList<File> b = new ArrayList<File>();
        for (int i = 0; i < a.size(); i++) {
            b.add(new File(a.get(i)));
        }
        return b;
    }

    public ArrayList<String> toStringArray(ArrayList<File> a) {
        ArrayList<String> b = new ArrayList<String>();
        for (int i = 0; i < a.size(); i++) {
            b.add(a.get(i).getPath());
        }
        return b;
    }

    public void showNameDialog(final MainActivity m, final ArrayList<String> b, final String current) {
        MaterialDialog.Builder a = new MaterialDialog.Builder(m);
        View v = m.getLayoutInflater().inflate(R.layout.dialog, null);
        final EditText e = (EditText) v.findViewById(R.id.newname);
        e.setText("Newzip.zip");
        a.customView(v, true);
        if(m.theme1==1)
            a.theme(Theme.DARK);
        a.title(getString(m, R.string.enterzipname));
        e.setHint(getString(m, R.string.enterzipname));
        a.positiveText(R.string.create);
        a.callback(new MaterialDialog.ButtonCallback() {
            @Override
            public void onPositive(MaterialDialog materialDialog) {
                Intent intent2 = new Intent(m, ZipTask.class);
                String name = current + "/" + e.getText().toString();
                intent2.putExtra("name", name);
                intent2.putExtra("files", b);
                m.startService(intent2);
            }

            @Override
            public void onNegative(MaterialDialog materialDialog) {

            }
        });
        a.negativeText(getString(m, R.string.cancel));
        a.positiveColor(Color.parseColor(m.fabskin));
        a.negativeColor(Color.parseColor(m.fabskin));
        a.build().show();
    }

    public void showSortDialog(final Main m) {
        String[] sort = m.getResources().getStringArray(R.array.sortby);
        int current = Integer.parseInt(m.Sp.getString("sortby", "0"));
        MaterialDialog.Builder a = new MaterialDialog.Builder(m.getActivity());
        if(m.theme1==1)a.theme(Theme.DARK);
        a.items(sort).itemsCallbackSingleChoice(current, new MaterialDialog.ListCallbackSingleChoice() {
            @Override
            public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {

                m.Sp.edit().putString("sortby", "" + which).commit();
                m.getSortModes();
                m.loadlist(new File(m.current), false);
                dialog.dismiss();
                return true;
            }
        });
        a.title(R.string.sortby);
        a.build().show();
    }

    public void showHistoryDialog(final Main m) {
        final ArrayList<String> paths = m.history.readTable();
        final MaterialDialog.Builder a = new MaterialDialog.Builder(m.getActivity());
        a.positiveText(R.string.cancel);
        a.positiveColor(Color.parseColor(m.fabSkin));
        a.title(R.string.history);
        if(m.theme1==1)
            a.theme(Theme.DARK);
        LayoutInflater layoutInflater = (LayoutInflater) m.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.list_dialog, null);
        ListView listView = (ListView) view.findViewById(R.id.listView);
        listView.setDivider(null);
        a.customView(view, true);
        a.autoDismiss(true);
        MaterialDialog x=a.build();
        HiddenAdapter adapter = new HiddenAdapter(m.getActivity(),m, R.layout.bookmarkrow, toFileArray(paths),m.hidden,x,true);
        listView.setAdapter(adapter);
        x.show();

    }

    public void showHiddenDialog(final Main m) {
          final ArrayList<String> paths = m.hidden.readTable();
            final MaterialDialog.Builder a = new MaterialDialog.Builder(m.getActivity());
        a.positiveText(R.string.cancel);
        a.positiveColor(Color.parseColor(m.fabSkin));
        a.title(R.string.hiddenfiles);
        if(m.theme1==1)
            a.theme(Theme.DARK);
        LayoutInflater layoutInflater = (LayoutInflater) m.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.list_dialog, null);
        ListView listView = (ListView) view.findViewById(R.id.listView);
        a.customView(view, true);
        a.autoDismiss(true);
        listView.setDivider(null);
        MaterialDialog x=a.build();
        HiddenAdapter adapter = new HiddenAdapter(m.getActivity(),m, R.layout.bookmarkrow, toFileArray(paths),m.hidden,x,false);
        listView.setAdapter(adapter);
        x.show();

    }
    public void setPermissionsDialog(final Layoutelements f, final Main main){
        if(main.rootMode){
            final File file=new File(f.getDesc());
            final MaterialDialog.Builder a=new MaterialDialog.Builder(main.getActivity());
            View v=main.getActivity().getLayoutInflater().inflate(R.layout.permissiontable,null);
            final CheckBox readown=(CheckBox) v.findViewById(R.id.creadown);
            final CheckBox readgroup=(CheckBox) v.findViewById(R.id.creadgroup);
            final CheckBox readother=(CheckBox) v.findViewById(R.id.creadother);
            final CheckBox writeown=(CheckBox) v.findViewById(R.id.cwriteown);
            final CheckBox writegroup=(CheckBox) v.findViewById(R.id.cwritegroup);
            final CheckBox writeother=(CheckBox) v.findViewById(R.id.cwriteother);
            final CheckBox exeown=(CheckBox) v.findViewById(R.id.cexeown);
            final CheckBox exegroup=(CheckBox) v.findViewById(R.id.cexegroup);
            final CheckBox exeother=(CheckBox) v.findViewById(R.id.cexeother);
            String perm=f.getPermissions();
            if(perm.length()<6){
                Toast.makeText(main.getActivity(),R.string.not_allowed,Toast.LENGTH_SHORT).show();
                return;
            }
            ArrayList<Boolean[]> arrayList=parse(perm);
            Boolean[] read=arrayList.get(0);
            Boolean[] write=arrayList.get(1);
            Boolean[] exe=arrayList.get(2);
            readown.setChecked(read[0]);
            readgroup.setChecked(read[1]);
            readother.setChecked(read[2]);
            writeown.setChecked(write[0]);
            writegroup.setChecked(write[1]);
            writeother.setChecked(write[2]);
            exeown.setChecked(exe[0]);
            exegroup.setChecked(exe[1]);
            exeother.setChecked(exe[2]);
            a.positiveText(R.string.set);
            a.positiveColor(Color.parseColor(main.fabSkin));
            a.callback(new MaterialDialog.ButtonCallback() {
                @Override
                public void onPositive(MaterialDialog materialDialog) {
                    int a=0,b=0,c=0;
                    if(readown.isChecked())a=4;
                    if(writeown.isChecked())b=2;
                    if(exeown.isChecked())c=1;
                    int owner=a+b+c;
                    int d=0,e=0,f=0;
                    if(readgroup.isChecked())d=4;
                    if(writegroup.isChecked())e=2;
                    if(exegroup.isChecked())f=1;
                    int group=d+e+f;
                    int g=0,h=0,i=0;
                    if(readother.isChecked())g=4;
                    if(writeother.isChecked())h=2;
                    if(exeother.isChecked())i=1;
                    int other=g+h+i;
                    String  finalValue=owner+""+group+""+other;

                    String command="chmod "+finalValue+" "+file.getPath();
                    if(file.isDirectory())command="chmod -R "+finalValue+" "+file.getPath();
                    Command com=new Command(1,command) {
                        @Override
                        public void commandOutput(int i, String s) {
                            Toast.makeText(main.getActivity(),s,Toast.LENGTH_LONG);
                        }

                        @Override
                        public void commandTerminated(int i, String s) {
                            Toast.makeText(main.getActivity(),s,Toast.LENGTH_LONG);
                        }

                        @Override
                        public void commandCompleted(int i, int i2) {
                            Toast.makeText(main.getActivity(),main.getResources().getString(R.string.done),Toast.LENGTH_LONG);
                        }
                    };
                    try {//
                        RootTools.remount(file.getPath(),"RW");
                        RootTools.getShell(true).add(com);
                        main.updateList();
                    } catch (Exception e1) {
                        Toast.makeText(main.getActivity(),main.getResources().getString(R.string.error),Toast.LENGTH_LONG).show();
                        e1.printStackTrace();
                    }

                }

                @Override
                public void onNegative(MaterialDialog materialDialog) {

                }
            });
            a.title(file.getName());
            a.customView(v, true);
            if(main.theme1==1)a.theme(Theme.DARK);
            a.build().show();}else{Toast.makeText(main.getActivity(),main.getResources().getString(R.string.enablerootmde),Toast.LENGTH_LONG).show();}
    }
    public String[] parseName(String line){
        boolean linked=false;String name="",link="",size="-1",date="";
        String[] array=line.split(" ");
        for(int i=0;i<array.length;i++){
            if(array[i].contains("->")){linked=true;}
        }int p=getColonPosition(array);
        date=array[p-1] +" | "+array[p];
        size=array[p-2];
        if(!linked){
            for(int i=p+1;i<array.length;i++){name=name+" "+array[i];}
            name=name.trim();
        }
        else if(linked){
            int q=getLinkPosition(array);
            for(int i=p+1;i<q;i++){name=name+" "+array[i];}
            name=name.trim();
            for(int i=q+1;i<array.length;i++){link=link+" "+array[i];}
        }
        String size1=size;
        if(size.equals("")){size="-1";size1="";}
        ParsePosition pos = new ParsePosition(0);
        SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-mm-dd | HH:mm");
        Date stringDate = simpledateformat.parse(date, pos);
        return new String[]{name,link,array[0],size,stringDate.getTime()+"",size1};
    }
    public int getLinkPosition(String[] array){
        for(int i=0;i<array.length;i++){
            if(array[i].contains("->"))return i;
        }
        return  0;
    }
    public int getColonPosition(String[] array){
        for(int i=0;i<array.length;i++){
            if(array[i].contains(":"))return i;
        }
        return  0;
    }  public  final int READ = 4;
    public  final int WRITE = 2;
    public  final int EXECUTE = 1;
    public ArrayList<Boolean[]> parse(String permLine) {
        ArrayList<Boolean[]> arrayList=new ArrayList<Boolean[]>();
        Boolean[] read=new Boolean[]{false,false,false};
        Boolean[] write=new Boolean[]{false,false,false};
        Boolean[] execute=new Boolean[]{false,false,false};
        int owner = 0;
        if (permLine.charAt(1) == 'r') {
            owner += READ;
            read[0]=true;
        }
        if (permLine.charAt(2) == 'w') {
            owner += WRITE;
            write[0]=true;
        }
        if (permLine.charAt(3) == 'x') {
            owner += EXECUTE;
            execute[0]=true;
        }
        int group = 0;
        if (permLine.charAt(4) == 'r') {
            group += READ;
            read[1]=true;
        }
        if (permLine.charAt(5) == 'w') {
            group += WRITE;
            write[1]=true;
        }
        if (permLine.charAt(6) == 'x') {
            group += EXECUTE;
        execute[1]=true;
        }
        int world = 0;
        if (permLine.charAt(7) == 'r') {
            world += READ;
        read[2]=true;
        }
        if (permLine.charAt(8) == 'w') {
            world += WRITE;
        write[2]=true;
        }
        if (permLine.charAt(9) == 'x') {
            world += EXECUTE;
        execute[2]=true;
        }
        arrayList.add(read);
        arrayList.add(write);
        arrayList.add(execute);
        return arrayList;
    }
    public Boolean[] unparsePermissions(int i){

        switch (i){
            case 0:return new Boolean[]{false,false,false};
            case 1:return new Boolean[]{false,false,true};
            case 2:return new Boolean[]{false,true,false};
            case 3:return new Boolean[]{false,true,true};
            case 4:return new Boolean[]{true,false,false};
            case 5:return new Boolean[]{true,false,true};
            case 6:return new Boolean[]{true,true,false};
            case 7:return new Boolean[]{true,true,true};
            default:return null;
        }
    }
    public int parsePermissions(String permission) {
        int tmp;
        if (permission.charAt(0) == 'r')
            tmp = 4;
        else
            tmp = 0;

        RootTools.log("permission " + tmp);
        RootTools.log("character " + permission.charAt(0));

        if (permission.charAt(1) == 'w')
            tmp += 2;
        else
            tmp += 0;

        RootTools.log("permission " + tmp);
        RootTools.log("character " + permission.charAt(1));

        if (permission.charAt(2) == 'x')
            tmp += 1;
        else
            tmp += 0;

        RootTools.log("permission " + tmp);
        RootTools.log("character " + permission.charAt(2));

        return tmp;
    }

    public int parseSpecialPermissions(String permission) {
        int tmp = 0;
        if (permission.charAt(2) == 's')
            tmp += 4;

        if (permission.charAt(5) == 's')
            tmp += 2;

        if (permission.charAt(8) == 't')
            tmp += 1;

        RootTools.log("special permissions " + tmp);

        return tmp;
    }
} public class IconUtils {
    int LIGHT = 0, DARK = 1, CURRENT, rand;
    Context c;

    public IconUtils(SharedPreferences Sp, Context c) {

        rand = Integer.parseInt(Sp.getString("theme", "0"));
        CURRENT = rand==2 ? PreferenceUtils.hourOfDay() : rand;
        this.c = c;
    }

    public Drawable getCopyDrawable() {
        if (CURRENT == LIGHT)
            return c.getResources().getDrawable(R.drawable.ic_content_copy_black_36dp);
        else
            return c.getResources().getDrawable(R.drawable.ic_content_copy_white_36dp);
    }

    public Drawable getCutDrawable() {
        if (CURRENT == LIGHT)
            return c.getResources().getDrawable(R.drawable.ic_content_cut_black_36dp);
        else
            return c.getResources().getDrawable(R.drawable.ic_content_cut_white_36dp);
    }
    public Drawable getBookDrawable1() {
        if (CURRENT == LIGHT)
            return c.getResources().getDrawable(R.drawable.ic_action_not_important_light);
        else
            return c.getResources().getDrawable(R.drawable.ic_action_not_important);
    }
    public Drawable getCancelDrawable() {
        if (CURRENT == LIGHT)
            return c.getResources().getDrawable(R.drawable.ic_action_cancel_light);
        else
            return c.getResources().getDrawable(R.drawable.ic_action_cancel);
    }

    public Drawable getNewDrawable() {
        if (CURRENT == LIGHT)
            return c.getResources().getDrawable(R.drawable.ic_action_new_light);
        else
            return c.getResources().getDrawable(R.drawable.ic_action_new_light);
    }

    public Drawable getSearchDrawable() {
        if (CURRENT == LIGHT)
            return c.getResources().getDrawable(R.drawable.ic_action_search);
        else
            return c.getResources().getDrawable(R.drawable.ic_action_search);
    }

    public Drawable getDeleteDrawable() {
        if (CURRENT == LIGHT)
            return c.getResources().getDrawable(R.drawable.ic_delete_black_48dp);
        else
            return c.getResources().getDrawable(R.drawable.ic_delete_white_36dp);
    }

    public Drawable getAllDrawable() {
        if (CURRENT == LIGHT)
            return c.getResources().getDrawable(R.drawable.ic_select_all_black_36dp);
        else
            return c.getResources().getDrawable(R.drawable.ic_select_all_white_36dp);
    }

    public Drawable getAboutDrawable() {
        if (CURRENT == LIGHT)
            return c.getResources().getDrawable(R.drawable.ic_action_about);
        else
            return c.getResources().getDrawable(R.drawable.ic_action_about);
    }

    public Drawable getRootDrawable() {
        if (CURRENT == LIGHT)
            return c.getResources().getDrawable(R.drawable.root);
        else
            return c.getResources().getDrawable(R.drawable.root);
    }
    public int getDrawerDrawable() {
        if (CURRENT == LIGHT)
            return (R.drawable.ic_drawer_l);
        else
            return (R.drawable.ic_drawer_l);
    }
    public Drawable getSdDrawable() {
        if (CURRENT == LIGHT)
            return c.getResources().getDrawable(R.drawable.ic_action_sd_storage);
        else
            return c.getResources().getDrawable(R.drawable.ic_action_sd_storage);
    }
    public Drawable getSdDrawable1() {
        if (CURRENT == LIGHT)
            return c.getResources().getDrawable(R.drawable.ic_action_sd_storage_light);
        else
            return c.getResources().getDrawable(R.drawable.ic_action_sd_storage);
    }
    public Drawable getGridDrawable() {
        if (CURRENT == LIGHT)
            return c.getResources().getDrawable(R.drawable.ic_action_view_as_grid_light);
        else
            return c.getResources().getDrawable(R.drawable.ic_action_view_as_grid);
    }

} public class MediaFile {

    private static final String NO_MEDIA = ".nomedia";
    private static final String ALBUM_ART_URI = "content://media/external/audio/albumart";
    private static final String[] ALBUM_PROJECTION = { BaseColumns._ID, MediaStore.Audio.AlbumColumns.ALBUM_ID, "media_type" };

    private static File getExternalFilesDir(Context context) {


        try {
            Method method = Context.class.getMethod("getExternalFilesDir", String.class);
            return (File) method.invoke(context, (String) null);
        } catch (SecurityException ex) {
         //   Log.d(Maui.LOG_TAG, "Unexpected reflection error.", ex);
            return null;
        } catch (NoSuchMethodException ex) {
       //     Log.d(Maui.LOG_TAG, "Unexpected reflection error.", ex);
            return null;
        } catch (IllegalArgumentException ex) {
           // Log.d(Maui.LOG_TAG, "Unexpected reflection error.", ex);
            return null;
        } catch (IllegalAccessException ex) {
            //Log.d(Maui.LOG_TAG, "Unexpected reflection error.", ex);
            return null;
        } catch (InvocationTargetException ex) {
            //Log.d(Maui.LOG_TAG, "Unexpected reflection error.", ex);
            return null;
        }
    }


    private final File file;
    private final Context context;
    private final ContentResolver contentResolver;
    Uri filesUri;
    public MediaFile(Context context, File file) {
        this.file = file;
        this.context = context;
        contentResolver = context.getContentResolver();
        filesUri = MediaStore.Files.getContentUri("external");
    }

    /**
     * Deletes the file. Returns true if the file has been successfully deleted or otherwise does not exist. This operation is not
     * recursive.
     */
    public boolean delete()
            throws IOException {

        if (!file.exists()) {
            return true;
        }

        boolean directory = file.isDirectory();
        if (directory) {
            // Verify directory does not contain any files/directories within it.
            String[] files = file.list();
            if (files != null && files.length > 0) {
                return false;
            }
        }

        String where = MediaStore.MediaColumns.DATA + "=?";
        String[] selectionArgs = new String[] { file.getAbsolutePath() };

        // Delete the entry from the media database. This will actually delete media files (images, audio, and video).
        contentResolver.delete(filesUri, where, selectionArgs);

        if (file.exists()) {
            // If the file is not a media file, create a new entry suggesting that this location is an image, even
            // though it is not.
            ContentValues values = new ContentValues();
            values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
            contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            // Delete the created entry, such that content provider will delete the file.
            contentResolver.delete(filesUri, where, selectionArgs);
        }

        return !file.exists();
    }

    public File getFile() {
        return file;
    }

    private int getTemporaryAlbumId() {
        final File temporaryTrack;
        try {
            temporaryTrack = installTemporaryTrack();
        } catch (IOException ex) {
            return 0;
        }

        final String[] selectionArgs = { temporaryTrack.getAbsolutePath() };
        Cursor cursor = contentResolver.query(filesUri, ALBUM_PROJECTION, MediaStore.MediaColumns.DATA + "=?",
                selectionArgs, null);
        if (cursor == null || !cursor.moveToFirst()) {
            if (cursor != null) {
                cursor.close();
                cursor = null;
            }
            ContentValues values = new ContentValues();
            values.put(MediaStore.MediaColumns.DATA, temporaryTrack.getAbsolutePath());
            values.put(MediaStore.MediaColumns.TITLE, "{MediaWrite Workaround}");
            values.put(MediaStore.MediaColumns.SIZE, temporaryTrack.length());
            values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg");
            values.put(MediaStore.Audio.AudioColumns.IS_MUSIC, true);
            contentResolver.insert(filesUri, values);
        }
        cursor = contentResolver.query(filesUri, ALBUM_PROJECTION, MediaStore.MediaColumns.DATA + "=?",
                selectionArgs, null);
        if (cursor == null) {
            return 0;
        }
        if (!cursor.moveToFirst()) {
            cursor.close();
            return 0;
        }
        int id = cursor.getInt(0);
        int albumId = cursor.getInt(1);
        int mediaType = cursor.getInt(2);
        cursor.close();

        ContentValues values = new ContentValues();
        boolean updateRequired = false;
        if (albumId == 0) {
            values.put(MediaStore.Audio.AlbumColumns.ALBUM_ID, 13371337);
            updateRequired = true;
        }
        if (mediaType != 2) {
            values.put("media_type", 2);
            updateRequired = true;
        }
        if (updateRequired) {
            contentResolver.update(filesUri, values, BaseColumns._ID + "=" + id, null);
        }
        cursor = contentResolver.query(filesUri, ALBUM_PROJECTION, MediaStore.MediaColumns.DATA + "=?",
                selectionArgs, null);
        if (cursor == null) {
            return 0;
        }

        try {
            if (!cursor.moveToFirst()) {
                return 0;
            }
            return cursor.getInt(1);
        } finally {
            cursor.close();
        }
    }

    private File installTemporaryTrack()
            throws IOException {
        File externalFilesDir = getExternalFilesDir(context);
        if (externalFilesDir == null) {
            return null;
        }
        File temporaryTrack = new File(externalFilesDir, "temptrack.mp3");
        if (!temporaryTrack.exists()) {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = context.getResources().openRawResource(R.raw.temptrack);
                out = new FileOutputStream(temporaryTrack);
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException ex) {
                        return null;
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException ex) {
                        return null;
                    }
                }
            }
        }
        return temporaryTrack;
    }
    public boolean mkdir()
            throws IOException {
        if (file.exists()) {
            return file.isDirectory();
        }

        File tmpFile = new File(file, ".MediaWriteTemp");
        int albumId = getTemporaryAlbumId();

        if (albumId == 0) {
            throw new IOException("Fail");
        }

        Uri albumUri = Uri.parse(ALBUM_ART_URI + '/' + albumId);
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, tmpFile.getAbsolutePath());

        if (contentResolver.update(albumUri, values, null, null) == 0) {
            values.put(MediaStore.Audio.AlbumColumns.ALBUM_ID, albumId);
            contentResolver.insert(Uri.parse(ALBUM_ART_URI), values);
        }

        try {
            ParcelFileDescriptor fd = contentResolver.openFileDescriptor(albumUri, "r");
            fd.close();
        } finally {
            MediaFile tmpMediaFile = new MediaFile(context, tmpFile);
            tmpMediaFile.delete();
        }

        return file.exists();
    }

    /**
     * Returns an OutputStream to write to the file. The file will be truncated immediately.
     */
    public OutputStream write(long size)
            throws IOException {

        if (NO_MEDIA.equals(file.getName().trim())) {
            throw new IOException("Unable to create .nomedia file via media content provider API.");
        }

        if (file.exists() && file.isDirectory()) {
            throw new IOException("File exists and is a directory.");
        }

        // Delete any existing entry from the media database.
        // This may also delete the file (for media types), but that is irrelevant as it will be truncated momentarily in any case.
        String where = MediaStore.MediaColumns.DATA + "=?";
        String[] selectionArgs = new String[] { file.getAbsolutePath() };
        contentResolver.delete(filesUri, where, selectionArgs);

        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
        values.put(MediaStore.MediaColumns.SIZE, size);
        Uri uri = contentResolver.insert(filesUri, values);

        if (uri == null) {
            // Should not occur.
            throw new IOException("Internal error.");
        }

        return contentResolver.openOutputStream(uri);
    }
} public class PreferenceUtils {

    public static String getStatusColor(String skin) {

        String[] colors = new String[]{
                "#F44336","#D32F2F",
                "#e91e63","#C2185B",
                "#9c27b0","#7B1FA2",
                "#673ab7","#512DA8",
                "#3f51b5","#303F9F",
                "#2196F3","#1976D2",
                "#03A9F4","#0288D1",
                "#00BCD4","#0097A7",
                "#009688","#00796B",
                "#4CAF50","#388E3C",
                "#8bc34a","#689F38",
                "#FFC107","#FFA000",
                "#FF9800","#F57C00",
                "#FF5722","#E64A19",
                "#795548","#5D4037",
                "#212121","#000000",
                "#607d8b","#455A64",
                "#004d40","#002620"
        };
        return colors[ Arrays.asList(colors).indexOf(skin)+1];
    }


    public static void random(SharedPreferences Sp) {

        String[] colors = new String[]{
                "#F44336",
                "#e91e63",
                "#9c27b0",
                "#673ab7",
                "#3f51b5",
                "#2196F3",
                "#03A9F4",
                "#00BCD4",
                "#009688",
                "#4CAF50",
                "#8bc34a",
                "#FFC107",
                "#FF9800",
                "#FF5722",
                "#795548",
                "#212121",
                "#607d8b",
                "#004d40"
        };

        Random random = new Random();
        int pos = random.nextInt(colors.length - 1);
        Sp.edit().putString("skin_color", colors[pos]).commit();
    }

    public static final String LICENCE_TERMS = "<html><body>" +
            "<h3>Notices for files:</h3>" +
            "<ul><li>nineoldandroids-2.4.0.jar</ul></li>" +	//nineoldandroids
            "<p style = 'background-color:#eeeeee;padding-left:1em'><code>" +
            "<br>/*<br>" +
            "&nbsp;* Copyright 2012 Jake Wharton<br>" +
            "&nbsp;* <br>" +
            "&nbsp;* Licensed under the Apache License, Version 2.0 (the \"License\");<br>" +
            "&nbsp;* you may not use this file except in compliance with the License.<br>" +
            "&nbsp;* You may obtain a copy of the License at<br>" +
            "&nbsp;* <br>" +
            "&nbsp;* &nbsp;&nbsp;&nbsp;http://www.apache.org/licenses/LICENSE-2.0<br>" +
            "&nbsp;* <br>" +
            "&nbsp;* Unless required by applicable law or agreed to in writing, software<br>" +
            "&nbsp;* distributed under the License is distributed on an \"AS IS\" BASIS,<br>" +
            "&nbsp;* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<br>" +
            "&nbsp;* See the License for the specific language governing permissions and<br>" +
            "&nbsp;* limitations under the License.<br>" +
            "&nbsp;*/ " +
            "<br><br></code></p>" +
            "<h3>Notices for files:</h3> " +
            "<ul><li>RootTools.jar</ul></li>" +	//RootTools
            "<p style = 'background-color:#eeeeee;padding-left:1em'><code>" +
            "<br>/*<br>" +
            "&nbsp;* This file is part of the RootTools Project: http://code.google.com/p/roottools/<br>" +
            "&nbsp;*<br>" +
            "&nbsp;* Copyright (c) 2012 Stephen Erickson, Chris Ravenscroft, Dominik Schuermann, Adam Shanks<br>" +
            "&nbsp;*<br>" +
            "&nbsp;* This code is dual-licensed under the terms of the Apache License Version 2.0 and<br>" +
            "&nbsp;* the terms of the General Public License (GPL) Version 2.<br>" +
            "&nbsp;* You may use this code according to either of these licenses as is most appropriate<br>" +
            "&nbsp;* for your project on a case-by-case basis.<br>" +
            "&nbsp;*<br>" +
            "&nbsp;* The terms of each license can be found in the root directory of this project's repository as well as at:<br>" +
            "&nbsp;*<br>" +
            "&nbsp;* &nbsp;&nbsp;&nbsp;http://www.apache.org/licenses/LICENSE-2.0<br>" +
            "&nbsp;* &nbsp;&nbsp;&nbsp;http://www.gnu.org/licenses/gpl-2.0.txt<br>" +
            "&nbsp;*<br>" +
            "&nbsp;* Unless required by applicable law or agreed to in writing, software<br>" +
            "&nbsp;* distributed under these Licenses is distributed on an \"AS IS\" BASIS,<br>" +
            "&nbsp;* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<br>" +
            "&nbsp;* See each License for the specific language governing permissions and<br>" +
            "&nbsp;* limitations under that License.<br>" +
            "&nbsp;*/ " +
            "<br><br></code></p>" +
            "<h3>Notices for libraries:</h3> " +
            "<ul><li>CircularImageView</ul></li>" +	//CircularImageView
            "<p style = 'background-color:#eeeeee;padding-left:1em'><code>" +
            "<br>/*<br>" +
            "&nbsp;* The MIT License (MIT)<br>" +
            "&nbsp;*<br>" +
            "&nbsp;* Copyright (c) 2014 Pkmmte Xeleon<br>" +
            "&nbsp;*<br>" +
            "&nbsp;* Permission is hereby granted, free of charge, to any person obtaining a copy<br>" +
            "&nbsp;* of this software and associated documentation files (the \"Software\"), to deal<br>" +
            "&nbsp;* in the Software without restriction, including without limitation the rights<br>" +
            "&nbsp;* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell<br>" +
            "&nbsp;* copies of the Software, and to permit persons to whom the Software is<br>" +
            "&nbsp;* furnished to do so, subject to the following conditions:" +
            "&nbsp;*<br>" +
            "&nbsp;* The above copyright notice and this permission notice shall be included in<br>" +
            "&nbsp;* all copies or substantial portions of the Software.<br>" +
            "&nbsp;* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR<br>" +
            "&nbsp;* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,<br>" +
            "&nbsp;* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE<br>" +
            "&nbsp;* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER<br>" +
            "&nbsp;* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,<br>" +
            "&nbsp;* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN<br>" +
            "&nbsp;* THE SOFTWARE.<br>" +
            "&nbsp;*/ " +
            "<br><br></code></p>" +
            "<h3>Notices for libraries:</h3> " +
            "<ul><li>FloatingActionButton</ul></li>" +	//FloatingActionBar
            "<p style = 'background-color:#eeeeee;padding-left:1em'><code>" +
            "<br>/*<br>" +
            "&nbsp;* The MIT License (MIT)<br>" +
            "&nbsp;*<br>" +
            "&nbsp;* Copyright (c) 2014 Oleksandr Melnykov<br>" +
            "&nbsp;*<br>" +
            "&nbsp;* Permission is hereby granted, free of charge, to any person obtaining a copy<br>" +
            "&nbsp;* of this software and associated documentation files (the \"Software\"), to deal<br>" +
            "&nbsp;* in the Software without restriction, including without limitation the rights<br>" +
            "&nbsp;* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell<br>" +
            "&nbsp;* copies of the Software, and to permit persons to whom the Software is<br>" +
            "&nbsp;* furnished to do so, subject to the following conditions:" +
            "&nbsp;*<br>" +
            "&nbsp;* The above copyright notice and this permission notice shall be included in<br>" +
            "&nbsp;* all copies or substantial portions of the Software.<br>" +
            "&nbsp;* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR<br>" +
            "&nbsp;* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,<br>" +
            "&nbsp;* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE<br>" +
            "&nbsp;* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER<br>" +
            "&nbsp;* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,<br>" +
            "&nbsp;* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN<br>" +
            "&nbsp;* THE SOFTWARE.<br>" +
            "&nbsp;*/ " +
            "<br><br></code></p>" +
            "<h3>Notices for libraries:</h3>" +
            "<ul><li>Android System Bar Tint</ul></li>" +	// SystemBar tint
            "<p style = 'background-color:#eeeeee;padding-left:1em'><code>" +
            "<br>/*<br>" +
            "&nbsp;* Copyright 2013 readyState Software Limited<br>" +
            "&nbsp;* <br>" +
            "&nbsp;* Licensed under the Apache License, Version 2.0 (the \"License\");<br>" +
            "&nbsp;* you may not use this file except in compliance with the License.<br>" +
            "&nbsp;* You may obtain a copy of the License at<br>" +
            "&nbsp;* <br>" +
            "&nbsp;* &nbsp;&nbsp;&nbsp;http://www.apache.org/licenses/LICENSE-2.0<br>" +
            "&nbsp;* <br>" +
            "&nbsp;* Unless required by applicable law or agreed to in writing, software<br>" +
            "&nbsp;* distributed under the License is distributed on an \"AS IS\" BASIS,<br>" +
            "&nbsp;* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<br>" +
            "&nbsp;* See the License for the specific language governing permissions and<br>" +
            "&nbsp;* limitations under the License.<br>" +
            "&nbsp;*/ " +
            "<br><br></code></p>" +
            "<h3>Notices for libraries:</h3> " +
            "<ul><li>Material Dialogs</ul></li>" +	//Material Dialogs
            "<p style = 'background-color:#eeeeee;padding-left:1em'><code>" +
            "<br>/*<br>" +
            "&nbsp;* The MIT License (MIT)<br>" +
            "&nbsp;*<br>" +
            "&nbsp;* Copyright (c) 2014 Aidan Michael Follestad<br>" +
            "&nbsp;*<br>" +
            "&nbsp;* Permission is hereby granted, free of charge, to any person obtaining a copy<br>" +
            "&nbsp;* of this software and associated documentation files (the \"Software\"), to deal<br>" +
            "&nbsp;* in the Software without restriction, including without limitation the rights<br>" +
            "&nbsp;* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell<br>" +
            "&nbsp;* copies of the Software, and to permit persons to whom the Software is<br>" +
            "&nbsp;* furnished to do so, subject to the following conditions:" +
            "&nbsp;*<br>" +
            "&nbsp;* The above copyright notice and this permission notice shall be included in<br>" +
            "&nbsp;* all copies or substantial portions of the Software.<br>" +
            "&nbsp;* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR<br>" +
            "&nbsp;* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,<br>" +
            "&nbsp;* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE<br>" +
            "&nbsp;* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER<br>" +
            "&nbsp;* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,<br>" +
            "&nbsp;* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN<br>" +
            "&nbsp;* THE SOFTWARE.<br>" +
            "&nbsp;*/ " +
            "<br><br></code></p>" +
            "<h3>Notices for libraries:</h3>" +
            "<ul><li>UnRAR</ul></li>" +	// junRar
            "<p style = 'background-color:#eeeeee;padding-left:1em'><code>" +
            "<br>/*<br>" +
            "&nbsp;* UnRAR - free utility for RAR archives<br>" +
            "&nbsp;* License for use and distribution of<br>" +
            "&nbsp;* FREE portable version<br>" +
            "&nbsp;*/ " +
            "<br><br>" +
            "https://raw.githubusercontent.com/junrar/junrar/master/license.txt" +
            "<br><br></code></p>" +
            "<h3>Notices for libraries:</h3>" +
            "<ul><li>commons-compress</ul></li>" +	// commons-compress
            "<p style = 'background-color:#eeeeee;padding-left:1em'><code>" +
            "<br>/*<br>" +
            "&nbsp;* Copyright [yyyy] [name of copyright owner]<br>" +
            "&nbsp;* <br>" +
            "&nbsp;* Licensed under the Apache License, Version 2.0 (the \"License\");<br>" +
            "&nbsp;* you may not use this file except in compliance with the License.<br>" +
            "&nbsp;* You may obtain a copy of the License at<br>" +
            "&nbsp;* <br>" +
            "&nbsp;* &nbsp;&nbsp;&nbsp;http://www.apache.org/licenses/LICENSE-2.0<br>" +
            "&nbsp;* <br>" +
            "&nbsp;* Unless required by applicable law or agreed to in writing, software<br>" +
            "&nbsp;* distributed under the License is distributed on an \"AS IS\" BASIS,<br>" +
            "&nbsp;* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<br>" +
            "&nbsp;* See the License for the specific language governing permissions and<br>" +
            "&nbsp;* limitations under the License.<br>" +
            "&nbsp;*/ " +
            "<br><br></code></p>" +
            "<h3>Notices for libraries:</h3>" +
            "<ul><li>sticky-headers-recyclerview</ul></li>" +	// stickyHeadersRecyclerView
            "<p style = 'background-color:#eeeeee;padding-left:1em'><code>" +
            "<br>/*<br>" +
            "&nbsp;* Copyright 2014 Jacob Tabak - Timehop<br>" +
            "&nbsp;* <br>" +
            "&nbsp;* Licensed under the Apache License, Version 2.0 (the \"License\");<br>" +
            "&nbsp;* you may not use this file except in compliance with the License.<br>" +
            "&nbsp;* You may obtain a copy of the License at<br>" +
            "&nbsp;* <br>" +
            "&nbsp;* &nbsp;&nbsp;&nbsp;http://www.apache.org/licenses/LICENSE-2.0<br>" +
            "&nbsp;* <br>" +
            "&nbsp;* Unless required by applicable law or agreed to in writing, software<br>" +
            "&nbsp;* distributed under the License is distributed on an \"AS IS\" BASIS,<br>" +
            "&nbsp;* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<br>" +
            "&nbsp;* See the License for the specific language governing permissions and<br>" +
            "&nbsp;* limitations under the License.<br>" +
            "&nbsp;*/ " +
            "<br><br></code></p>" +
            "<h3>Notices for libraries:</h3>" +
            "<ul><li>Universal Image Loader</ul></li>" +	// universalImageLoader
            "<p style = 'background-color:#eeeeee;padding-left:1em'><code>" +
            "<br>/*<br>" +
            "&nbsp;* Copyright 2011-2015 Sergey Tarasevich<br>" +
            "&nbsp;* <br>" +
            "&nbsp;* Licensed under the Apache License, Version 2.0 (the \"License\");<br>" +
            "&nbsp;* you may not use this file except in compliance with the License.<br>" +
            "&nbsp;* You may obtain a copy of the License at<br>" +
            "&nbsp;* <br>" +
            "&nbsp;* &nbsp;&nbsp;&nbsp;http://www.apache.org/licenses/LICENSE-2.0<br>" +
            "&nbsp;* <br>" +
            "&nbsp;* Unless required by applicable law or agreed to in writing, software<br>" +
            "&nbsp;* distributed under the License is distributed on an \"AS IS\" BASIS,<br>" +
            "&nbsp;* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<br>" +
            "&nbsp;* See the License for the specific language governing permissions and<br>" +
            "&nbsp;* limitations under the License.<br>" +
            "&nbsp;*/ " +
            "<br><br></code></p>" +
            "</body></html>";

    public static int hourOfDay() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour <= 6 || hour >= 18) {
            return 1;
        } else
            return 0;
    }
} public class RootHelper
{
    public static String runAndWait(String cmd,boolean root)
    {

Command c=new Command(0,cmd) {
    @Override
    public void commandOutput(int i, String s) {

    }

    @Override
    public void commandTerminated(int i, String s) {

    }

    @Override
    public void commandCompleted(int i, int i2) {

    }
};
        try
        {RootTools.getShell(root).add(c);}
        catch (Exception e)
        {
            //       Logger.errorST("Exception when trying to run shell command", e);

            return null;
        }

        if (!waitForCommand(c))
        {
            return null;
        }

        return c.toString();
    }
    public static ArrayList<String> runAndWait1(String cmd, final boolean root)
    {
        final ArrayList<String> output=new ArrayList<String>();
Command cc=new Command(1,cmd) {
    @Override
    public void commandOutput(int i, String s) {
        output.add(s);
//        System.out.println("output "+root+s);
    }

    @Override
    public void commandTerminated(int i, String s) {

        System.out.println("error"+root+s);

    }

    @Override
    public void commandCompleted(int i, int i2) {

    }
};
        try {
            RootTools.getShell(root).add(cc);
        }
        catch (Exception e)
        {
            //       Logger.errorST("Exception when trying to run shell command", e);
e.printStackTrace();
            return null;
        }

        if (!waitForCommand(cc))
        {
            return null;
        }

        return output;
    }
    private static boolean waitForCommand(Command cmd)
    {
        while (!cmd.isFinished())
        {
            synchronized (cmd)
            {
                try
                {
                    if (!cmd.isFinished())
                    {
                        cmd.wait(2000);
                    }
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }

            if (!cmd.isExecuting() && !cmd.isFinished())
            {
                //         Logger.errorST("Error: Command is not executing and is not finished!");
                return false;
            }
        }

        //Logger.debug("Command Finished!");
        return true;
    }


    public static String getCommandLineString(String input) {
        return input.replaceAll(UNIX_ESCAPE_EXPRESSION, "\\\\$1");
    }	private static final String UNIX_ESCAPE_EXPRESSION = "(\\(|\\)|\\[|\\]|\\s|\'|\"|`|\\{|\\}|&|\\\\|\\?)";
    static Futils futils=new Futils();
    public static ArrayList<String[]> getFilesList(boolean showSize,String path,boolean showHidden){
        File f=new File(path);
        ArrayList<String[]> files=new ArrayList<String[]>();
        try {
            if(f.exists() && f.isDirectory()){
                for(File x:f.listFiles()){
                    String k="",size="";
                    if(x.isDirectory())
                    {k="-1";
                    if(showSize)size=""+getCount(x);
                    }else if(showSize)size=""+x.length();
                    if(showHidden){
                        files.add(new String[]{x.getPath(),"",parseFilePermission(x),k,x.lastModified()+"",size});
                    }
                    else{if(!x.isHidden()){files.add(new String[]{x.getPath(),"",parseFilePermission(x),k,x.lastModified()+"",size});}}
                }
            }}catch (Exception e){}


        return files;}
    public static String parseFilePermission(File f){
        String per="";
        if(f.canRead()){per=per+"r";}
        if(f.canWrite()){per=per+"w";}
        if(f.canExecute()){per=per+"x";}
        return  per;}
    public static ArrayList<String[]> getFilesList(String path,boolean root,boolean showHidden,boolean showSize)
    {
        String p = " ";
        if (showHidden) p = "a ";
        Futils futils = new Futils();
        ArrayList<String[]> a = new ArrayList<String[]>();
        ArrayList<String> ls = new ArrayList<String>();
        if (root) {
            if (!path.startsWith("/storage")) {
                String cpath = getCommandLineString(path);
                ls = runAndWait1("ls -l" + p + cpath, root);
                for (String file : ls) {
                    if (!file.contains("Permission denied"))
                        try {
                            String[] array = futils.parseName(file);
                            array[0] = path + "/" + array[0];
                            a.add(array);
                        } catch (Exception e) {
                            System.out.println(file);
                            e.printStackTrace();
                        }

                }
            } else if (futils.canListFiles(new File(path))) {
                a = getFilesList(showSize,path, showHidden);
            } else {
                a = new ArrayList<String[]>();
            }
        } else if (futils.canListFiles(new File(path))) {
            a = getFilesList(showSize,path, showHidden);
        } else {
            a = new ArrayList<String[]>();
        }
        if (a.size() == 0 && futils.canListFiles(new File(path))) {
            a = getFilesList(showSize,path, showHidden);
        }
        return a;

    }

    public static Integer getCount(File f){
        if(f.exists() && f.canRead() && f.isDirectory()){
            try{return f.listFiles().length;}catch(Exception e){return 0;}
        }
        return  null;}} public class RoundedImageView extends ImageView {

    public RoundedImageView(Context ctx, AttributeSet attrs) {
        super(ctx, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth(), h = getHeight();

        Bitmap roundBitmap = getRoundedCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) {
        Bitmap finalBitmap;
        if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
            finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
                    false);
        else
            finalBitmap = bitmap;
        Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
                finalBitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
                finalBitmap.getHeight());

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor("#BAB399"));
        canvas.drawCircle(finalBitmap.getWidth() / 2 + 0.7f,
                finalBitmap.getHeight() / 2 + 0.7f,
                finalBitmap.getWidth() / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(finalBitmap, rect, rect, paint);

        return output;
    }

} public class ScrimInsetsRelativeLayout extends RelativeLayout {
    private Drawable mInsetForeground;

    private Rect mInsets;
    private Rect mTempRect = new Rect();
    private OnInsetsCallback mOnInsetsCallback;

    public ScrimInsetsRelativeLayout(Context context) {
        super(context);
        init(context, null, 0);
    }

    public ScrimInsetsRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public ScrimInsetsRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        final TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.ScrimInsetsView, defStyle, 0);
        if (a == null) {
            return;
        }
        mInsetForeground = a.getDrawable(R.styleable.ScrimInsetsView_insetForeground);
        a.recycle();

        setWillNotDraw(true);
    }

    @Override
    protected boolean fitSystemWindows(Rect insets) {
        mInsets = new Rect(insets);
        setWillNotDraw(mInsetForeground == null);
        ViewCompat.postInvalidateOnAnimation(this);
        if (mOnInsetsCallback != null) {
            mOnInsetsCallback.onInsetsChanged(insets);
        }
        return true; // consume insets
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

        int width = getWidth();
        int height = getHeight();
        if (mInsets != null && mInsetForeground != null) {
            int sc = canvas.save();
            canvas.translate(getScrollX(), getScrollY());

            // Top
            mTempRect.set(0, 0, width, mInsets.top);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Bottom
            mTempRect.set(0, height - mInsets.bottom, width, height);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Left
            mTempRect.set(0, mInsets.top, mInsets.left, height - mInsets.bottom);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Right
            mTempRect.set(width - mInsets.right, mInsets.top, width, height - mInsets.bottom);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            canvas.restoreToCount(sc);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (mInsetForeground != null) {
            mInsetForeground.setCallback(this);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mInsetForeground != null) {
            mInsetForeground.setCallback(null);
        }
    }

    /**
     * Allows the calling container to specify a callback for custom processing when insets change (i.e. when
     * {@link #fitSystemWindows(Rect)} is called. This is useful for setting padding on UI elements based on
     * UI chrome insets (e.g. a Google Map or a ListView). When using with ListView or GridView, remember to set
     * clipToPadding to false.
     */
    public void setOnInsetsCallback(OnInsetsCallback onInsetsCallback) {
        mOnInsetsCallback = onInsetsCallback;
    }

    public static interface OnInsetsCallback {
        public void onInsetsChanged(Rect insets);
    }
} public class Shortcuts {
    Context context;
    String path;
    public Shortcuts(Context context) {
        this.context=context;
        path=context.getFilesDir()+"/shortcut.xml";
    }

    public void makeS() throws ParserConfigurationException, TransformerException {
        String sd = Environment.getExternalStorageDirectory() + "/";
        String[] a = new String[]{sd + Environment.DIRECTORY_DCIM, sd + Environment.DIRECTORY_DOWNLOADS, sd + Environment.DIRECTORY_MOVIES, sd + Environment.DIRECTORY_MUSIC, sd + Environment.DIRECTORY_PICTURES};
        File g = new File(path);
        if (!g.exists()) {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

// root elements
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("shortcut");
            doc.appendChild(rootElement);
            for (int i = 0; i < a.length; i++) {
                Element staff = doc.createElement("path");
                staff.appendChild(doc.createTextNode(a[i]));
                rootElement.appendChild(staff);
            }
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(g);
            transformer.transform(source, result);
        }
    }

    public void addS(File f) throws Exception {
        File g = new File(path);
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

// root elements
        Document doc = docBuilder.parse(g);
        NodeList nList = doc.getElementsByTagName("shortcut");
        Node nNode = nList.item(0);
        Element eElement = (Element) nNode;


// f elements
        Element staff = doc.createElement("path");
        staff.appendChild(doc.createTextNode(f.getPath()));
        eElement.appendChild(staff);


        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(path));
        transformer.transform(source, result);

    }

    public ArrayList<File> readS() throws FileNotFoundException, IOException, SAXException, ParserConfigurationException {
        ArrayList<File> f = new ArrayList<File>();
        File g = new File(path);
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

// root elements
        Document doc = docBuilder.parse(g);
        NodeList nList = doc.getElementsByTagName("path");
        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                f.add(new File(nNode.getTextContent()));
            }
        }
        return f;
    }

    public boolean isShortcut(File f) throws IOException, ParserConfigurationException, SAXException {
        boolean b = false;
        ArrayList<File> x = readS();
        for (int i = 0; i < x.size(); i++) {
            if (x.get(i) == f) {
                b = true;
            } else {
                b = false;
            }
        }
        return b;
    }

    public void removeS(File f1, Context s) throws IOException, SAXException, ParserConfigurationException, TransformerException {
        //	ArrayList<File> f=new ArrayList<File>();
        File g = new File(path);
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

// root elements
        Document doc = docBuilder.parse(g);
        NodeList List = doc.getElementsByTagName("shortcut");
        Node n = List.item(0);

        NodeList nList = n.getChildNodes();

        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);

            if (nNode.getTextContent().equals(f1.getPath())) {
                //Element e=(Element)nNode;
                n.removeChild(nNode);

            }
        }
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(path));
        transformer.transform(source, result);
    }
}
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.Theme;
import com.amaze.filemanager.R;
import com.amaze.filemanager.adapters.DrawerAdapter;
import com.amaze.filemanager.database.TabHandler;
import com.amaze.filemanager.fragments.AppsList;
import com.amaze.filemanager.fragments.Main;
import com.amaze.filemanager.fragments.ProcessViewer;
import com.amaze.filemanager.fragments.RarViewer;
import com.amaze.filemanager.fragments.TabFragment;
import com.amaze.filemanager.fragments.ZipViewer;
import com.amaze.filemanager.services.CopyService;
import com.amaze.filemanager.services.SearchService;
import com.amaze.filemanager.services.asynctasks.MoveFiles;
import com.amaze.filemanager.utils.Futils;
import com.amaze.filemanager.utils.IconUtils;
import com.amaze.filemanager.utils.MediaFile;
import com.amaze.filemanager.utils.PreferenceUtils;
import com.amaze.filemanager.utils.RootHelper;
import com.amaze.filemanager.utils.RoundedImageView;
import com.amaze.filemanager.utils.ScrimInsetsRelativeLayout;
import com.amaze.filemanager.utils.Shortcuts;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;
import com.melnykov.fab.FloatingActionButton;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.stericson.RootTools.RootTools;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
                ba1.title(R.string.newfolder);
                View v = getLayoutInflater().inflate(R.layout.dialog, null);
                final EditText edir = (EditText) v.findViewById(R.id.newname);
                edir.setHint(utils.getString(this, R.string.entername));
                ba1.customView(v, true);
                if(theme1==1)ba1.theme(Theme.DARK);
                ba1.positiveText(R.string.create);
                ba1.negativeText(R.string.cancel);
                ba1.positiveColor(Color.parseColor(fabskin));
                ba1.negativeColor(Color.parseColor(fabskin));
                ba1.callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onPositive(MaterialDialog materialDialog) {
                        String a = edir.getText().toString();
                        File f = new File(path + "/" + a);
                        boolean b=false;
                        if (!f.exists()) {
                            b=f.mkdirs();
                            ma.updateList();
                            if(b)
                                Toast.makeText(mainActivity, (R.string.foldercreated), Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mainActivity, ( R.string.fileexist), Toast.LENGTH_LONG).show();
                        }
                        if(!b && rootmode){
                            RootTools.remount(f.getParent(), "rw");
                            RootHelper.runAndWait("mkdir "+f.getPath(),true);
                            ma.updateList();
                        }
                        else if(!b && !rootmode){
                            try {
                                new MediaFile(mainActivity,f).mkdir();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onNegative(MaterialDialog materialDialog) {

                    }
                });
                ba1.build().show();
                break;
            case 1:
                final String path1 = ma.current;
                final MaterialDialog.Builder ba2 = new MaterialDialog.Builder(this);
                ba2.title((R.string.newfile));
                View v1 = getLayoutInflater().inflate(R.layout.dialog, null);
                final EditText edir1 = (EditText) v1.findViewById(R.id.newname);
                edir1.setHint(utils.getString(this, R.string.entername));
                ba2.customView(v1, true);
                if(theme1==1)ba2.theme(Theme.DARK);
                ba2.negativeText(R.string.cancel);
                ba2.positiveText(R.string.create);
                ba2.positiveColor(Color.parseColor(fabskin));
                ba2.negativeColor(Color.parseColor(fabskin));
                ba2.callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onPositive(MaterialDialog materialDialog) {
                        String a = edir1.getText().toString();boolean b=false;
                        File f1 = new File(path1 + "/" + a);
                        if (!f1.exists()) {
                            try {
                                b = f1.createNewFile();
                                ma.updateList();
                                Toast.makeText(mainActivity, ( R.string.filecreated), Toast.LENGTH_LONG).show();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            Toast.makeText(mainActivity,( R.string.fileexist), Toast.LENGTH_LONG).show();
                        }if(!b && rootmode)RootTools.remount(f1.getParent(),"rw");
                        RootHelper.runAndWait("touch "+f1.getPath(),true);
                        ma.updateList();
                    }

                    @Override
                    public void onNegative(MaterialDialog materialDialog) {

                    }
                });
                ba2.build().show();
                break;
        }
    }


    public void search() {
        final Main ma=(Main)((TabFragment)getSupportFragmentManager().findFragmentById(R.id.content_frame)).getTab();
        final String fpath = ma.current;
        final MaterialDialog.Builder a = new MaterialDialog.Builder(this);
        a.title(R.string.search);
        View v =getLayoutInflater().inflate(R.layout.dialog, null);
        final EditText e = (EditText) v.findViewById(R.id.newname);
        e.setHint(utils.getString(this, R.string.enterfile));
        a.customView(v, true);
        e.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                e.post(new Runnable() {
                    @Override
                    public void run() {
                        InputMethodManager inputMethodManager= (InputMethodManager) MainActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                        inputMethodManager.showSoftInput(e, InputMethodManager.SHOW_IMPLICIT);
                    }
                });
            }
        });
        e.requestFocus();
        if(theme1==1)a.theme(Theme.DARK);
        a.negativeText(R.string.cancel);
        a.positiveText(R.string.search);
        a.positiveColor(Color.parseColor(fabskin));
        a.negativeColor(Color.parseColor(fabskin));
        a.callback(new MaterialDialog.ButtonCallback() {
            @Override
            public void onPositive(MaterialDialog materialDialog) {
                String a = e.getText().toString();
                Intent i=new Intent(con, SearchService.class);