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

Java tutorial

Introduction

Here is the source code for com.sentaroh.android.TextFileBrowser.FileViewerFragment.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 java.io.File;

import com.sentaroh.android.Utilities.NotifyEvent;
import com.sentaroh.android.Utilities.NotifyEvent.NotifyEventListener;
import com.sentaroh.android.Utilities.ThreadCtrl;
import com.sentaroh.android.Utilities.ContextMenu.CustomContextMenu;
import com.sentaroh.android.Utilities.ContextMenu.CustomContextMenuItem.CustomContextMenuOnClickListener;
import com.sentaroh.android.Utilities.Widget.CustomTextView;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;

@SuppressLint("ClickableViewAccessibility")
@SuppressWarnings("deprecation")
public class FileViewerFragment extends Fragment {

    private final static String APPLICATION_TAG = "FileViewerFragment";
    private GlobalParameters mGlblParms = null;

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

    private ViewedFileListItem mViewedFile = null;

    private IndexedFileReader mIdxReader = null;
    private ThreadCtrl mTcIndexReader = null;

    private FragmentManager mFragmentManager = null;
    private Resources mResources = null;
    private Context mContext;
    private MainActivity mMainActivity = null;
    private String mLastMsgText = "";

    private ListView mTextListView = null;
    private FileViewerAdapter mTextListAdapter = null;
    //   private int TextFileBlockSize=1024*2048;

    private View mMainView = null;
    private Handler mUiHandler = null;
    private String mMainFilePath = "";
    private TextView mMainViewMsgArea;
    private ProgressBar mMainViewProgressBar;

    private Button mMainViewScrollLeft1, mMainViewScrollLeft2, mMainViewScrollRight1, mMainViewScrollRight2;
    private ThreadCtrl mTcScroll;
    private Thread mThScroll = null;
    private boolean mScrollActive = false;

    //   public void setOptions(boolean debug, int mln) {
    //      mGlblParms.debugEnabled=debug;
    //   }

    public static FileViewerFragment newInstance(String filepath) {
        //      if (mDebugEnable) 
        //      Log.v(APPLICATION_TAG,"newInstance fp="+filepath);
        FileViewerFragment frag = new FileViewerFragment();
        Bundle bundle = new Bundle();
        bundle.putString("FilePath", filepath);
        frag.setArguments(bundle);
        return frag;
    };

    public FileViewerFragment() {
        //      Log.v(APPLICATION_TAG,"Constructor(Default)");
    };

    public void setEncodeName(String enc_name) {
        mViewedFile.encodeName = enc_name;
    }

