/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.micode.notes.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.appwidget.AppWidgetManager;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Display;
import android.view.HapticFeedbackConstants;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService;
import net.micode.notes.model.WorkingNote;
import net.micode.notes.tool.BackupUtils;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import net.micode.notes.widget.NoteWidgetProvider_2x;
import net.micode.notes.widget.NoteWidgetProvider_4x;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
/**
 * NotesListActivity类的主要作用为显示便签列表界面，主要的功能实现方法有：
 * showCreateOrModifyFolderDialog() ---新建文件夹、修改文件夹名称 （597）
 * openFolder() ---查看文件夹 （558）
 * deleteFolder() ---删除文件夹 （524）
 * exportNoteToText() ---导出文本 （842）
 */
    /
public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener {
    //这个类继承于Activity类，实现了两个接口，分别是"点击监听器"，和"长按监听器"，即在这个类的界面实现对这两种操作的响应，这是整个project的主类
    private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0;
    //指的是查询记号,从数据库中查询调取相关数据时,这个TOKEN会起到一个指示器的作用

    private static final int FOLDER_LIST_QUERY_TOKEN      = 1;
//同为查询记号，文件夹请求时使用
    private static final int MENU_FOLDER_DELETE = 0;
//删除文件夹时
    private static final int MENU_FOLDER_VIEW = 1;
//查看文件夹
    private static final int MENU_FOLDER_CHANGE_NAME = 2;
//修改夹名
    private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction";
// 用于第一次打开小米便签的判断
    private enum ListEditState { 
        //enum表示枚举
        NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER //此处为编辑的三种状态
    };

    private ListEditState mState; //列表编辑状态

    private BackgroundQueryHandler mBackgroundQueryHandler; //后台疑问处理

    private NotesListAdapter mNotesListAdapter; //便签列表配适器

    private ListView mNotesListView; //主界面的视图

    private Button mAddNewNote; //最下方添加便签的按钮

    private boolean mDispatch; //是否调度的判断变量

    private int mOriginY; //首次触摸时屏幕上的垂直距离（y值）

    private int mDispatchY; //重新调度时的触摸的在屏幕上的垂直距离

    private TextView mTitleBar; //子文件夹下的 标头

    private long mCurrentFolderId; //当前文件夹的ID

    private ContentResolver mContentResolver; //提供内容分析,resolver:答问题者

    private ModeCallback mModeCallBack; //返回调用方法

    private static final String TAG = "NotesListActivity";

    public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; //列表滚动速度

    private NoteItemData mFocusNoteDataItem; //光标指向的物件的数据内容

    private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?";

    private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>"
            + Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR ("
            + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND "
            + NoteColumns.NOTES_COUNT + ">0)";

    private final static int REQUEST_CODE_OPEN_NODE = 102; //打开某个便签时，创建活动的请求码
    private final static int REQUEST_CODE_NEW_NODE  = 103; //新建便签时，创建活动的请求码


    @Override
    //@Override 的作用是告诉编译器检查这个方法，保证父类要包含一个被该方法重写的方法，否则就会编译出错。这样可以帮助程序员避免一些低级错误。

    protected void onCreate(final Bundle savedInstanceState) {
        //protected表示允许同一包内的成员（方法或变量）访问，并允许任何继承自该类的子类访问该成员。
        //final修饰类（“最终,最后”），表示该类是无法被任何其他类继承的，意味着此类在一个继承树中是一个叶子类，并且此类的设计已被认为很完美而不需要进行修改或扩展
        super.onCreate(savedInstanceState);
        setContentView(R.layout.note_list);
        initResources();
        //初始化活动可能需要的任何其他资源
        
        //final类的基本知识：
        // final类不能被继承，没有子类，final类中的方法默认是final的。
        //final成员变量表示常量，只能被赋值一次，赋值后值不再改变。

        /**
         * Insert an introduction when user firstly use this application
         */
        //当用户首次使用此应用程序时插入介绍
        setAppInfoFromRawRes();
    }

    @Override
    //当当前活动启动的活动完成并返回结果时调用该方法
    // 返回一些子模块完成的数据交给主Activity处理
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { //requestCode用于标识返回结果的活动。该变量在使用startActivityForResult（）方法启动活动时设置。
        if (resultCode == RESULT_OK
                && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) {
            mNotesListAdapter.changeCursor(null);  //如果两个条件都为真，则代码调用mNotesListAdapter实例上的changeCursor（）方法，将null作为参数传递。
        } else {
            super.onActivityResult(requestCode, resultCode, data); //否则调用父类（Activity类）的onActivityResult（）方法来处理结果。
            // 调用 Activity 的onActivityResult（）
        }
    }

    //基本功能为"设置应用信息"
    private void setAppInfoFromRawRes() {
        //判断是否已经存在介绍信息，
        // 如果不存在则读取R.raw.introduction资源中的文本内容
        // 并将其存入一个WorkingNote对象中，最后将其保存到数据库中
        
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        //获取默认的SharedPreferences对象
        if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) {
            StringBuilder sb = new StringBuilder();
            InputStream in = null;
            try {
                 in = getResources().openRawResource(R.raw.introduction);
                 //打开资源文件，得到一个输入流" in "
                if (in != null) {
                    InputStreamReader isr = new InputStreamReader(in);
                    BufferedReader br = new BufferedReader(isr);
                    //将文本数据读取出来并拼接到一个字符串sb中
                    char [] buf = new char[1024];
                    int len = 0;
                    while ((len = br.read(buf)) > 0) {
                        sb.append(buf, 0, len);
                    }
                } else {
                    Log.e(TAG, "Read introduction file error");
                    return;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return;
            } finally {
                if(in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER,
                    AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE,
                    ResourceParser.RED);
            //创建对象，并调用其setWorkingText()方法设置文本内容，然后调用saveNote()方法保存到数据库中。
            // 如果保存成功，将标记为已添加介绍信息，以便下次不再重复添加。
            // 如果保存失败，则打印错误日志并返回。
            note.setWorkingText(sb.toString());
            if (note.saveNote()) {
                sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit();
            } else {
                Log.e(TAG, "Save introduction note error");
                return;
            }
        }
    }

    @Override
    //“一般”用于活动生命周期管理，此处调用方法，并获取笔记列表
    protected void onStart() {
        super.onStart(); //细节为此处调用了父类
        startAsyncNotesListQuery(); //启动了一个异步的数据库查询操作，用于获取笔记列表
    }

    private void initResources() { //初始化笔记应用程序的各种资源
        mContentResolver = this.getContentResolver();
        //初始化了mContentResolver，获取到了一个ContentResolver对象
        mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver());
        //创建s一个BackgroundQueryHandler对象，并将mContentResolver传递给该对象的构造函数中
        mCurrentFolderId = Notes.ID_ROOT_FOLDER;
        mNotesListView = (ListView) findViewById(R.id.notes_list);
        mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null),
                null, false);
        //至此定义了一些成员变量，用于后续编程逻辑
        mNotesListView.setOnItemClickListener(new OnListItemClickListener()); //设置视图点击监听器
        mNotesListView.setOnItemLongClickListener(this); // 设置长按监听器
        mNotesListAdapter = new NotesListAdapter(this);
        mNotesListView.setAdapter(mNotesListAdapter); //创建了一个“NotesListAdapter”对象，并将其设置为“mNotesListView”对象的适配器
        mAddNewNote = (Button) findViewById(R.id.btn_new_note);  //使用从当前“Activity”中检索到的“Button”对象初始化了“mAddNewNote”变量
        mAddNewNote.setOnClickListener(this);
        mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener());
        mDispatch = false;
        mDispatchY = 0;
        mOriginY = 0;
        mTitleBar = (TextView) findViewById(R.id.tv_title_bar);// 从布局文件中获取TextView对象
        mState = ListEditState.NOTE_LIST;// 设置状态为Note List
        mModeCallBack = new ModeCallback();// 创建ModeCallback对象
    }

    private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener {
        private DropdownMenu mDropDownMenu;
        private ActionMode mActionMode;
        private MenuItem mMoveMenu;
//以上皆为成员变量
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            getMenuInflater().inflate(R.menu.note_list_options, menu); //将R.menu.note_list_options菜单文件解析为菜单
            menu.findItem(R.id.delete).setOnMenuItemClickListener(this);//设置菜单项R.id.delete的OnMenuItemClickListener为该类本身
            mMoveMenu = menu.findItem(R.id.move);//调用下面的更新菜单函数
            if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER
                    || DataUtils.getUserFolderCount(mContentResolver) == 0) { // 如果当前笔记所在文件夹是通话记录文件夹或用户文件夹数量为0
                mMoveMenu.setVisible(false); // 隐藏移动菜单项
            } else {
                mMoveMenu.setVisible(true); // 显示移动菜单项
                mMoveMenu.setOnMenuItemClickListener(this); // 设置菜单项R.id.move的OnMenuItemClickListener为该类本身
            }
            mActionMode = mode; // 保存上下文操作模式
            mNotesListAdapter.setChoiceMode(true); // 设置列表的选择模式为多选
            mNotesListView.setLongClickable(false); // 禁用长按触发
            mAddNewNote.setVisibility(View.GONE); // 隐藏添加新笔记按钮

            // 创建下拉式菜单
            View customView = LayoutInflater.from(NotesListActivity.this).inflate(R.layout.note_list_dropdown_menu, null); // 加载自定义视图
            mode.setCustomView(customView); // 设置自定义视图
            mDropDownMenu = new DropdownMenu(NotesListActivity.this, (Button) customView.findViewById(R.id.selection_menu), R.menu.note_list_dropdown); // 创建下拉式菜单
            mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){ // 设置下拉式菜单项的点击事件
                public boolean onMenuItemClick(MenuItem item) {
                    mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); // 选中或取消选中全部笔记
                    updateMenu(); // 更新菜单项
                    return true;
                }
            });
            return true;
        }

        private void updateMenu() {
            int selectedCount = mNotesListAdapter.getSelectedCount();
            // Update dropdown menu
            String format = getResources().getString(R.string.menu_select_title, selectedCount);
            mDropDownMenu.setTitle(format);
            MenuItem item = mDropDownMenu.findItem(R.id.action_select_all);
            if (item != null) {
                if (mNotesListAdapter.isAllSelected()) {
                    item.setChecked(true);
                    item.setTitle(R.string.menu_deselect_all);
                } else {
                    item.setChecked(false);
                    item.setTitle(R.string.menu_select_all);
                }
            }
        }

        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // TODO Auto-generated method stub
            return false;
        }

        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            // TODO Auto-generated method stub
            return false;
        }

        public void onDestroyActionMode(ActionMode mode) {
            mNotesListAdapter.setChoiceMode(false);
            mNotesListView.setLongClickable(true);
            mAddNewNote.setVisibility(View.VISIBLE);
        }

        // 完成 ActionMode 操作
        public void finishActionMode() {
            mActionMode.finish();
        }

        // 列表项选中状态变化监听器
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id,
                                              boolean checked) {
            mNotesListAdapter.setCheckedItem(position, checked);
            updateMenu();
        }

        // 菜单项点击监听器
        public boolean onMenuItemClick(MenuItem item) {
            // 如果没有选中任何项，显示提示信息并返回 true
            if (mNotesListAdapter.getSelectedCount() == 0) {
                Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none),
                        Toast.LENGTH_SHORT).show();
                return true;
            }

            switch (item.getItemId()) {
                case MENU_FOLDER_VIEW:
                    openFolder(mFocusNoteDataItem);//打开对应文件
                    break;
                case MENU_FOLDER_DELETE:
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);//设置确认是否删除的对话框
                    builder.setTitle(getString(R.string.alert_title_delete));
                    builder.setIcon(android.R.drawable.ic_dialog_alert);
                    builder.setMessage(getString(R.string.alert_message_delete_folder));
                    builder.setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    deleteFolder(mFocusNoteDataItem.getId());
                                }
                            });
                    builder.setNegativeButton(android.R.string.cancel, null);
                    builder.show();//显示对话框
                    break;
                case MENU_FOLDER_CHANGE_NAME:
                    showCreateOrModifyFolderDialog(false);
                    break;
                default:
                    break;
            }

            return true;
        }



        /**

         新建笔记按钮的触摸监听器
         */
        private class NewNoteOnTouchListener implements OnTouchListener {

            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
// 获取屏幕高度和新建笔记视图的高度，计算起始位置和事件坐标
                        Display display = getWindowManager().getDefaultDisplay();
                        int screenHeight = display.getHeight();
                        int newNoteViewHeight = mAddNewNote.getHeight();
                        int start = screenHeight - newNoteViewHeight;
                        int eventY = start + (int) event.getY();
                    /**
                     * Minus TitleBar's height
                     */
                        /**
                         * 减去标题栏的高度
                         */
                        if (mState == ListEditState.SUB_FOLDER) {
                            eventY -= mTitleBar.getHeight();
                            start -= mTitleBar.getHeight();
                        }

                        /**
                         * HACKME: 当点击"新建笔记"按钮的透明部分时，将事件分发给该按钮后面的列表视图。
                         * "新建笔记"按钮的透明部分可以用公式y=-0.12x+94（单位：像素）和按钮顶部的直线表示，
                         * 坐标基于"新建笔记"按钮的左侧。94表示透明部分的最大高度。
                         * 请注意，如果按钮的背景发生更改，则公式也应更改。这非常糟糕，只是为了满足UI设计师的强烈要求。
                         */
                        if (event.getY() < (event.getX() * (-0.12) + 94)) {
                            View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1
                                    - mNotesListView.getFooterViewsCount());
                            if (view != null && view.getBottom() > start
                                    && (view.getTop() < (start + 94))) {
                                mOriginY = (int) event.getY();
                                mDispatchY = eventY;
                                event.setLocation(event.getX(), mDispatchY);
                                mDispatch = true;
                                return mNotesListView.dispatchTouchEvent(event);
                            }
                        }
                        break;
                    }
                    case MotionEvent.ACTION_MOVE: {
                        // 分发事件给列表视图
                        if (mDispatch) {
                            mDispatchY += (int) event.getY() - mOriginY;
                            event.setLocation(event.getX(), mDispatchY);
                            return mNotesListView.dispatchTouchEvent(event);
                        }
                        break;
                    }
                    default: {
                        // 分发事件给列表视图
                        if (mDispatch) {
                            event.setLocation(event.getX(), mDispatchY);
                            mDispatch = false;
                            return mNotesListView.dispatchTouchEvent(event);
                        }
                        break;
                    }
                }
                return false;


                /**
                 * 启动异步查询笔记列表数据
                 */
                private void startAsyncNotesListQuery() {
                    String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION
                            : NORMAL_SELECTION;
                    // 使用后台查询处理器启动异步查询
                    mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null,
                            Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] {
                                    String.valueOf(mCurrentFolderId)
                            }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC");
                }

    private final class BackgroundQueryHandler extends AsyncQueryHandler {
        public BackgroundQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }


        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
                case FOLDER_NOTE_LIST_QUERY_TOKEN: // 查询文件夹下的笔记列表
                    mNotesListAdapter.changeCursor(cursor); // 更新笔记列表的游标
                    break;
                case FOLDER_LIST_QUERY_TOKEN: // 查询文件夹列表
                    if (cursor != null && cursor.getCount() > 0) { // 如果查询结果非空
                        showFolderListMenu(cursor); // 显示文件夹列表菜单
                    } else {
                        Log.e(TAG, "Query folder failed"); // 记录错误日志
                    }
                    break;
                default:
                    return;
            }
        }

        private void showFolderListMenu(Cursor cursor) {
            AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); // 创建 AlertDialog.Builder 对象
            builder.setTitle(R.string.menu_title_select_folder); // 设置标题
            final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor); // 创建 FoldersListAdapter 对象
            builder.setAdapter(adapter, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) { // 设置点击监听器
                    DataUtils.batchMoveToFolder(mContentResolver,
                            mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); // 批量将笔记移动到选择的文件夹中
                    Toast.makeText(
                            NotesListActivity.this,
                            getString(R.string.format_move_notes_to_folder,
                                    mNotesListAdapter.getSelectedCount(),
                                    adapter.getFolderName(NotesListActivity.this, which)), // 显示提示信息，格式为“移动了X条笔记到Y文件夹中”
                            Toast.LENGTH_SHORT).show(); // 显示 Toast
                    mModeCallBack.finishActionMode(); // 结束上下文操作模式
                }
            });
            builder.show(); // 显示 AlertDialog
        }


        private void createNewNote() {//创建新的笔记
        private void createNewNote() {
// 创建Intent，指向NoteEditActivity
            Intent intent = new Intent(this, NoteEditActivity.class);
// 设置Intent的Action为插入或编辑操作
            intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
// 将当前文件夹的ID作为extra传递给NoteEditActivity
            intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId);
// 启动NoteEditActivity并等待返回结果
            this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE);
    }

    private void batchDelete() {
        new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() {
            protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) {
                HashSet<AppWidgetAttribute> widgets = mNotesListAdapter.getSelectedWidget();
                if (!isSyncMode()) {
                    // if not synced, delete notes directly
                    if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter
                            .getSelectedItemIds())) {
                    } else {
                        Log.e(TAG, "Delete notes error, should not happens");
                    }
                } else {
                    // in sync mode, we'll move the deleted note into the trash
                    // folder
                    if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter
                            .getSelectedItemIds(), Notes.ID_TRASH_FOLER)) {
                        Log.e(TAG, "Move notes to trash folder error, should not happens");
                    }
                }
                return widgets;
            }

            @Override
            protected void onPostExecute(HashSet<AppWidgetAttribute> widgets) {//这是一个循环体结构，如果id不等的话，会进行更新id的操作。
                if (widgets != null) {
                    for (AppWidgetAttribute widget : widgets) {//此处判断是否为一个widget
                        if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID
                                && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {////更新widget信息
                            updateWidget(widget.widgetId, widget.widgetType);//更新桌面挂件
                        }
                    }
                }
                mModeCallBack.finishActionMode();
            }
        }.execute();
    }

            /**
             * 删除指定的文件夹
             * @param folderId 待删除的文件夹 ID
             */
            private void deleteFolder(long folderId) {
                if (folderId == Notes.ID_ROOT_FOLDER) { // 如果待删除的是根文件夹，记录错误日志并直接返回
                    Log.e(TAG, "Wrong folder id, should not happen " + folderId);
                    return;
                }

                HashSet<Long> ids = new HashSet<Long>();
                ids.add(folderId);
                HashSet<AppWidgetAttribute> widgets = DataUtils.getFolderNoteWidget(mContentResolver,
                        folderId);
                if (!isSyncMode()) { // 如果不在同步模式，直接删除文件夹
                    DataUtils.batchDeleteNotes(mContentResolver, ids);
                } else { // 否则将待删除文件夹移动到回收站文件夹中
                    DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER);
                }
                if (widgets != null) { // 更新相关小部件
                    for (AppWidgetAttribute widget : widgets) {
                        if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID
                                && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {
                            updateWidget(widget.widgetId, widget.widgetType);
                        }
                    }
                }
            }

            // 打开笔记
            private void openNode(NoteItemData data) {
                Intent intent = new Intent(this, NoteEditActivity.class);
                intent.setAction(Intent.ACTION_VIEW);
                intent.putExtra(Intent.EXTRA_UID, data.getId());
                this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE);
            }

