com.sentaroh.android.TextFileBrowser.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.sentaroh.android.TextFileBrowser.MainActivity.java

Source

package com.sentaroh.android.TextFileBrowser;

/*
The MIT License (MIT)
Copyright (c) 2011-2013 Sentaroh
    
Permission is hereby granted, free of charge, to any person obtaining a copy of 
this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to 
the following conditions:
    
The above copyright notice and this permission notice shall be included in all copies or 
substantial portions of the Software.
    
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
    
*/

import static com.sentaroh.android.TextFileBrowser.Constants.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;

import com.sentaroh.android.Utilities.ContentProviderUtil;
import com.sentaroh.android.Utilities.LocalMountPoint;
import com.sentaroh.android.Utilities.NotifyEvent;
import com.sentaroh.android.Utilities.NotifyEvent.NotifyEventListener;
import com.sentaroh.android.Utilities.ThemeUtil;
import com.sentaroh.android.Utilities.ThreadCtrl;
import com.sentaroh.android.Utilities.Dialog.CommonDialog;
import com.sentaroh.android.Utilities.Dialog.FileSelectDialogFragment;

@SuppressLint("NewApi")
public class MainActivity extends AppCompatActivity {

    private GlobalParameters mGlblParms = null;

    private boolean mTerminateApplication = false;
    private int mRestartStatus = 0;

    private Spinner mViewedFileListSpinner = null;
    private int mSavedViewedFileListSpinnerPosition = -1;
    private ViewedFileListAdapter mViewedFileListAdapter = null;
    private CommonDialog mCommonDlg = null;

    private FragmentManager mFragmentManager = null;