    public String getEncodeName() {
        return mIdxReader.getCurrentEncodeName();//mViewedFile.encodeName;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "onConfigurationChanged entered");
        saveViewAttributes();
        if (!mViewedFile.ix_reader_view.isIndexCreationFinished()) {
            mMainViewProgressBar.setVisibility(ProgressBar.VISIBLE);
            //         mIdxReader.refreshParentResources(mMainViewProgressBar,mMainViewMsgArea);
        } else {
            buildTextListAdapter();
            restoreViewAttributes();
        }
    };

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "onSaveInstanceState entered");
        saveViewAttributes();
        //      saveTaskData();
    };

    private void saveViewAttributes() {
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "saveViewAttributes entered");
        if (mMainActivity.isApplicationTerminating())
            return;
        mLastMsgText = mMainViewMsgArea.getText().toString();
        mViewedFile.listViewPos[0] = mTextListView.getFirstVisiblePosition();
        if (mTextListView.getChildAt(0) != null)
            mViewedFile.listViewPos[1] = mTextListView.getChildAt(0).getTop();
        //      mViewedFile.lastMsgText=mMainViewMsgArea.getText().toString();
        if (mTextListAdapter != null) {
            mViewedFile.copyFrom = mTextListAdapter.getCopyBegin();
            mViewedFile.copyTo = mTextListAdapter.getCopyEnd();
            mViewedFile.horizontalPos = mTextListAdapter.getHorizontalPosition();
        }
        final EditText et_find_string = (EditText) mMainView.findViewById(R.id.activity_browser_main_search_text);
        mViewedFile.searchString = et_find_string.getText().toString();
    };

    private void restoreViewAttributes() {
        mTextListView.setSelectionFromTop(mViewedFile.listViewPos[0], mViewedFile.listViewPos[1]);
        mTextListAdapter.setCopyBegin(mViewedFile.copyFrom);
        mTextListAdapter.setCopyEnd(mViewedFile.copyTo);
        mTextListAdapter.setHorizontalPosition(mViewedFile.horizontalPos);
        final EditText et_find_string = (EditText) mMainView.findViewById(R.id.activity_browser_main_search_text);
        et_find_string.setText(mViewedFile.searchString);

        mMainViewMsgArea.setText(mLastMsgText);
        if (mLastMsgText.equals("")) {
            mMainViewMsgArea.setVisibility(TextView.GONE);
        } else {
            mMainViewMsgArea.setVisibility(TextView.VISIBLE);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGlblParms = (GlobalParameters) getActivity().getApplication();
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "onCreate entered");
        //        setRetainInstance(true);
        mUiHandler = new Handler();
        mMainActivity = (MainActivity) getActivity();
        mContext = getActivity().getApplicationContext();
        mResources = getResources();
        mFragmentManager = getFragmentManager();
        mRestartStatus = 0;

        mMainFilePath = getArguments().getString("FilePath");

        initViewWidget();
    };

    private void initViewWidget() {
        boolean found = false;
        if (mGlblParms.viewedFileList != null) {
            for (int i = 0; i < mGlblParms.viewedFileList.size(); i++) {
                if (mMainFilePath.equals(mGlblParms.viewedFileList.get(i).file_path)) {
                    found = true;
                    mViewedFile = mGlblParms.viewedFileList.get(i);
                    mViewedFile.file_view_fragment = this;
                    //                  Log.v("","frag update="+mViewedFile.file_view_fragment);
                    mIdxReader = mViewedFile.ix_reader_view;
                    mTcIndexReader = mViewedFile.tc_view;
                    if (mViewedFile.viewerParmsInitRequired) {
                        mViewedFile.viewerParmsInitRequired = false;
                        //                     mViewedFile.browseMode=mGlblParms.settingBrowseMode;
                        mViewedFile.lineBreak = mGlblParms.settingLineBreak;
                        mViewedFile.showLineNo = mGlblParms.settingShowLineno;
                        mViewedFile.encodeName = mGlblParms.settingEncodeName;
                    } else {
                        if (mViewedFile.viewerParmsRestoreRequired)
                            mRestartStatus = 0;
                        else
                            mRestartStatus = 2;
                    }
                    if (mGlblParms.debugEnabled) {
                        Log.v(APPLICATION_TAG,
                                "Viewer option:" + " File path=" + mViewedFile.file_path + ", Browse mode="
                                        + mViewedFile.browseMode + ", Line break=" + mViewedFile.lineBreak
                                        + ", Show line no=" + mViewedFile.showLineNo + ", Encode name="
                                        + mViewedFile.encodeName);
                    }
                    break;
                }
            }
        }
        if (!found) {
            if (mGlblParms.debugEnabled)
                Log.v(APPLICATION_TAG, "ViewedFile item not found, fp=" + mMainFilePath);
            mFragmentManager.beginTransaction().remove(this).commit();
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "onCreateView entered");
        //        WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        View v = inflater.inflate(R.layout.text_browser_file_view, container, false);

        ////      Context context = new ContextThemeWrapper(getActivity(), mGlblParms.screenTheme);
        //      mContext = new ContextThemeWrapper(getActivity(), mGlblParms.screenTheme);
        //      // clone the inflater using the ContextThemeWrapper
        //      LayoutInflater localInflater = inflater.cloneInContext(mContext);
        //      // inflate using the cloned inflater, not the passed in default   
        //      View v=localInflater.inflate(R.layout.text_browser_file_view, container, false);

        mMainView = v;

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

        mMainViewMsgArea = (TextView) v.findViewById(R.id.activity_browser_main_msg);
        mMainViewScrollRight1 = (Button) v.findViewById(R.id.activity_browser_main_scroll_right1);
        mMainViewScrollRight2 = (Button) v.findViewById(R.id.activity_browser_main_scroll_right2);
        mMainViewScrollLeft1 = (Button) v.findViewById(R.id.activity_browser_main_scroll_left1);
        mMainViewScrollLeft2 = (Button) v.findViewById(R.id.activity_browser_main_scroll_left2);

        mTextListView = (ListView) v.findViewById(R.id.activity_browser_main_view);

        mMainViewProgressBar = (ProgressBar) mMainView.findViewById(R.id.activity_browser_main_progress_bar);

        mTextListAdapter = null;

        return v;
    }

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

    //   private void putThreadInfo() {
    //      Log.v("","id="+Thread.currentThread().getId()+", name="+Thread.currentThread().getName());
    //   }

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

        if (mRestartStatus == 0) {
            NotifyEvent ntfy = new NotifyEvent(mContext);
            ntfy.setListener(new NotifyEventListener() {
                @Override
                public void positiveResponse(final Context c, final Object[] o) {
                    if (mMainActivity.isApplicationTerminating())
                        return;
                    buildTextListAdapter();
                    if (mViewedFile.viewerParmsRestoreRequired) {
                        restoreViewAttributes();
                    } else {
                        if (mIdxReader.getCharModeLineCount() == 0) {
                            mMainViewMsgArea.setVisibility(TextView.VISIBLE);
                            mMainViewMsgArea.setText(c.getString(R.string.msgs_text_browser_ir_file_empty));
                        } else {
                            mMainViewMsgArea.setText("");
                            mMainViewMsgArea.setVisibility(TextView.GONE);
                        }
                    }
                    mViewedFile.viewerParmsRestoreRequired = false;
                    mMainActivity.refreshOptionMenu();
                    setInitViewPosition();
                }

                @Override
                public void negativeResponse(Context c, final Object[] o) {
                    if (mMainActivity.isApplicationTerminating())
                        return;
                    if (mIdxReader != null) {
                        buildTextListAdapter();
                        mMainViewMsgArea.setVisibility(TextView.VISIBLE);
                        mMainViewMsgArea.setText((String) o[0]);
                    } else {
                        mMainViewMsgArea.setVisibility(TextView.VISIBLE);
                        mMainViewMsgArea.setText("FileViewer not found error, restart browser.");
                    }
                    mMainActivity.refreshOptionMenu();
                    setInitViewPosition();
                }
            });
            if (mIdxReader != null)
                createFileIndexList(mMainFilePath, ntfy);
            else
                ntfy.notifyToListener(false, null);
        } else if (mRestartStatus == 1) {
        } else if (mRestartStatus == 2) {
            //         Log.v("","search="+mViewedFile.searchEnabled+", aa="+mViewedFile.browseMode);
            buildTextListAdapter();
            restoreViewAttributes();
            setInitViewPosition();
        }
        mRestartStatus = 1;

        mTextListView.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
                createCcmenu(mTextListView, mTextListAdapter, pos);
                return false;
            }
        });

        setFindStringListener();

        setScrollButtonListener();
    };

    private void setInitViewPosition() {
        if (Build.VERSION.SDK_INT == 19) {
            mUiHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mTextListView.setSelection(0);
                    mTextListView.setSelectionFromTop(mViewedFile.listViewPos[0], mViewedFile.listViewPos[1]);
                }
            }, 500);
        }
    };

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

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mGlblParms.debugEnabled)
            Log.v(APPLICATION_TAG, "onDestroy entered");
        // Application process is follow
        if (mViewedFile != null)
            mViewedFile.file_view_fragment = null;
        //      if (mTerminateApplication) {
        //         mTextListAdapter=null;
        //      } else {
        //         
        //      }
    };

    public void switchDisplayMode() {
        switchDisplayMode(mViewedFile.browseMode);
    };

    private void switchDisplayMode(int c_mode) {
        if (c_mode == FileViewerAdapter.TEXT_BROWSER_BROWSE_MODE_CHAR) {
            mViewedFile.browseMode = FileViewerAdapter.TEXT_BROWSER_BROWSE_MODE_HEX;
        } else {
            mViewedFile.browseMode = FileViewerAdapter.TEXT_BROWSER_BROWSE_MODE_CHAR;
        }
        rebuildTextListAdapter(true);
        if (Build.VERSION.SDK_INT == 19) {
            mUiHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mTextListView.setSelection(0);
                }
            }, 100);
        }
    };

    public void reloadFile() {
        NotifyEvent ntfy = new NotifyEvent(mContext);
        ntfy.setListener(new NotifyEventListener() {
            @Override
            public void positiveResponse(Context c, Object[] o) {
                int pos = 0, posTop = 0;
                pos = mTextListView.getFirstVisiblePosition();
                if (mTextListView.getChildAt(0) != null)
                    posTop = mTextListView.getChildAt(0).getTop();
                buildTextListAdapter();
                restoreViewAttributes();
                mTextListView.setSelectionFromTop(pos, posTop);
                if (mIdxReader.getCharModeLineCount() == 0) {
                    mMainViewMsgArea.setVisibility(TextView.VISIBLE);
                    mMainViewMsgArea.setText(c.getString(R.string.msgs_text_browser_ir_file_empty));
                } else {
                    mMainViewMsgArea.setText("");
                    mMainViewMsgArea.setVisibility(TextView.GONE);
                }
                mMainActivity.refreshOptionMenu();
            }

            @Override
            public void negativeResponse(Context c, Object[] o) {
                buildTextListAdapter();
                mMainActivity.refreshOptionMenu();
            }
        });
        mTextListView.setAdapter(null);
        createFileIndexList(mMainFilePath, ntfy);
    };

    private void createFileIndexList(String uri, final NotifyEvent p_ntfy) {
        String fp = uri.replaceFirst("file://", "");
        if (!fp.equals("")) {
            File lf = new File(fp);
            if (lf.exists() && lf.canRead()) {
                if (lf.length() < (1024 * 1024 * 1024 * 2) - 1024) {
                    ProgressBar pb = (ProgressBar) mMainView.findViewById(R.id.activity_browser_main_progress_bar);
                    mIdxReader.houseKeepIndexCacheFolder(mGlblParms.settingIndexCache);
                    mIdxReader.startFileIndexCreation(fp, mTcIndexReader, p_ntfy, pb, mMainViewMsgArea,
                            mViewedFile.encodeName, mUiHandler);
                } else {
                    p_ntfy.notifyToListener(false,
                            new Object[] { getString(R.string.msgs_text_browser_file_file_size_too_big) });
                }
            } else {
                mMainViewMsgArea.setVisibility(TextView.VISIBLE);
                if (!lf.exists()) {
                    p_ntfy.notifyToListener(false,
                            new Object[] { getString(R.string.msgs_text_browser_file_does_not_existed) });
                } else {
                    p_ntfy.notifyToListener(false,
                            new Object[] { getString(R.string.msgs_text_browser_file_can_not_be_accessed) });
                }
            }
        } else {
            p_ntfy.notifyToListener(false,
                    new Object[] { getString(R.string.msgs_text_browser_file_file_name_not_specified) });
        }
    };

    public void rebuildTextListAdapter(boolean reset_copy) {
        if (reset_copy) {
            int pos = 0, posTop = 0;
            pos = mTextListView.getFirstVisiblePosition();
            if (mTextListView.getChildAt(0) != null)
                posTop = mTextListView.getChildAt(0).getTop();
            buildTextListAdapter();
            mMainViewMsgArea.setText("");
            mMainViewMsgArea.setVisibility(TextView.GONE);
            mTextListAdapter.resetCopy();
            mTextListView.setSelectionFromTop(pos, posTop);
        } else {
            int pos = 0, posTop = 0;
            pos = mTextListView.getFirstVisiblePosition();
            if (mTextListView.getChildAt(0) != null)
                posTop = mTextListView.getChildAt(0).getTop();
            int cp_begin = mTextListAdapter.getCopyBegin();
            int cp_end = mTextListAdapter.getCopyEnd();
            int h_pos = mTextListAdapter.getHorizontalPosition();
            buildTextListAdapter();
            mTextListView.setSelectionFromTop(pos, posTop);
            mTextListAdapter.setHorizontalPosition(h_pos);
            if (cp_begin != -1) {
                mTextListAdapter.setCopyBegin(cp_begin);
                mTextListAdapter.setCopyEnd(cp_end);
            }
        }
    };

    @SuppressLint("NewApi")
    private void buildTextListAdapter() {
        LinearLayout ll_scroll = (LinearLayout) mMainView.findViewById(R.id.activity_browser_main_scroll_view);
        if (mViewedFile.lineBreak == CustomTextView.LINE_BREAK_NOTHING
                && mViewedFile.browseMode == FileViewerAdapter.TEXT_BROWSER_BROWSE_MODE_CHAR)
            ll_scroll.setVisibility(LinearLayout.VISIBLE);
        else
            ll_scroll.setVisibility(LinearLayout.GONE);

        //      mTextListView=(ListView)mMainView.findViewById(R.id.activity_browser_main_view);

        mTextListAdapter = new FileViewerAdapter(getActivity(), R.layout.text_browser_list_item,
                mGlblParms.debugEnabled, mIdxReader, mViewedFile.browseMode, mViewedFile.showLineNo,
                mViewedFile.lineBreak, mGlblParms.settingFontFamily, mGlblParms.settingFontStyle,
                mGlblParms.settingFontSize, mGlblParms.settingTabStop);
        //      mTextListView.setClickable(true);
        //      mTextListView.setFocusable(true);
        //      mTextListView.setFocusableInTouchMode(true);
        mTextListView.setAdapter(mTextListAdapter);
        //      mTextListView.setScrollingCacheEnabled(true);
        mTextListView.setFastScrollEnabled(true);
        mTextListView.setSelection(0);
        mTextListView.setSelected(true);

        final Button btnFind = (Button) mMainView.findViewById(R.id.activity_browser_main_search_btn);
        final EditText et_find_string = (EditText) mMainView.findViewById(R.id.activity_browser_main_search_text);
        final CheckBox cb_case = (CheckBox) mMainView
                .findViewById(R.id.activity_browser_main_search_case_sensitive);
        btnFind.setVisibility(Button.GONE);
        et_find_string.setVisibility(EditText.GONE);
        cb_case.setVisibility(CheckBox.GONE);
        if (mViewedFile.searchEnabled
                && mViewedFile.browseMode == FileViewerAdapter.TEXT_BROWSER_BROWSE_MODE_CHAR) {
            btnFind.setVisibility(Button.VISIBLE);
            et_find_string.setVisibility(EditText.VISIBLE);
            cb_case.setVisibility(CheckBox.VISIBLE);
        }
    };

    @SuppressWarnings("unused")
    private void setUiMsg(final TextView tv_msg, Handler handler, final String msg) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                tv_msg.setVisibility(TextView.VISIBLE);
                tv_msg.setText(msg);
            }
        });
    };

    private void createCcmenu(final ListView lv, final FileViewerAdapter adapter, final int pos) {
        final TextView main_view_msg = (TextView) mMainView.findViewById(R.id.activity_browser_main_msg);
        CustomContextMenu mCcMenu = new CustomContextMenu(mResources, mFragmentManager);

        mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_move_top), R.drawable.text_browser_menu_top)
                .setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    public void onClick(CharSequence menuTitle) {
                        mViewedFile.findPosIsValid = false;
                        lv.setSelection(0);
                    }
                });
        mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_move_bottom), R.drawable.text_browser_menu_bottom)
                .setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    public void onClick(CharSequence menuTitle) {
                        mViewedFile.findPosIsValid = false;
                        lv.setSelection(adapter.getCount() - 1);
                    }
                });
        mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_copy_from), R.drawable.ic_24_select_begin)
                .setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    public void onClick(CharSequence menuTitle) {
                        adapter.setCopyBegin(pos);
                        adapter.notifyDataSetChanged();
                        main_view_msg.setVisibility(TextView.VISIBLE);
                        main_view_msg.setText(getString(R.string.msgs_text_browser_copymsg_specify_end));
                    }
                });
        if (adapter.getCopyBegin() != -1) {
            mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_copy_to), R.drawable.ic_24_select_end)
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        public void onClick(CharSequence menuTitle) {
                            adapter.setCopyEnd(pos);
                            adapter.notifyDataSetChanged();
                            main_view_msg.setVisibility(TextView.GONE);
                            main_view_msg.setText("");
                        }
                    });
        }
        mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_do_copy))
                .setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    public void onClick(CharSequence menuTitle) {
                        String msg = "";
                        if (adapter.isCopyActive()) {
                            if (adapter.getCopyBegin() > adapter.getCopyEnd())
                                msg = copyToClipboard(adapter.getCopyEnd(), adapter.getCopyBegin(), adapter);
                            else
                                msg = copyToClipboard(adapter.getCopyBegin(), adapter.getCopyEnd(), adapter);
                        } else {
                            msg = copyToClipboard(pos, pos, adapter);
                        }
                        main_view_msg.setVisibility(TextView.VISIBLE);
                        main_view_msg.setText(msg);
                    }
                });
        if (adapter.isCopyActive() || adapter.getCopyBegin() != -1) {
            mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_reset_copy))
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        public void onClick(CharSequence menuTitle) {
                            adapter.resetCopy();
                            adapter.notifyDataSetChanged();
                            main_view_msg.setVisibility(TextView.GONE);
                            main_view_msg.setText("");
                        }
                    });
        }
        mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_select_all_for_copy), R.drawable.ic_24_select_all)
                .setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    public void onClick(CharSequence menuTitle) {
                        adapter.resetCopy();
                        adapter.setCopyBegin(0);
                        adapter.setCopyEnd(adapter.getCount() - 1);
                        adapter.notifyDataSetChanged();
                        main_view_msg.setVisibility(TextView.GONE);
                        main_view_msg.setText("");
                    }
                });
        if (mViewedFile.browseMode == FileViewerAdapter.TEXT_BROWSER_BROWSE_MODE_CHAR) {
            mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_select_encode))
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        public void onClick(CharSequence menuTitle) {
                            EncodeSelectorFragment esfm = EncodeSelectorFragment.newInstance();
                            esfm.showDialog(mFragmentManager, esfm);
                        }
                    });

            //         mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_switch_hex),
            //               R.drawable.ic_32_hex)
            //           .setOnClickListener(new CustomContextMenuOnClickListener() {
            //            @Override
            //            public void onClick(CharSequence menuTitle) {
            //               switchDisplayMode(mViewedFile.browseMode);
            //               mMainActivity.refreshOptionMenu();
            //            }
            //           });
        } else {
            //         mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_switch_char),
            //               R.drawable.ic_32_text)
            //           .setOnClickListener(new CustomContextMenuOnClickListener() {
            //            @Override
            //            public void onClick(CharSequence menuTitle) {
            //               switchDisplayMode(mViewedFile.browseMode);
            //               mMainActivity.refreshOptionMenu();
            //            }
            //           });
        }
        if (mViewedFile.browseMode == FileViewerAdapter.TEXT_BROWSER_BROWSE_MODE_CHAR) {
            if (mViewedFile.showLineNo) {
                mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_hide_line_no))
                        .setOnClickListener(new CustomContextMenuOnClickListener() {
                            @Override
                            public void onClick(CharSequence menuTitle) {
                                mViewedFile.showLineNo = false;
                                mMainActivity.refreshOptionMenu();
                                rebuildTextListAdapter(false);
                            }
                        });
            } else {
                mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_show_line_no))
                        .setOnClickListener(new CustomContextMenuOnClickListener() {
                            @Override
                            public void onClick(CharSequence menuTitle) {
                                mViewedFile.showLineNo = true;
                                mMainActivity.refreshOptionMenu();
                                rebuildTextListAdapter(false);
                            }
                        });
            }
            ;

            if (mViewedFile.lineBreak == CustomTextView.LINE_BREAK_NOTHING) {
                //current=no line break
                mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_line_break_no_word))
                        .setOnClickListener(new CustomContextMenuOnClickListener() {
                            @Override
                            public void onClick(CharSequence menuTitle) {
                                mViewedFile.lineBreak = CustomTextView.LINE_BREAK_NO_WORD_WRAP;
                                rebuildTextListAdapter(false);
                                mMainActivity.refreshOptionMenu();
                                //                  applySettingParms();
                            }
                        });
                mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_line_break_word))
                        .setOnClickListener(new CustomContextMenuOnClickListener() {
                            @Override
                            public void onClick(CharSequence menuTitle) {
                                mViewedFile.lineBreak = CustomTextView.LINE_BREAK_WORD_WRAP;
                                rebuildTextListAdapter(false);
                                mMainActivity.refreshOptionMenu();
                            }
                        });
            } else if (mViewedFile.lineBreak == CustomTextView.LINE_BREAK_NO_WORD_WRAP) {
                //current=no word line break
                mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_line_break_nothing))
                        .setOnClickListener(new CustomContextMenuOnClickListener() {
                            @Override
                            public void onClick(CharSequence menuTitle) {
                                mViewedFile.lineBreak = CustomTextView.LINE_BREAK_NOTHING;
                                rebuildTextListAdapter(false);
                                mMainActivity.refreshOptionMenu();
                            }
                        });
                mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_line_break_word))
                        .setOnClickListener(new CustomContextMenuOnClickListener() {
                            @Override
                            public void onClick(CharSequence menuTitle) {
                                mViewedFile.lineBreak = CustomTextView.LINE_BREAK_WORD_WRAP;
                                rebuildTextListAdapter(false);
                                mMainActivity.refreshOptionMenu();
                            }
                        });
            } else if (mViewedFile.lineBreak == CustomTextView.LINE_BREAK_WORD_WRAP) {
                //current=word line break
                mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_line_break_nothing))
                        .setOnClickListener(new CustomContextMenuOnClickListener() {
                            @Override
                            public void onClick(CharSequence menuTitle) {
                                mViewedFile.lineBreak = CustomTextView.LINE_BREAK_NOTHING;
                                rebuildTextListAdapter(false);
                                mMainActivity.refreshOptionMenu();
                            }
                        });
                mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_line_break_no_word))
                        .setOnClickListener(new CustomContextMenuOnClickListener() {
                            @Override
                            public void onClick(CharSequence menuTitle) {
                                mViewedFile.lineBreak = CustomTextView.LINE_BREAK_NO_WORD_WRAP;
                                rebuildTextListAdapter(false);
                                mMainActivity.refreshOptionMenu();
                            }
                        });
            }
        }
        mCcMenu.createMenu();
    };

    private String copyToClipboard(int from_line, int to_line, FileViewerAdapter adapter) {
        ClipboardManager cm = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
        String sep = "";
        int c_line = 0;
        StringBuilder out = new StringBuilder("");
        for (int i = from_line; i <= to_line; i++) {
            c_line++;
            out.append(sep);
            out.append(adapter.getItem(i)[0]);
            sep = "\n";
        }
        cm.setText(out);
        return String.format(getString(R.string.msgs_text_browser_copymsg_copied), c_line);
    };

    public void switchFindWidget() {
        final Button btnFind = (Button) mMainView.findViewById(R.id.activity_browser_main_search_btn);
        final EditText et_find_string = (EditText) mMainView.findViewById(R.id.activity_browser_main_search_text);
        final CheckBox cb_case = (CheckBox) mMainView
                .findViewById(R.id.activity_browser_main_search_case_sensitive);
        //      final TextView main_msg = (TextView) findViewById(R.id.activity_browser_main_msg);
        if (mViewedFile.searchEnabled) {
            btnFind.setVisibility(Button.GONE);
            et_find_string.setVisibility(Button.GONE);
            cb_case.setVisibility(Button.GONE);
            mViewedFile.searchEnabled = false;
        } else {
            btnFind.setVisibility(Button.VISIBLE);
            et_find_string.setVisibility(Button.VISIBLE);
            cb_case.setVisibility(Button.VISIBLE);
            mViewedFile.searchEnabled = true;
        }
    }

    private void setFindStringListener() {
        final Button btnFind = (Button) mMainView.findViewById(R.id.activity_browser_main_search_btn);
        final EditText et_find_string = (EditText) mMainView.findViewById(R.id.activity_browser_main_search_text);
        final CheckBox cb_case = (CheckBox) mMainView
                .findViewById(R.id.activity_browser_main_search_case_sensitive);
        final TextView main_msg = (TextView) mMainView.findViewById(R.id.activity_browser_main_msg);

        cb_case.setChecked(mViewedFile.searchCaseSensitive);
        cb_case.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                mViewedFile.searchCaseSensitive = arg1;
            }
        });

        et_find_string.setText(mViewedFile.searchString);
        if (mViewedFile.searchString.equals(""))
            btnFind.setEnabled(false);
        et_find_string.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable arg0) {
                if (arg0.toString().equals(""))
                    btnFind.setEnabled(false);
                else
                    btnFind.setEnabled(true);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                main_msg.setText("");
                main_msg.setVisibility(TextView.GONE);
            }
        });

        mTextListView.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void onScrollStateChanged(AbsListView arg0, int arg1) {
                //            Log.v("","onScrollStateChanged, arg1="+arg1);
                if (arg1 == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL
                        || arg1 == AbsListView.OnScrollListener.SCROLL_STATE_FLING)
                    mViewedFile.findPosIsValid = false;

            }
        });

        btnFind.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                //            InputMethodManager imm=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                //            imm.hideSoftInputFromWindow(et_find_string.getWindowToken(),0); 
                mViewedFile.searchString = et_find_string.getText().toString();
                int start_pos = 0;
                if (mViewedFile.findResultPos == -1 || !mViewedFile.findPosIsValid) {
                    //????
                    start_pos = mTextListView.getFirstVisiblePosition();
                } else {//????
                    //??????????
                    start_pos = mViewedFile.findResultPos + 1;
                }
                mViewedFile.findPosIsValid = true;
                mViewedFile.findResultPos = mTextListAdapter.findString(
                        FileViewerAdapter.TEXT_BROWSER_BROWSE_MODE_CHAR, start_pos, mViewedFile.searchString,
                        cb_case.isChecked());
                if (mViewedFile.findResultPos != -1) {
                    //               Log.v("","fp="+mViewedFileListItem.findResultPos);
                    if (mViewedFile.findResultPos > 0) {
                        mTextListView.setSelection(mViewedFile.findResultPos - 1);
                    } else {
                        mTextListView.setSelection(mViewedFile.findResultPos);
                    }
                    main_msg.setText("");
                    main_msg.setVisibility(TextView.GONE);
                } else {
                    mViewedFile.findResultPos = start_pos;//??
                    mTextListView.setSelected(false);
                    main_msg.setText(mContext.getString(R.string.msgs_text_browser_search_string_not_found));
                    main_msg.setVisibility(TextView.VISIBLE);
                }
            }
        });
        //      if (mViewedFile.searchEnabled) {
        //         if (mViewedFile.browseMode==FileViewerAdapter.TEXT_BROWSER_BROWSE_MODE_CHAR) {
        //            btnFind.setVisibility(Button.VISIBLE);
        //            et_find_string.setVisibility(EditText.VISIBLE);
        //            cb_case.setVisibility(CheckBox.VISIBLE);
        //         } else {
        //            btnFind.setVisibility(Button.GONE);
        //            et_find_string.setVisibility(EditText.GONE);
        //            cb_case.setVisibility(CheckBox.GONE);
        //         }
        //      }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void setScrollButtonListener() {
        mTcScroll = new ThreadCtrl();
        mTcScroll.setEnabled();
        mMainViewScrollRight1.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (mScrollActive) {
                        mTcScroll.setDisabled();
                        waitThreadTerminate();
                    }
                    startScroll(mTcScroll, 20);//Scroll right
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    mTcScroll.setDisabled();
                    waitThreadTerminate();
                } else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
                    mTcScroll.setDisabled();
                    waitThreadTerminate();
                }
                return false;
            }
        });
        mMainViewScrollRight2.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (mScrollActive) {
                        mTcScroll.setDisabled();
                        waitThreadTerminate();
                    }
                    startScroll(mTcScroll, 2);//Scroll right
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    mTcScroll.setDisabled();
                    waitThreadTerminate();
                } else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
                    mTcScroll.setDisabled();
                    waitThreadTerminate();
                }
                return false;
            }
        });

        mMainViewScrollLeft1.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (mScrollActive) {
                        mTcScroll.setDisabled();
                        waitThreadTerminate();
                    }
                    startScroll(mTcScroll, -20);//Scroll left
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    mTcScroll.setDisabled();
                    waitThreadTerminate();
                } else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
                    mTcScroll.setDisabled();
                    waitThreadTerminate();
                }
                return false;
            }
        });
        mMainViewScrollLeft2.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (mScrollActive) {
                        mTcScroll.setDisabled();
                        waitThreadTerminate();
                    }
                    startScroll(mTcScroll, -2);//Scroll left
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    mTcScroll.setDisabled();
                    waitThreadTerminate();
                } else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
                    mTcScroll.setDisabled();
                    waitThreadTerminate();
                }
                return false;
            }
        });

    };

    private void waitThreadTerminate() {
        try {
            mThScroll.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    };

    private void startScroll(final ThreadCtrl tc, final int move) {
        final Handler hndl = new Handler();
        mScrollActive = true;
        mThScroll = new Thread() {
            @Override
            public void run() {
                while (tc.isEnabled()) {
                    hndl.post(new Runnable() {
                        @Override
                        public void run() {
                            if (move > 0)
                                mTextListAdapter.incrementHorizontalPosition(move);
                            else
                                mTextListAdapter.decrementHorizontalPosition(move * -1);
                            mTextListAdapter.notifyDataSetChanged();
                        }
                    });
                    waitSpecifiedTime(200);
                }
                mScrollActive = false;
                mTcScroll.setEnabled();
            }
        };
        mThScroll.start();
    };

    private void waitSpecifiedTime(long wt) {
        try {
            Thread.sleep(wt);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    };

}