// 打开文件夹
            private void openFolder(NoteItemData data) {
                mCurrentFolderId = data.getId();
                startAsyncNotesListQuery();
                // 根据当前打开的文件夹设置状态和标题
                if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
                    mState = ListEditState.CALL_RECORD_FOLDER;
                    mAddNewNote.setVisibility(View.GONE);
                } else {
                    mState = ListEditState.SUB_FOLDER;
                }
                if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
                    mTitleBar.setText(R.string.call_record_folder_name);
                } else {
                    mTitleBar.setText(data.getSnippet());
                }
                mTitleBar.setVisibility(View.VISIBLE);
            }

            // 监听器接口中的点击事件响应方法
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btn_new_note: // 如果是新建笔记按钮被点击
                        createNewNote(); // 创建新笔记
                        break;
                    default:
                        break;
                }
            }

// 显示软键盘
            private void showSoftInput() {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (inputMethodManager != null) {
                    inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
                }
            }

// 隐藏软键盘
            private void hideSoftInput(View view) {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
            /**
             * 显示创建或修改文件夹对话框
             *
             * @param create 是否创建文件夹
             */
            private void showCreateOrModifyFolderDialog(final boolean create) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null);
                final EditText etName = (EditText) view.findViewById(R.id.et_foler_name);
                showSoftInput();
                if (!create) {
                    if (mFocusNoteDataItem != null) {
                        etName.setText(mFocusNoteDataItem.getSnippet());
                        builder.setTitle(getString(R.string.menu_folder_change_name));
                    } else {
                        Log.e(TAG, "长按数据项为空");
                        return;
                    }
                } else {
                    etName.setText("");
                    builder.setTitle(this.getString(R.string.menu_create_folder));
                }

                builder.setPositiveButton(android.R.string.ok, null);
                builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        hideSoftInput(etName);
                    }
                });

                final Dialog dialog = builder.setView(view).show();
                final Button positive = (Button) dialog.findViewById(android.R.id.button1);
                positive.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        hideSoftInput(etName);
                        String name = etName.getText().toString();
                        if (DataUtils.checkVisibleFolderName(mContentResolver, name)) {
                            Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name),
                                    Toast.LENGTH_LONG).show();
                            etName.setSelection(0, etName.length());
                            return;
                        }
                        if (!create) {
                            if (!TextUtils.isEmpty(name)) {
                                ContentValues values = new ContentValues();
                                values.put(NoteColumns.SNIPPET, name);
                                values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
                                values.put(NoteColumns.LOCAL_MODIFIED, 1);
                                mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID
                                        + "=?", new String[]{
                                        String.valueOf(mFocusNoteDataItem.getId())
                                });
                            }
                        } else if (!TextUtils.isEmpty(name)) {
                            ContentValues values = new ContentValues();
                            values.put(NoteColumns.SNIPPET, name);
                            values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
                            mContentResolver.insert(Notes.CONTENT_NOTE_URI, values);
                        }
                        dialog.dismiss();
                    }
                });

                if (TextUtils.isEmpty(etName.getText())) {
                    positive.setEnabled(false);
                }
                /**
                 * 当名称编辑文本为空时，禁用积极按钮
                 */
                etName.addTextChangedListener(new TextWatcher() {
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                        // TODO Auto-generated method stub
                    }

                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        if (TextUtils.isEmpty(etName.getText())) {
                            positive.setEnabled(false);
                        } else {
                            positive.setEnabled(true);
                        }
                    }

                    public void afterTextChanged(Editable s) {
                        // TODO Auto-generated method stub
                    }
                });
            }

            @Override
            public void onBackPressed() {
                switch (mState) {
                    case SUB_FOLDER:
                        // 返回根目录，切换状态并刷新列表
                        mCurrentFolderId = Notes.ID_ROOT_FOLDER;
                        mState = ListEditState.NOTE_LIST;
                        startAsyncNotesListQuery();
                        mTitleBar.setVisibility(View.GONE);
                        break;
                    case CALL_RECORD_FOLDER:
                        // 返回根目录，切换状态并刷新列表
                        mCurrentFolderId = Notes.ID_ROOT_FOLDER;
                        mState = ListEditState.NOTE_LIST;
                        mAddNewNote.setVisibility(View.VISIBLE);
                        mTitleBar.setVisibility(View.GONE);
                        startAsyncNotesListQuery();
                        break;
                    case NOTE_LIST:
                        super.onBackPressed(); // 默认返回操作
                        break;
                    default:
                        break;
                }
            }