    private Context mContext;
    private Activity mActivity;

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "onSaveInstanceState entered");

        saveViewContents(outState);
    };

    private void saveViewContents(Bundle outState) {
        outState.putInt("SpinnerPos", mViewedFileListSpinner.getSelectedItemPosition());
        outState.putInt("FAH_Size", mGlblParms.viewedFileList.size());
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024 * 32);
            ObjectOutputStream oos = new ObjectOutputStream(bos);

            for (int i = 0; i < mGlblParms.viewedFileList.size(); i++) {
                ViewedFileListItem vfli = mGlblParms.viewedFileList.get(i);
                vfli.writeExternal(oos);
            }
            oos.flush();
            byte[] buf = bos.toByteArray();
            outState.putByteArray("FAH_List", buf);
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    };

    @Override
    protected void onRestoreInstanceState(Bundle savedState) {
        super.onRestoreInstanceState(savedState);
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "onRestoreInstanceState entered");
        restoreViewContents(savedState);
        mRestartStatus = 2;
    };

    private void restoreViewContents(Bundle savedState) {
        mSavedViewedFileListSpinnerPosition = savedState.getInt("SpinnerPos");
        byte[] buf = savedState.getByteArray("FAH_List");
        int list_size = savedState.getInt("FAH_Size");
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(buf);
            ObjectInputStream ois = new ObjectInputStream(bis);
            mGlblParms.viewedFileList = new ArrayList<ViewedFileListItem>();
            for (int i = 0; i < list_size; i++) {
                ViewedFileListItem vfli = new ViewedFileListItem();
                vfli.readExternal(ois);
                mGlblParms.viewedFileList.add(vfli);
            }

            ois.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "onNewIntent entered, restartStatus=" + mRestartStatus);
        if (mRestartStatus == 2)
            return;
        String fp = "";
        String cd = getCacheDir() + "/attached/";
        if (intent.getData() != null)
            fp = ContentProviderUtil.getFilePath(mContext, cd, intent.getData());
        //      if (intent!=null) if (intent.getDataString()!=null) fp=intent.getDataString().replace("file://", "");
        if (fp == null || fp.equals("")) {
            if (mGlblParms.currentViewedFile.equals("")) {
                showFileSelectDialog();
                //            finish();
            }
        } else {
            if (!isFileAlreadyViewed(fp)) {
                addFileToViewedFileList(true, fp);
            } else {
                showFileByViewedFileList(fp);
            }
            refreshOptionMenu();
        }
    };

    private void initViewWidget() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        setContentView(R.layout.text_browser_activity);

        if (mGlblParms.viewedFileList == null)
            mGlblParms.viewedFileList = new ArrayList<ViewedFileListItem>();

        initFileSelectionSpinner();
    };

    private void initFileSelectionSpinner() {
        mViewedFileListSpinner = (Spinner) findViewById(R.id.text_browser_activity_file_view_selector);
        mViewedFileListAdapter = new ViewedFileListAdapter(this, R.layout.custom_simple_spinner_item,
                mGlblParms.viewedFileList);
        mViewedFileListAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mViewedFileListSpinner.setPrompt(mContext.getString(R.string.msgs_text_browser_select_view_file));
        mViewedFileListSpinner.setAdapter(mViewedFileListAdapter);
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        mContext = this;
        mActivity = this;
        mFragmentManager = getSupportFragmentManager();
        mRestartStatus = 0;
        if (mGlblParms == null) {
            mGlblParms = (GlobalParameters) getApplication();
        }
        if (mGlblParms.commonNotification == null)
            mGlblParms.commonNotification = new NotificationCommonParms();
        initSettingParms();
        setTheme(mGlblParms.screenTheme);
        mGlblParms.themeColorList = ThemeUtil.getThemeColorList(mActivity);
        super.onCreate(savedInstanceState);

        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "onCreate entered");

        //      if (Build.VERSION.SDK_INT>=14) getActionBar().setHomeButtonEnabled(false);

        mCommonDlg = new CommonDialog(mActivity, mFragmentManager);

        initViewWidget();

        //        SortedMap<String, Charset> ac=Charset.availableCharsets();
        //        Set<String> ks=ac.keySet();
        //        Object[] ka=ks.toArray();
        //        Log.v("","ka="+ka.length);
        //        for (int i=0;i<ka.length;i++) {
        //           Log.v("","i="+i+", k="+ka[i]);
        //        }

    };

    @Override
    public void onStart() {
        super.onStart();
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "onStart entered");
    };

    @Override
    public void onRestart() {
        super.onStart();
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "onRestart entered");
    };

    @Override
    public void onResume() {
        super.onResume();
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "onResume entered, restartStatus=" + mRestartStatus);
        String fp = "";

        if (mRestartStatus == 0) {
            Intent in = getIntent();
            String cd = getCacheDir() + "/attached/";
            if (in.getData() != null)
                fp = ContentProviderUtil.getFilePath(mContext, cd, in.getData());
            if (fp == null || fp.equals("")) {
                NotificationUtil.initNotification(mContext, mGlblParms.commonNotification);
                showFileSelectDialog();
                //            if (getViewedFileListCount()==0) mTerminateApplication=true;
                //            finish();
            } else {
                NotificationUtil.initNotification(mContext, mGlblParms.commonNotification);
                NotificationUtil.clearNotification(mContext, mGlblParms.commonNotification);
                if (!isFileAlreadyViewed(fp)) {
                    addFileToViewedFileList(true, fp);
                    showFileByViewedFileList(fp);
                } else {
                    showFileByViewedFileList(fp);
                }
                NotificationUtil.showOngoingNotificationMsg(mContext, mGlblParms.commonNotification, fp);
            }
        } else if (mRestartStatus == 1) {
        } else if (mRestartStatus == 2) {
            NotificationUtil.initNotification(mContext, mGlblParms.commonNotification);
            for (int i = 0; i < mGlblParms.viewedFileList.size(); i++) {
                ViewedFileListItem vfli = mGlblParms.viewedFileList.get(i);

                vfli.viewerParmsInitRequired = false;
                vfli.viewerParmsRestoreRequired = true;
                vfli.encodeName = "";

                vfli.file_view_fragment = FileViewerFragment.newInstance(vfli.file_path);
                vfli.tc_view = new ThreadCtrl();
                vfli.ix_reader_view = new IndexedFileReader(mGlblParms.debugEnabled,
                        mGlblParms.settingAlwayDeterminCharCode, this, mCommonDlg, vfli.tc_view,
                        mGlblParms.settingEncodeName, mGlblParms.settingIndexCache,
                        mGlblParms.settingBufferCharIndexSize, mGlblParms.settingBufferHexIndexSize,
                        mGlblParms.settingBufferPoolSize, this);
                //            mViewedFileListAdapter.notifyDataSetChanged();
                if (i == mSavedViewedFileListSpinnerPosition)
                    mGlblParms.currentViewedFile = vfli.file_path;
            }
            initFileSelectionSpinner();

            mCommonDlg.showCommonDialog(false, "W", getString(R.string.msgs_tb_application_restarted), "", null);

            showFileByViewedFileList(mGlblParms.currentViewedFile);

            NotificationUtil.showOngoingNotificationMsg(mContext, mGlblParms.commonNotification,
                    mGlblParms.currentViewedFile);
            mViewedFileListSpinner.setSelection(mSavedViewedFileListSpinnerPosition);

        }
        mRestartStatus = 1;

        setViewedFilleSelectorListener();

        Handler hndl = new Handler();
        hndl.postDelayed(new Runnable() {
            @Override
            public void run() {
                mEnableFileSelection = true;
            }
        }, 500);

    };

    private boolean isFileAlreadyViewed(String fp) {
        boolean result = false;
        for (int i = 0; i < getViewedFileListCount(); i++) {
            if (mGlblParms.viewedFileList.get(i).file_path.equals(fp)) {
                result = true;
                break;
            }
        }
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "isFileAlreadyViewed, fp=" + fp + ", result=" + result);
        return result;
    };

    private int getViewedFileListCount() {
        int result = 0;
        if (mGlblParms.viewedFileList != null)
            result = mGlblParms.viewedFileList.size();
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "getViewedFileListCount, result=" + result);
        return result;
    };

    private void addFileToViewedFileList(boolean set_selection, String fp) {
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "addFileToViewedFileList, fp=" + fp);
        ViewedFileListItem vfli = new ViewedFileListItem();
        vfli.file_path = fp;
        vfli.file_name = fp.substring(fp.lastIndexOf("/") + 1);

        String ft = "";
        if (vfli.file_name.lastIndexOf(".") >= 0)
            ft = vfli.file_name.substring(vfli.file_name.lastIndexOf(".") + 1);
        String mt = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ft);
        if (mt != null && mt.startsWith("text"))
            vfli.browseMode = FileViewerAdapter.TEXT_BROWSER_BROWSE_MODE_CHAR;
        else
            vfli.browseMode = FileViewerAdapter.TEXT_BROWSER_BROWSE_MODE_HEX;

        vfli.tc_view = new ThreadCtrl();
        mGlblParms.viewedFileList.add(vfli);

        vfli.ix_reader_view = new IndexedFileReader(mGlblParms.debugEnabled,
                mGlblParms.settingAlwayDeterminCharCode, this, mCommonDlg, vfli.tc_view,
                mGlblParms.settingEncodeName, mGlblParms.settingIndexCache, mGlblParms.settingBufferCharIndexSize,
                mGlblParms.settingBufferHexIndexSize, mGlblParms.settingBufferPoolSize, this);
        mViewedFileListAdapter.notifyDataSetChanged();
        vfli.file_view_fragment = FileViewerFragment.newInstance(fp);

        if (set_selection)
            mViewedFileListSpinner.setSelection(mGlblParms.viewedFileList.size() - 1);
    };

    private void removeFileFromViewedFileList(String fp) {
        ViewedFileListItem vfli = null;
        int rem_pos = -1;
        for (int i = 0; i < getViewedFileListCount(); i++) {
            if (mViewedFileListAdapter.getItem(i).file_path.equals(fp)) {
                vfli = mGlblParms.viewedFileList.get(i);
                Log.v("", "fp=" + vfli.file_path);
                Log.v("", "frag=" + vfli.file_view_fragment);
                if (vfli.file_view_fragment != null) {
                    mFragmentManager.beginTransaction().setTransition(FragmentTransaction.TRANSIT_NONE)
                            .remove(vfli.file_view_fragment).commit();
                }
                mGlblParms.viewedFileList.remove(i);
                mViewedFileListAdapter.notifyDataSetChanged();
                rem_pos = i;
                mGlblParms.currentViewedFile = "";
                break;
            }
        }
        if (rem_pos != -1) {
            if (rem_pos > 1) {
                //            mViewedFileListSpinner.setSelection(rem_pos-1);
                showFileByViewedFileList(mViewedFileListAdapter.getItem(rem_pos - 1).file_path);
                NotificationUtil.showOngoingNotificationMsg(mContext, mGlblParms.commonNotification,
                        mGlblParms.currentViewedFile);
            } else {
                if (getViewedFileListCount() > 0) {
                    //               mViewedFileListSpinner.setSelection(0);
                    showFileByViewedFileList(mViewedFileListAdapter.getItem(0).file_path);
                    NotificationUtil.showOngoingNotificationMsg(mContext, mGlblParms.commonNotification,
                            mGlblParms.currentViewedFile);
                }
            }
        }
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "removeFileFromViewedFileList, fp=" + fp + ", result=" + rem_pos);
    };

    private ViewedFileListItem getViewedFileListItem(String fp) {
        ViewedFileListItem vfli = null;
        int pos = -1;
        for (int i = 0; i < getViewedFileListCount(); i++) {
            if (mGlblParms.viewedFileList.get(i).file_path.equals(fp)) {
                vfli = mGlblParms.viewedFileList.get(i);
                pos = i;
                break;
            }
        }
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "getViewedFileListItem, fp=" + fp + ", result=" + pos);
        //      Thread.dumpStack();
        return vfli;
    };

    private void showFileByViewedFileList(String fp) {
        int pos = -1;
        for (int i = 0; i < getViewedFileListCount(); i++) {
            ViewedFileListItem vfli = mGlblParms.viewedFileList.get(i);
            if (vfli.file_path.equals(fp)) {
                if (vfli.file_view_fragment != null) {
                    FragmentTransaction ft = mFragmentManager.beginTransaction();
                    ft.setTransition(FragmentTransaction.TRANSIT_NONE);
                    ft.replace(R.id.container, vfli.file_view_fragment);
                    ft.commit();
                } else {
                    vfli.file_view_fragment = FileViewerFragment.newInstance(fp);
                    FragmentTransaction ft = mFragmentManager.beginTransaction();
                    ft.setTransition(FragmentTransaction.TRANSIT_NONE);
                    ft.replace(R.id.container, vfli.file_view_fragment);
                    ft.commit();
                }
                mGlblParms.currentViewedFile = mGlblParms.viewedFileList.get(i).file_path;
                pos = i;
                break;
            }
        }
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "showFileByViewedFileList, fp=" + fp + ", result=" + pos);
    };

    @Override
    public void onPause() {
        super.onPause();
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "onPause entered");
        // Application process is follow
    };

    @Override
    public void onStop() {
        super.onStop();
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "onStop entered");
        // Application process is follow
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "onDestroy entered");
        // Application process is follow
        if (mTerminateApplication) {
            NotificationUtil.clearNotification(mContext, mGlblParms.commonNotification);
            //         deleteTaskData();
            if (mGlblParms.settingExitCleanly) {
                Handler hndl = new Handler();
                hndl.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                }, 200);
            } else {
                mGlblParms.viewedFileList = null;
                mGlblParms.commonNotification = null;
                mGlblParms = null;
                System.gc();
            }
        } else {

        }
    };

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_BACK:
            if (getViewedFileListCount() > 1) {
                NotifyEvent ntfy = new NotifyEvent(mContext);
                ntfy.setListener(new NotifyEventListener() {
                    @Override
                    public void positiveResponse(Context c, Object[] o) {
                        confirmCloseFile();
                    }

                    @Override
                    public void negativeResponse(Context c, Object[] o) {
                    }
                });
                mCommonDlg.showCommonDialog(true, "W", getString(R.string.msgs_tb_menu_close_confirm_msg), "",
                        ntfy);
            } else {
                confirmExit();
            }
            return true;
        // break;
        default:
            return super.onKeyDown(keyCode, event);
        // break;
        }
    };

    private void confirmCloseFile() {
        final ViewedFileListItem vfli = getViewedFileListItem(mGlblParms.currentViewedFile);
        //      final FileViewerFragment fvf=(FileViewerFragment) vfli.file_view_fragment;
        if (vfli.tc_view.isThreadActive()) {
            NotifyEvent ntfy = new NotifyEvent(mContext);
            ntfy.setListener(new NotifyEventListener() {
                @Override
                public void positiveResponse(Context c, Object[] o) {
                    if (vfli.tc_view.isThreadActive())
                        vfli.tc_view.setDisabled();
                    removeFileFromViewedFileList(mGlblParms.currentViewedFile);
                    if (getViewedFileListCount() < 1) {
                        mTerminateApplication = true;
                        finish();
                    }
                }

                @Override
                public void negativeResponse(Context c, Object[] o) {
                }
            });
            mCommonDlg.showCommonDialog(true, "W",
                    getString(R.string.msgs_text_browser_file_reading_cancel_confirm), "", ntfy);
        } else {
            removeFileFromViewedFileList(mGlblParms.currentViewedFile);
            if (getViewedFileListCount() < 1) {
                mTerminateApplication = true;
                finish();
            }
        }
    };

    @SuppressLint("NewApi")
    public void refreshOptionMenu() {
        if (Build.VERSION.SDK_INT >= 11)
            invalidateOptionsMenu();
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "onCreateOptionsMenu Entered");
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_tb_setting, menu);
        return true;
    };

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "onPrepareOptionsMenu Entered");
        super.onPrepareOptionsMenu(menu);
        ViewedFileListItem vf = getViewedFileListItem(mGlblParms.currentViewedFile);
        if (vf != null) {
            //         FileViewerFragment fvf=(FileViewerFragment)vf.file_view_fragment;
            //         Log.v("","mode="+vf.browseMode+", t="+vf.tc_view.isThreadActive());
            if (vf.browseMode == FileViewerAdapter.TEXT_BROWSER_BROWSE_MODE_CHAR) {
                menu.findItem(R.id.menu_tb_mode_swicth).setTitle(getString(R.string.msgs_tb_menu_mode_switch_hex))
                        .setIcon(R.drawable.ic_32_hex);
                menu.findItem(R.id.menu_tb_settings).setVisible(true);
                menu.findItem(R.id.menu_tb_mode_swicth).setVisible(true);
                menu.findItem(R.id.menu_tb_reload).setVisible(true);
                menu.findItem(R.id.menu_tb_open).setVisible(true);
                menu.findItem(R.id.menu_tb_find).setVisible(true);
                menu.findItem(R.id.menu_tb_about).setVisible(true);
            } else {
                menu.findItem(R.id.menu_tb_mode_swicth).setTitle(getString(R.string.msgs_tb_menu_mode_switch_char))
                        .setIcon(R.drawable.ic_32_text);
                menu.findItem(R.id.menu_tb_settings).setVisible(true);
                menu.findItem(R.id.menu_tb_mode_swicth).setVisible(true);
                menu.findItem(R.id.menu_tb_reload).setVisible(true);
                menu.findItem(R.id.menu_tb_open).setVisible(true);
                menu.findItem(R.id.menu_tb_find).setVisible(false);
                menu.findItem(R.id.menu_tb_about).setVisible(true);
            }
            if (vf.tc_view.isThreadActive()) {
                menu.findItem(R.id.menu_tb_settings).setEnabled(false);
                menu.findItem(R.id.menu_tb_mode_swicth).setEnabled(false);
                menu.findItem(R.id.menu_tb_reload).setEnabled(false);
                menu.findItem(R.id.menu_tb_open).setVisible(false);
                //            menu.findItem(R.id.menu_tb_open).setEnabled(false);
                menu.findItem(R.id.menu_tb_find).setEnabled(false);
                menu.findItem(R.id.menu_tb_about).setEnabled(false);
            } else {
                menu.findItem(R.id.menu_tb_settings).setEnabled(true);
                menu.findItem(R.id.menu_tb_mode_swicth).setEnabled(true);
                menu.findItem(R.id.menu_tb_reload).setEnabled(true);
                menu.findItem(R.id.menu_tb_open).setVisible(true);
                //            menu.findItem(R.id.menu_tb_open).setEnabled(true);
                menu.findItem(R.id.menu_tb_find).setEnabled(true);
                menu.findItem(R.id.menu_tb_about).setEnabled(true);
            }
        }
        return true;
    };

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "onOptionsItemSelected Entered");
        ViewedFileListItem vf = getViewedFileListItem(mGlblParms.currentViewedFile);
        FileViewerFragment fvf = (FileViewerFragment) vf.file_view_fragment;
        if (item.getItemId() == R.id.menu_tb_settings) {
            invokeSettings();
            refreshOptionMenu();
        } else if (item.getItemId() == R.id.menu_tb_open) {
            showFileSelectDialog();
        } else if (item.getItemId() == R.id.menu_tb_reload) {
            fvf.reloadFile();
        } else if (item.getItemId() == R.id.menu_tb_mode_swicth) {
            fvf.switchDisplayMode();
            refreshOptionMenu();
        } else if (item.getItemId() == R.id.menu_tb_find) {
            fvf.switchFindWidget();
            refreshOptionMenu();
            //      } else if (item.getItemId()== R.id.menu_tb_encode) {
            //         EncodeSelectorFragment esfm=EncodeSelectorFragment.newInstance();
            //         esfm.showDialog(mFragmentManager, esfm, 
            //               getViewedFileListItem(mGlblParms.currentViewedFile));
            //         refreshOptionMenu();
        } else if (item.getItemId() == R.id.menu_tb_about) {
            aboutTextFileBrowser();
        } else if (item.getItemId() == R.id.menu_tb_exit) {
            confirmExit();
        }
        return false;
    };

    public boolean isApplicationTerminating() {
        return mTerminateApplication;
    }

    private void confirmExit() {
        NotifyEvent ntfy = new NotifyEvent(mContext);
        ntfy.setListener(new NotifyEventListener() {
            @Override
            public void positiveResponse(Context c, Object[] o) {
                ViewedFileListItem vfli = getViewedFileListItem(mGlblParms.currentViewedFile);
                //            mFragmentManager.beginTransaction().remove(vfli.file_view_fragment).commit();
                //            mGlblParms.viewedFileList.remove(vfli);

                for (int i = 0; i < mGlblParms.viewedFileList.size(); i++) {
                    vfli = mGlblParms.viewedFileList.get(i);
                    if (vfli.tc_view.isThreadActive()) {
                        vfli.tc_view.setDisabled();
                    }
                }
                mTerminateApplication = true;
                mGlblParms.viewedFileList.clear();
                finish();
            }

            @Override
            public void negativeResponse(Context c, Object[] o) {
            }
        });
        mCommonDlg.showCommonDialog(true, "W", mContext.getString(R.string.msgs_tb_menu_exit_confirm_msg), "",
                ntfy);
    };

    private void aboutTextFileBrowser() {
        mCommonDlg.showCommonDialog(false, "I", getString(R.string.msgs_tb_menu_about),
                String.format(getString(R.string.msgs_text_browser_about_tb), getApplVersionName()), null);
    };

    public String getApplVersionName() {
        try {
            String packegeName = getPackageName();
            PackageInfo packageInfo = getPackageManager().getPackageInfo(packegeName, PackageManager.GET_META_DATA);
            return packageInfo.versionName;
        } catch (NameNotFoundException e) {
            return "";
        }
    };

    public void invokeSettings() {
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "invokeSettings Entered");
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivityForResult(intent, 0);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "Return from settings");
        if (requestCode == 0)
            applySettingParms();
    };

    private void applySettingParms() {
        int lb = mGlblParms.settingLineBreak;
        int tab_stop = mGlblParms.settingTabStop;
        String fn = mGlblParms.settingFontFamily;
        String fs = mGlblParms.settingFontStyle;
        String sz = mGlblParms.settingFontSize;
        boolean t_sl = mGlblParms.settingShowLineno;

        int prev_theme = mGlblParms.screenTheme;

        initSettingParms();

        if (!mGlblParms.settingFontFamily.equals(fn) || !mGlblParms.settingFontStyle.equals(fs)
                || !mGlblParms.settingFontSize.equals(sz) || mGlblParms.settingLineBreak != lb
                || mGlblParms.settingShowLineno != t_sl ||
                //            mGlblParms.debugEnabled!=t_dbg ||
                tab_stop != mGlblParms.settingTabStop) {
            ViewedFileListItem vfli = null;
            for (int i = 0; i < mGlblParms.viewedFileList.size(); i++) {
                vfli = mGlblParms.viewedFileList.get(i);
                if (mGlblParms.settingLineBreak != lb)
                    vfli.lineBreak = mGlblParms.settingLineBreak;
                if (mGlblParms.settingShowLineno != t_sl)
                    vfli.showLineNo = mGlblParms.settingShowLineno;
            }
            ViewedFileListItem vf = getViewedFileListItem(mGlblParms.currentViewedFile);
            FileViewerFragment fvf = (FileViewerFragment) vf.file_view_fragment;
            fvf.rebuildTextListAdapter(false);
        }

        if (prev_theme != mGlblParms.screenTheme) {
            mGlblParms.screenTheme = prev_theme;
            mCommonDlg.showCommonDialog(false, "W",
                    mContext.getString(R.string.msgs_text_browser_theme_changed_msg), null, null);

            //         finish();
            //         
            //         Intent in=new Intent(mContext,MainActivity.class);
            //         startActivity(in);

            //         setTheme(mGlblParms.screenTheme);
            //           initViewWidget();
            //           mActivity=this;
        }

    };

    private void initSettingParms() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        mGlblParms.settingFontFamily = prefs.getString(getString(R.string.settings_tb_font_family), "0");
        if (mGlblParms.settingFontFamily.equals("0")) {
            prefs.edit().putString(getString(R.string.settings_tb_line_break), "1").commit();
            prefs.edit().putString(getString(R.string.settings_tb_font_family), DEFAULT_FONT_FAMILY).commit();
            mGlblParms.settingFontFamily = DEFAULT_FONT_FAMILY;
            prefs.edit().putString(getString(R.string.settings_tb_font_style), DEFAULT_FONT_STYLE).commit();
            prefs.edit().putString(getString(R.string.settings_tb_font_size), DEFAULT_FONT_SIZE).commit();
            prefs.edit().putString(getString(R.string.settings_tb_index_cache), Constants.INDEX_CACHE_UP_TO_50MB)
                    .commit();
            prefs.edit().putBoolean(getString(R.string.settings_tb_show_lineno), true).commit();
            prefs.edit().putBoolean(getString(R.string.settings_tb_alway_determin_encode), false).commit();
            prefs.edit().putBoolean(getString(R.string.settings_tb_debug_enable), false).commit();
            prefs.edit().putString(getString(R.string.settings_tb_tab_stop), DEFAULT_TAB_STOP).commit();
        }

        mGlblParms.settingEncodeName = prefs.getString(getString(R.string.settings_tb_encode_name), "");

        mGlblParms.settingAlwayDeterminCharCode = prefs
                .getBoolean(getString(R.string.settings_tb_alway_determin_encode), false);
        mGlblParms.settingFontStyle = prefs.getString(getString(R.string.settings_tb_font_style),
                DEFAULT_FONT_STYLE);
        mGlblParms.settingLineBreak = Integer
                .valueOf(prefs.getString(getString(R.string.settings_tb_line_break), "1"));
        mGlblParms.settingFontSize = prefs.getString(getString(R.string.settings_tb_font_size), DEFAULT_FONT_SIZE);
        mGlblParms.settingIndexCache = prefs.getString(getString(R.string.settings_tb_index_cache),
                Constants.INDEX_CACHE_UP_TO_50MB);
        mGlblParms.settingShowLineno = prefs.getBoolean(getString(R.string.settings_tb_show_lineno), true);
        mGlblParms.settingTabStop = Integer
                .valueOf(prefs.getString(getString(R.string.settings_tb_tab_stop), DEFAULT_TAB_STOP));
        mGlblParms.settingBufferCharIndexSize = Integer
                .valueOf(prefs.getString(getString(R.string.settings_tb_buffer_char_index_size), "8"));
        mGlblParms.settingBufferHexIndexSize = Integer
                .valueOf(prefs.getString(getString(R.string.settings_tb_buffer_hex_index_size), "2"));
        mGlblParms.settingBufferPoolSize = Integer
                .valueOf(prefs.getString(getString(R.string.settings_tb_buffer_pool_size), "32"));
        if (mGlblParms.settingBufferPoolSize < 128)
            mGlblParms.settingBufferPoolSize = 256;
        mGlblParms.debugEnabled = prefs.getBoolean(getString(R.string.settings_tb_debug_enable), false);

        mGlblParms.settingExitCleanly = prefs.getBoolean(getString(R.string.settings_tb_exit_cleanly), false);

        //      if (Build.VERSION.SDK_INT>=11) {
        //         mGlblParms.settingUseLightTheme=
        //               prefs.getBoolean(getString(R.string.settings_tb_use_light_theme),false);
        //      }
        mGlblParms.settingUseLightTheme = prefs.getBoolean(getString(R.string.settings_tb_use_light_theme), false);
        if (mGlblParms.settingUseLightTheme)
            mGlblParms.screenTheme = R.style.MainLight;
        else
            mGlblParms.screenTheme = R.style.Main;

        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG,
                    "Init Setting parms: " + "Line break=" + mGlblParms.settingLineBreak + ", Font family="
                            + mGlblParms.settingFontFamily + ", Font style=" + mGlblParms.settingFontStyle
                            + ", Font size=" + mGlblParms.settingFontSize + ", Tab stop="
                            + mGlblParms.settingTabStop + ", use light theme=" + mGlblParms.settingUseLightTheme);
    };

    private FileSelectDialogFragment mFileSelectorDialogFragment = null;

    private void showFileSelectDialog() {
        //      Intent in=new Intent(mContext, FileSelectorActivity.class);
        //      in.putExtra("enableCreate", false);
        //      in.putExtra("title",mContext.getString(R.string.msgs_text_browser_file_select_file));
        //      in.putExtra("filename","");
        //      in.putExtra("lurl",LocalMountPoint.getExternalStorageDir());
        //      in.putExtra("ldir","");
        //      
        //      startActivity(in);

        boolean enableCreate = false;
        String title = mContext.getString(R.string.msgs_text_browser_file_select_file);
        String filename = "";
        String lurl = LocalMountPoint.getExternalStorageDir();
        String ldir = "";

        NotifyEvent ntfy = new NotifyEvent(this);
        ntfy.setListener(new NotifyEventListener() {
            @Override
            public void positiveResponse(Context c, Object[] o) {
                String fp = (String) o[0];
                if (!isFileAlreadyViewed(fp)) {
                    addFileToViewedFileList(true, fp);
                } else {
                    showFileByViewedFileList(fp);
                }
                refreshOptionMenu();
                mFileSelectorDialogFragment = null;
            }

            @Override
            public void negativeResponse(Context c, Object[] o) {
                if (getViewedFileListCount() == 0) {
                    mTerminateApplication = true;
                    finish();
                }
                mFileSelectorDialogFragment = null;
                //            finish();
            }
        });
        if (mFileSelectorDialogFragment == null) {
            mFileSelectorDialogFragment = FileSelectDialogFragment.newInstance(mGlblParms.debugEnabled,
                    enableCreate, true, false, false, true, lurl, ldir, filename, title);
            mFileSelectorDialogFragment.showDialog(getSupportFragmentManager(), mFileSelectorDialogFragment, ntfy);
        }
    };

    private boolean mEnableFileSelection = false;

    final public void setUiEnabled() {
        mEnableFileSelection = true;
        mViewedFileListSpinner.setEnabled(true);
    };

    final public void setUiDisabled() {
        mEnableFileSelection = false;
        mViewedFileListSpinner.setEnabled(false);
    };

    private void setViewedFilleSelectorListener() {
        mViewedFileListSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
                String prev = mGlblParms.currentViewedFile;
                if (mEnableFileSelection) {
                    mGlblParms.currentViewedFile = mGlblParms.viewedFileList.get(position).file_path;
                    showFileByViewedFileList(mGlblParms.currentViewedFile);
                    NotificationUtil.showOngoingNotificationMsg(mContext, mGlblParms.commonNotification,
                            mGlblParms.currentViewedFile);

                    if (mGlblParms.debugEnabled)
                        Log.v(APPLICATION_TAG, "ViewedFile was seleced, pos=" + position + ", prev=" + prev
                                + ", new=" + mGlblParms.currentViewedFile);
                } else {
                    if (mGlblParms.debugEnabled)
                        Log.v(APPLICATION_TAG, "ViewedFile selection ignored, pos=" + position + ", prev=" + prev
                                + ", new=" + mGlblParms.currentViewedFile);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });

    };
}