/**
 * 更新 widget
 *
 * @param appWidgetId   widget id
 * @param appWidgetType widget 类型
 */
            private void updateWidget(int appWidgetId, int appWidgetType) {
                Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                if (appWidgetType == Notes.TYPE_WIDGET_2X) {
                    intent.setClass(this, NoteWidgetProvider_2x.class);
                } else if (appWidgetType == Notes.TYPE_WIDGET_4X) {
                    intent.setClass(this, NoteWidgetProvider_4x.class);
                } else {
                    Log.e(TAG, "Unspported widget type");
                    return;
                }

                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { appWidgetId });

                // 发送广播通知 widget 更新数据
                sendBroadcast(intent);
                setResult(RESULT_OK, intent);
            }
            @Override
            public void onBackPressed() {
                switch (mState) {
                    case SUB_FOLDER:
                        // 返回根目录，切换状态并刷新列表
                        mCurrentFolderId = Notes.ID_ROOT_FOLDER;
                        mState = ListEditState.NOTE_LIST;
                        startAsyncNotesListQuery();
                        mTitleBar.setVisibility(View.GONE);
                        break;
                    case CALL_RECORD_FOLDER:
                        // 返回根目录，切换状态并刷新列表
                        mCurrentFolderId = Notes.ID_ROOT_FOLDER;
                        mState = ListEditState.NOTE_LIST;
                        mAddNewNote.setVisibility(View.VISIBLE);
                        mTitleBar.setVisibility(View.GONE);
                        startAsyncNotesListQuery();
                        break;
                    case NOTE_LIST:
                        super.onBackPressed(); // 默认返回操作
                        break;
                    default:
                        break;
                }
            }

/**
 * 更新 widget
 *
 * @param appWidgetId   widget id
 * @param appWidgetType widget 类型
 */
            private void updateWidget(int appWidgetId, int appWidgetType) {
                Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                if (appWidgetType == Notes.TYPE_WIDGET_2X) {
                    intent.setClass(this, NoteWidgetProvider_2x.class);
                } else if (appWidgetType == Notes.TYPE_WIDGET_4X) {
                    intent.setClass(this, NoteWidgetProvider_4x.class);
                } else {
                    Log.e(TAG, "Unspported widget type");
                    return;
                }

                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { appWidgetId });

                // 发送广播通知 widget 更新数据
                sendBroadcast(intent);
                setResult(RESULT_OK, intent);
            }

            这段代码是一个Android Activity中的方法，用于创建并显示选项菜单。下面是带有中文注释的代码：

            @Override
            public boolean onPrepareOptionsMenu(Menu menu) {
                menu.clear(); //清空菜单
                if (mState == ListEditState.NOTE_LIST) { //如果状态为笔记列表
                    getMenuInflater().inflate(R.menu.note_list, menu); //加载笔记列表菜单布局
                    // 设置同步或取消同步菜单项的标题
                    menu.findItem(R.id.menu_sync).setTitle(
                            GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync);
                } else if (mState == ListEditState.SUB_FOLDER) { //如果状态为子文件夹
                    getMenuInflater().inflate(R.menu.sub_folder, menu); //加载子文件夹菜单布局
                } else if (mState == ListEditState.CALL_RECORD_FOLDER) { //如果状态为通话记录文件夹
                    getMenuInflater().inflate(R.menu.call_record_folder, menu); //加载通话记录文件夹菜单布局
                } else {
                    Log.e(TAG, "Wrong state:" + mState); //如果状态错误，则记录日志
                }
                return true; //返回true表示菜单已经准备好了
            }

            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
                switch (item.getItemId()) { //根据菜单项的id进行处理
                    case R.id.menu_new_folder: { //新建文件夹
                        showCreateOrModifyFolderDialog(true); //显示创建或修改文件夹对话框
                        break;
                    }
                    case R.id.menu_export_text: { //导出为文本
                        exportNoteToText(); //导出笔记到文本文件
                        break;
                    }
                    case R.id.menu_sync: { //同步
                        if (isSyncMode()) { //如果处于同步模式
                            if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) {
                                GTaskSyncService.startSync(this); //开始同步
                            } else {
                                GTaskSyncService.cancelSync(this); //取消同步
                            }
                        } else {
                            startPreferenceActivity(); //启动设置页面
                        }
                        break;
                    }
                    case R.id.menu_setting: { //设置
                        startPreferenceActivity(); //启动设置页面
                        break;
                    }
                    case R.id.menu_new_note: { //新建笔记
                        createNewNote(); //创建新笔记
                        break;
                    }
                    case R.id.menu_search: //搜索
                        onSearchRequested(); //启动搜索
                        break;
                    default:
                        break;
                }
                return true; //返回true表示菜单项已经被处理了
            }

            // 点击导出文本菜单项时调用该方法，将笔记导出为文本文件
            private void exportNoteToText() {
                final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this);
                new AsyncTask<Void, Void, Integer>() {
                    // 在后台线程中执行导出操作
                    @Override
                    protected Integer doInBackground(Void... unused) {
                        return backup.exportToText();
                    }
                    // 导出完成后根据结果弹出对话框显示提示信息
                    @Override
                    protected void onPostExecute(Integer result) {
                        if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) {
                            // 如果SD卡未挂载，显示导出失败的提示对话框
                            AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
                            builder.setTitle(NotesListActivity.this.getString(R.string.failed_sdcard_export));
                            builder.setMessage(NotesListActivity.this.getString(R.string.error_sdcard_unmounted));
                            builder.setPositiveButton(android.R.string.ok, null);
                            builder.show();
                        } else if (result == BackupUtils.STATE_SUCCESS) {
                            // 如果导出成功，显示导出成功的提示对话框
                            AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
                            builder.setTitle(NotesListActivity.this.getString(R.string.success_sdcard_export));
                            builder.setMessage(NotesListActivity.this.getString(
                                    R.string.format_exported_file_location, backup.getExportedTextFileName(),
                                    backup.getExportedTextFileDir()));
                            builder.setPositiveButton(android.R.string.ok, null);
                            builder.show();
                        } else if (result == BackupUtils.STATE_SYSTEM_ERROR) {
                            // 如果出现系统错误，显示导出失败的提示对话框
                            AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
                            builder.setTitle(NotesListActivity.this.getString(R.string.failed_sdcard_export));
                            builder.setMessage(NotesListActivity.this.getString(R.string.error_sdcard_export));
                            builder.setPositiveButton(android.R.string.ok, null);
                            builder.show();
                        }
                    }
                }.execute();
            }

            private boolean isSyncMode() {
// 判断是否启用同步模式
                return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
            }

            private void startPreferenceActivity() {
// 启动设置页面
                Activity from = getParent() != null ? getParent() : this;
                Intent intent = new Intent(from, NotesPreferenceActivity.class);
                from.startActivityIfNeeded(intent, -1);
            }

    private class OnListItemClickListener implements OnItemClickListener {

        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (view instanceof NotesListItem) {
                NoteItemData item = ((NotesListItem) view).getItemData();
                if (mNotesListAdapter.isInChoiceMode()) {
                    // 如果是选择模式，则更新选择状态
                    if (item.getType() == Notes.TYPE_NOTE) {
                        position = position - mNotesListView.getHeaderViewsCount();
                        mModeCallBack.onItemCheckedStateChanged(null, position, id,
                                !mNotesListAdapter.isSelectedItem(position));
                    }
                    return;
                }

                switch (mState) {
                    case NOTE_LIST:
                        // 在笔记列表中，根据笔记或文件夹类型打开对应项
                        if (item.getType() == Notes.TYPE_FOLDER || item.getType() == Notes.TYPE_SYSTEM) {
                            openFolder(item);
                        } else if (item.getType() == Notes.TYPE_NOTE) {
                            openNode(item);
                        } else {
                            Log.e(TAG, "Wrong note type in NOTE_LIST");
                        }
                        break;
                    case SUB_FOLDER:
                    case CALL_RECORD_FOLDER:
                        // 在子文件夹列表或通话记录文件夹中，打开对应的笔记
                        if (item.getType() == Notes.TYPE_NOTE) {
                            openNode(item);
                        } else {
                            Log.e(TAG, "Wrong note type in SUB_FOLDER");
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        // 开始查询目标文件夹
        private void startQueryDestinationFolders() {
// 筛选条件，查询类型为文件夹且父文件夹不是回收站文件夹也不是当前文件夹
            String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?";
// 如果当前状态是在笔记列表，那么直接使用该筛选条件；如果当前状态是在文件夹列表，还需要加上查询根目录的条件
            selection = (mState == ListEditState.NOTE_LIST) ? selection:
                    "(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")";

            // 开始异步查询
            mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN,
                    null,
                    Notes.CONTENT_NOTE_URI,
                    FoldersListAdapter.PROJECTION,
                    selection,
                    new String[] {
                            String.valueOf(Notes.TYPE_FOLDER),
                            String.valueOf(Notes.ID_TRASH_FOLER),
                            String.valueOf(mCurrentFolderId)
                    },
                    NoteColumns.MODIFIED_DATE + " DESC");

        }

        // 长按列表项触发
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            if (view instanceof NotesListItem) {
                mFocusNoteDataItem = ((NotesListItem) view).getItemData();
                if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) {
// 如果长按的是笔记类型的列表项且没有进入多选模式，则进入多选模式
                    if (mNotesListView.startActionMode(mModeCallBack) !OnCreateContextMenuListener= null) {
                        mModeCallBack.onItemCheckedStateChanged(null, position, id, true);
                        mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
                    } else {
                        Log.e(TAG, "startActionMode fails");
                    }
                } else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) {
// 如果长按的是文件夹类型的列表项，则注册一个创建上下文菜单的监听器
                    mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener);
                }
            }
            return false;
        }