2 * Copyright (C) 2012 The CyanogenMod Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.cyanogenmod.filemanager.activities;
19 import android.app.ActionBar;
20 import android.app.Activity;
21 import android.app.AlertDialog;
22 import android.app.SearchManager;
23 import android.content.BroadcastReceiver;
24 import android.content.Context;
25 import android.content.DialogInterface;
26 import android.content.Intent;
27 import android.content.IntentFilter;
28 import android.content.res.Configuration;
29 import android.os.Bundle;
30 import android.os.Parcelable;
31 import android.preference.PreferenceActivity;
32 import android.provider.SearchRecentSuggestions;
33 import android.text.Html;
34 import android.text.TextUtils;
35 import android.util.Log;
36 import android.view.KeyEvent;
37 import android.view.MenuItem;
38 import android.view.View;
39 import android.widget.AdapterView;
40 import android.widget.AdapterView.OnItemClickListener;
41 import android.widget.AdapterView.OnItemLongClickListener;
42 import android.widget.ImageView;
43 import android.widget.ListAdapter;
44 import android.widget.ListView;
45 import android.widget.ProgressBar;
46 import android.widget.TextView;
47 import android.widget.Toast;
49 import com.cyanogenmod.filemanager.FileManagerApplication;
50 import com.cyanogenmod.filemanager.R;
51 import com.cyanogenmod.filemanager.activities.preferences.SearchPreferenceFragment;
52 import com.cyanogenmod.filemanager.activities.preferences.SettingsPreferences;
53 import com.cyanogenmod.filemanager.adapters.SearchResultAdapter;
54 import com.cyanogenmod.filemanager.commands.AsyncResultExecutable;
55 import com.cyanogenmod.filemanager.commands.AsyncResultListener;
56 import com.cyanogenmod.filemanager.console.NoSuchFileOrDirectory;
57 import com.cyanogenmod.filemanager.console.RelaunchableException;
58 import com.cyanogenmod.filemanager.listeners.OnRequestRefreshListener;
59 import com.cyanogenmod.filemanager.model.Directory;
60 import com.cyanogenmod.filemanager.model.FileSystemObject;
61 import com.cyanogenmod.filemanager.model.ParentDirectory;
62 import com.cyanogenmod.filemanager.model.Query;
63 import com.cyanogenmod.filemanager.model.SearchResult;
64 import com.cyanogenmod.filemanager.model.Symlink;
65 import com.cyanogenmod.filemanager.parcelables.SearchInfoParcelable;
66 import com.cyanogenmod.filemanager.preferences.AccessMode;
67 import com.cyanogenmod.filemanager.preferences.FileManagerSettings;
68 import com.cyanogenmod.filemanager.preferences.Preferences;
69 import com.cyanogenmod.filemanager.providers.RecentSearchesContentProvider;
70 import com.cyanogenmod.filemanager.tasks.SearchResultDrawingAsyncTask;
71 import com.cyanogenmod.filemanager.ui.ThemeManager;
72 import com.cyanogenmod.filemanager.ui.ThemeManager.Theme;
73 import com.cyanogenmod.filemanager.ui.dialogs.ActionsDialog;
74 import com.cyanogenmod.filemanager.ui.dialogs.MessageProgressDialog;
75 import com.cyanogenmod.filemanager.ui.policy.DeleteActionPolicy;
76 import com.cyanogenmod.filemanager.ui.policy.IntentsActionPolicy;
77 import com.cyanogenmod.filemanager.ui.widgets.ButtonItem;
78 import com.cyanogenmod.filemanager.ui.widgets.FlingerListView;
79 import com.cyanogenmod.filemanager.ui.widgets.FlingerListView.OnItemFlingerListener;
80 import com.cyanogenmod.filemanager.ui.widgets.FlingerListView.OnItemFlingerResponder;
81 import com.cyanogenmod.filemanager.util.CommandHelper;
82 import com.cyanogenmod.filemanager.util.DialogHelper;
83 import com.cyanogenmod.filemanager.util.ExceptionUtil;
84 import com.cyanogenmod.filemanager.util.ExceptionUtil.OnRelaunchCommandResult;
85 import com.cyanogenmod.filemanager.util.FileHelper;
86 import com.cyanogenmod.filemanager.util.StorageHelper;
88 import java.io.FileNotFoundException;
89 import java.util.ArrayList;
90 import java.util.List;
93 * An activity for search files and folders.
95 public class SearchActivity extends Activity
96 implements AsyncResultListener, OnItemClickListener,
97 OnItemLongClickListener, OnRequestRefreshListener {
99 private static final String TAG = "SearchActivity"; //$NON-NLS-1$
101 private static boolean DEBUG = false;
104 * An {@link Intent} action for restore view information.
106 public static final String ACTION_RESTORE =
107 "com.cyanogenmod.filemanager.activities.SearchActivity#Restore"; //$NON-NLS-1$
110 * Intent extra parameter for search in the selected directory on enter.
112 public static final String EXTRA_SEARCH_DIRECTORY = "extra_search_directory"; //$NON-NLS-1$
115 * Intent extra parameter for pass the restore information.
117 public static final String EXTRA_SEARCH_RESTORE = "extra_search_restore"; //$NON-NLS-1$
120 //Minimum characters to allow query
121 private static final int MIN_CHARS_SEARCH = 3;
123 private final BroadcastReceiver mNotificationReceiver = new BroadcastReceiver() {
125 public void onReceive(Context context, Intent intent) {
126 if (intent != null) {
127 if (intent.getAction().compareTo(
128 FileManagerSettings.INTENT_SETTING_CHANGED) == 0) {
130 // The settings has changed
131 String key = intent.getStringExtra(
132 FileManagerSettings.EXTRA_SETTING_CHANGED_KEY);
134 if (SearchActivity.this.mSearchListView.getAdapter() != null &&
137 SETTINGS_HIGHLIGHT_TERMS.getId()) == 0 ||
140 SETTINGS_SHOW_RELEVANCE_WIDGET.getId()) == 0 ||
143 SETTINGS_SORT_SEARCH_RESULTS_MODE.getId()) == 0)) {
145 // Recreate the adapter
146 int pos = SearchActivity.
147 this.mSearchListView.getFirstVisiblePosition();
149 SearchActivity.this.mSearchListView.setSelection(pos);
153 } else if (intent.getAction().compareTo(
154 FileManagerSettings.INTENT_THEME_CHANGED) == 0) {
162 * A listener for flinging events from {@link FlingerListView}
164 private final OnItemFlingerListener mOnItemFlingerListener = new OnItemFlingerListener() {
167 public boolean onItemFlingerStart(
168 AdapterView<?> parent, View view, int position, long id) {
170 // Response if the item can be removed
171 SearchResultAdapter adapter = (SearchResultAdapter)parent.getAdapter();
172 SearchResult result = adapter.getItem(position);
173 if (result != null && result.getFso() != null) {
174 if (result.getFso() instanceof ParentDirectory) {
175 // This is not possible ...
180 } catch (Exception e) {
181 ExceptionUtil.translateException(SearchActivity.this, e, true, false);
187 public void onItemFlingerEnd(OnItemFlingerResponder responder,
188 AdapterView<?> parent, View view, int position, long id) {
191 // Response if the item can be removed
192 SearchResultAdapter adapter = (SearchResultAdapter)parent.getAdapter();
193 SearchResult result = adapter.getItem(position);
194 if (result != null && result.getFso() != null) {
195 DeleteActionPolicy.removeFileSystemObject(
204 // Cancels the flinger operation
207 } catch (Exception e) {
208 ExceptionUtil.translateException(SearchActivity.this, e, true, false);
217 MessageProgressDialog mDialog = null;
221 AsyncResultExecutable mExecutable = null;
226 ListView mSearchListView;
230 ProgressBar mSearchWaiting;
234 TextView mSearchFoundItems;
238 TextView mSearchTerms;
239 private View mEmptyListMsg;
241 private String mSearchDirectory;
245 List<FileSystemObject> mResultList;
254 SearchInfoParcelable mRestoreState;
256 private SearchResultDrawingAsyncTask mDrawingSearchResultTask;
268 protected void onCreate(Bundle state) {
270 Log.d(TAG, "SearchActivity.onCreate"); //$NON-NLS-1$
273 // Check if app is running in chrooted mode
274 this.mChRooted = FileManagerApplication.getAccessMode().compareTo(AccessMode.SAFE) == 0;
276 // Register the broadcast receiver
277 IntentFilter filter = new IntentFilter();
278 filter.addAction(FileManagerSettings.INTENT_SETTING_CHANGED);
279 filter.addAction(FileManagerSettings.INTENT_THEME_CHANGED);
280 registerReceiver(this.mNotificationReceiver, filter);
283 overridePendingTransition(R.anim.translate_to_right_in, R.anim.hold_out);
285 //Set the main layout of the activity
286 setContentView(R.layout.search);
293 //Initialize action bars and search
294 initTitleActionBar();
297 // Apply current theme
300 if (this.mRestoreState != null) {
301 //Restore activity from cached data
305 if (Intent.ACTION_SEARCH.equals(getIntent().getAction())) {
307 } else if (ACTION_RESTORE.equals(getIntent().getAction())) {
308 restoreState(getIntent().getExtras());
314 super.onCreate(state);
321 protected void onDestroy() {
323 Log.d(TAG, "SearchActivity.onDestroy"); //$NON-NLS-1$
326 // Unregister the receiver
328 unregisterReceiver(this.mNotificationReceiver);
329 } catch (Throwable ex) {
333 //All destroy. Continue
341 public void onConfigurationChanged(Configuration newConfig) {
342 super.onConfigurationChanged(newConfig);
349 protected void onNewIntent(Intent intent) {
351 if (Intent.ACTION_SEARCH.equals(getIntent().getAction())) {
360 protected void onPause() {
362 overridePendingTransition(R.anim.hold_in, R.anim.translate_to_left_out);
370 protected void onSaveInstanceState(Bundle outState) {
372 Log.d(TAG, "SearchActivity.onSaveInstanceState"); //$NON-NLS-1$
375 super.onSaveInstanceState(outState);
379 * Method that save the instance of the activity.
381 * @param state The current state of the activity
383 private void saveState(Bundle state) {
385 if (this.mSearchListView.getAdapter() != null) {
386 state.putParcelable(EXTRA_SEARCH_RESTORE, createSearchInfo());
388 } catch (Throwable ex) {
389 Log.w(TAG, "The state can't be saved", ex); //$NON-NLS-1$
394 * Method that restore the instance of the activity.
396 * @param state The previous state of the activity
398 private void restoreState(Bundle state) {
400 if (state.containsKey(EXTRA_SEARCH_RESTORE)) {
401 this.mRestoreState = state.getParcelable(EXTRA_SEARCH_RESTORE);
403 } catch (Throwable ex) {
404 Log.w(TAG, "The state can't be restored", ex); //$NON-NLS-1$
409 * Method that initializes the titlebar of the activity.
411 private void initTitleActionBar() {
412 //Configure the action bar options
413 getActionBar().setBackgroundDrawable(
414 getResources().getDrawable(R.drawable.bg_holo_titlebar));
415 getActionBar().setDisplayOptions(
416 ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);
417 getActionBar().setDisplayHomeAsUpEnabled(true);
418 View customTitle = getLayoutInflater().inflate(R.layout.simple_customtitle, null, false);
420 TextView title = (TextView)customTitle.findViewById(R.id.customtitle_title);
421 title.setText(R.string.search);
422 title.setContentDescription(getString(R.string.search));
423 ButtonItem configuration = (ButtonItem)customTitle.findViewById(R.id.ab_button1);
424 configuration.setImageResource(R.drawable.ic_holo_light_config);
425 configuration.setVisibility(View.VISIBLE);
427 getActionBar().setCustomView(customTitle);
431 * Method that initializes the component of the activity.
433 private void initComponents() {
435 this.mEmptyListMsg = findViewById(R.id.search_empty_msg);
437 this.mSearchListView = (ListView)findViewById(R.id.search_listview);
438 this.mSearchListView.setOnItemClickListener(this);
439 this.mSearchListView.setOnItemLongClickListener(this);
441 // If we should set the listview to response to flinger gesture detection
443 Preferences.getSharedPreferences().getBoolean(
444 FileManagerSettings.SETTINGS_USE_FLINGER.getId(),
445 ((Boolean)FileManagerSettings.
446 SETTINGS_USE_FLINGER.
447 getDefaultValue()).booleanValue());
449 ((FlingerListView)this.mSearchListView).
450 setOnItemFlingerListener(this.mOnItemFlingerListener);
454 this.mSearchWaiting = (ProgressBar)findViewById(R.id.search_waiting);
455 this.mSearchFoundItems = (TextView)findViewById(R.id.search_status_found_items);
456 setFoundItems(0, ""); //$NON-NLS-1$
457 this.mSearchTerms = (TextView)findViewById(R.id.search_status_query_terms);
458 this.mSearchTerms.setText(
459 Html.fromHtml(getString(R.string.search_terms, ""))); //$NON-NLS-1$
463 * Method invoked when an action item is clicked.
465 * @param view The button pushed
467 public void onActionBarItemClick(View view) {
468 switch (view.getId()) {
469 case R.id.ab_button1:
471 Intent settings = new Intent(this, SettingsPreferences.class);
473 PreferenceActivity.EXTRA_SHOW_FRAGMENT,
474 SearchPreferenceFragment.class.getName());
475 startActivity(settings);
484 * Method that initializes the titlebar of the activity.
486 private void initSearch() {
487 //Stop any pending action
489 if (SearchActivity.this.mDrawingSearchResultTask != null
490 && SearchActivity.this.mDrawingSearchResultTask.isRunning()) {
491 SearchActivity.this.mDrawingSearchResultTask.cancel(true);
493 } catch (Throwable ex2) {
497 if (SearchActivity.this.mDialog != null) {
498 SearchActivity.this.mDialog.dismiss();
500 } catch (Throwable ex2) {
504 //Recovery the search directory
505 Bundle bundle = getIntent().getBundleExtra(SearchManager.APP_DATA);
506 //If data is not present, use root directory to do the search
507 this.mSearchDirectory = FileHelper.ROOT_DIRECTORY;
508 if (bundle != null) {
509 this.mSearchDirectory =
510 bundle.getString(EXTRA_SEARCH_DIRECTORY, FileHelper.ROOT_DIRECTORY);
513 //Retrieve the query ¿from voice recognizer?
514 boolean voiceQuery = true;
515 List<String> userQueries =
516 getIntent().getStringArrayListExtra(android.speech.RecognizerIntent.EXTRA_RESULTS);
517 if (userQueries == null || userQueries.size() == 0) {
519 userQueries = new ArrayList<String>();
520 //Recovers and save the last term search in the memory
521 Preferences.setLastSearch(getIntent().getStringExtra(SearchManager.QUERY));
522 userQueries.add(Preferences.getLastSearch());
526 //Filter the queries? Needed if queries come from voice recognition
527 final List<String> filteredUserQueries =
528 (voiceQuery) ? filterQuery(userQueries) : userQueries;
531 this.mQuery = new Query().fillSlots(filteredUserQueries);
532 List<String> queries = this.mQuery.getQueries();
534 //Check if some queries has lower than allowed, in this case
535 //request the user for stop the search
537 int cc = queries.size();
538 for (int i = 0; i < cc; i++) {
539 if (queries.get(i).trim().length() < MIN_CHARS_SEARCH) {
545 askUserBeforeSearch(voiceQuery, this.mQuery, this.mSearchDirectory);
547 doSearch(voiceQuery, this.mQuery, this.mSearchDirectory);
553 * Method that ask the user before do the search.
555 * @param voiceQuery Indicates if the query is from voice recognition
556 * @param query The terms of the search
557 * @param searchDirectory The directory of the search
559 private void askUserBeforeSearch(
560 final boolean voiceQuery, final Query query, final String searchDirectory) {
561 //Show a dialog asking the user
563 DialogHelper.createYesNoDialog(
565 R.string.search_few_characters_title,
566 R.string.search_few_characters_msg,
567 new DialogInterface.OnClickListener() {
569 public void onClick(DialogInterface alertDialog, int which) {
570 if (which == DialogInterface.BUTTON_POSITIVE) {
571 doSearch(voiceQuery, query, searchDirectory);
575 //Close search activity
576 back(true, null, false);
579 DialogHelper.delegateDialogShow(this, dialog);
583 * Method that do the search.
585 * @param voiceQuery Indicates if the query is from voice recognition
586 * @param query The terms of the search
587 * @param searchDirectory The directory of the search
591 final boolean voiceQuery, final Query query, final String searchDirectory) {
593 // Recovers the user preferences about save suggestions
594 boolean saveSuggestions = Preferences.getSharedPreferences().getBoolean(
595 FileManagerSettings.SETTINGS_SAVE_SEARCH_TERMS.getId(),
596 ((Boolean)FileManagerSettings.SETTINGS_SAVE_SEARCH_TERMS.
597 getDefaultValue()).booleanValue());
598 if (saveSuggestions) {
599 //Save every query for use as recent suggestions
600 SearchRecentSuggestions suggestions =
601 new SearchRecentSuggestions(this,
602 RecentSearchesContentProvider.AUTHORITY,
603 RecentSearchesContentProvider.MODE);
605 List<String> queries = query.getQueries();
606 int cc = queries.size();
607 for (int i = 0; i < cc; i++) {
608 suggestions.saveRecentQuery(queries.get(i), null);
614 if (this.mSearchListView.getAdapter() != null) {
615 ((SearchResultAdapter)this.mSearchListView.getAdapter()).dispose();
617 this.mResultList = new ArrayList<FileSystemObject>();
618 SearchResultAdapter adapter =
619 new SearchResultAdapter(this,
620 new ArrayList<SearchResult>(), R.layout.search_item, this.mQuery);
621 this.mSearchListView.setAdapter(adapter);
624 this.mSearchTerms.setText(
625 Html.fromHtml(getString(R.string.search_terms, query.getTerms())));
627 //Now, do the search in background
628 this.mSearchListView.post(new Runnable() {
632 //Retrieve the terms of the search
633 String label = getString(R.string.searching_action_label);
635 //Show a dialog for the progress
636 SearchActivity.this.mDialog =
637 new MessageProgressDialog(
640 R.string.searching, label, true);
644 // Set the cancel listener
645 SearchActivity.this.mDialog.setOnCancelListener(
646 new MessageProgressDialog.OnCancelListener() {
648 public boolean onCancel() {
649 //User has requested the cancellation of the search
650 //Broadcast the cancellation
651 if (!SearchActivity.this.mExecutable.isCancelled()) {
652 if (SearchActivity.this.mExecutable.cancel()) {
653 ListAdapter listAdapter =
655 this.mSearchListView.getAdapter();
656 if (listAdapter != null) {
657 SearchActivity.this.toggleResults(
658 listAdapter.getCount() > 0, true);
667 SearchActivity.this.mDialog.show();
669 //Execute the query (search are process in background)
670 SearchActivity.this.mExecutable =
671 CommandHelper.findFiles(
674 SearchActivity.this.mQuery,
678 } catch (Throwable ex) {
679 //Remove all elements
681 SearchActivity.this.removeAll();
682 } catch (Throwable ex2) {
686 if (SearchActivity.this.mDialog != null) {
687 SearchActivity.this.mDialog.dismiss();
689 } catch (Throwable ex2) {
693 //Capture the exception
694 Log.e(TAG, "Search failed", ex); //$NON-NLS-1$
695 DialogHelper.showToast(
697 R.string.search_error_msg, Toast.LENGTH_SHORT);
698 SearchActivity.this.mSearchListView.setVisibility(View.GONE);
705 * Method that restore the activity from the cached data.
707 private void loadFromCacheData() {
708 this.mSearchListView.post(new Runnable() {
712 List<SearchResult> list = SearchActivity.this.mRestoreState.getSearchResultList();
713 String directory = SearchActivity.this.mRestoreState.getSearchDirectory();
714 SearchActivity.this.toggleResults(list.size() > 0, true);
715 setFoundItems(list.size(), directory);
718 Query query = SearchActivity.this.mRestoreState.getSearchQuery();
720 TextUtils.join(" | ", //$NON-NLS-1$;
721 query.getQueries().toArray(new String[]{}));
722 if (terms.endsWith(" | ")) { //$NON-NLS-1$;
723 terms = ""; //$NON-NLS-1$;
725 SearchActivity.this.mSearchTerms.setText(
726 Html.fromHtml(getString(R.string.search_terms, terms)));
729 if (SearchActivity.this.mSearchWaiting != null) {
730 SearchActivity.this.mSearchWaiting.setVisibility(View.VISIBLE);
733 //Add list to the listview
734 if (SearchActivity.this.mSearchListView.getAdapter() != null) {
735 ((SearchResultAdapter)SearchActivity.this.
736 mSearchListView.getAdapter()).clear();
738 SearchResultAdapter adapter =
739 new SearchResultAdapter(
740 SearchActivity.this.mSearchListView.getContext(),
742 R.layout.search_item,
744 SearchActivity.this.mSearchListView.setAdapter(adapter);
745 SearchActivity.this.mSearchListView.setSelection(0);
747 } catch (Throwable ex) {
748 //Capture the exception
749 ExceptionUtil.translateException(SearchActivity.this, ex);
753 if (SearchActivity.this.mSearchWaiting != null) {
754 SearchActivity.this.mSearchWaiting.setVisibility(View.GONE);
762 * Method that filter the user queries for valid queries only.<br/>
764 * Only allow query strings with more that 3 characters
766 * @param original The original user queries
767 * @return List<String> The list of queries filtered
769 @SuppressWarnings("static-method")
770 private List<String> filterQuery(List<String> original) {
771 List<String> dst = new ArrayList<String>(original);
773 for (int i = cc - 1; i >= 0; i--) {
774 String query = dst.get(i);
775 if (query == null || query.trim().length() < MIN_CHARS_SEARCH) {
783 * Method that removes all items and display a message.
787 SearchResultAdapter adapter = (SearchResultAdapter)this.mSearchListView.getAdapter();
789 this.mSearchListView.setSelection(0);
790 toggleResults(false, true);
794 * Method that toggle the views when there are results.
796 * @param hasResults Indicates if there are results
797 * @param showEmpty Show the empty list message
800 void toggleResults(boolean hasResults, boolean showEmpty) {
801 this.mSearchListView.setVisibility(hasResults ? View.VISIBLE : View.INVISIBLE);
802 this.mEmptyListMsg.setVisibility(!hasResults && showEmpty ? View.VISIBLE : View.INVISIBLE);
806 * Method that display the number of found items.
808 * @param items The number of items
809 * @param searchDirectory The search directory path
812 void setFoundItems(final int items, final String searchDirectory) {
813 if (this.mSearchFoundItems != null) {
814 this.mSearchFoundItems.post(new Runnable() {
817 String directory = searchDirectory;
818 if (SearchActivity.this.mChRooted &&
819 directory != null && directory.length() > 0) {
820 directory = StorageHelper.getChrootedPath(directory);
826 R.plurals.search_found_items, items, Integer.valueOf(items));
827 SearchActivity.this.mSearchFoundItems.setText(
829 R.string.search_found_items_in_directory,
841 public boolean onKeyUp(int keyCode, KeyEvent event) {
843 case KeyEvent.KEYCODE_BACK:
844 back(true, null, false);
847 return super.onKeyUp(keyCode, event);
855 public boolean onOptionsItemSelected(MenuItem item) {
856 switch (item.getItemId()) {
857 case android.R.id.home:
858 back(true, null, false);
861 return super.onOptionsItemSelected(item);
869 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
871 SearchResult result = ((SearchResultAdapter)parent.getAdapter()).getItem(position);
872 FileSystemObject fso = result.getFso();
873 if (fso instanceof Directory) {
874 back(false, fso, false);
876 } else if (fso instanceof Symlink) {
877 Symlink symlink = (Symlink)fso;
878 if (symlink.getLinkRef() != null && symlink.getLinkRef() instanceof Directory) {
879 back(false, symlink.getLinkRef(), false);
882 fso = symlink.getLinkRef();
885 // Open the file with the preferred registered app
886 back(false, fso, false);
888 } catch (Throwable ex) {
889 ExceptionUtil.translateException(this.mSearchListView.getContext(), ex);
897 public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
898 // Different actions depending on user preference
900 // Get the adapter, the search result and the fso
901 SearchResultAdapter adapter = ((SearchResultAdapter)parent.getAdapter());
902 SearchResult searchResult = adapter.getItem(position);
903 FileSystemObject fso = searchResult.getFso();
905 // Open the actions menu
907 return true; //Always consume the event
911 * Method invoked when a request to show the menu associated
912 * with an item is started.
914 * @param item The item for which the request was started
916 public void onRequestMenu(FileSystemObject item) {
917 // Prior to show the dialog, refresh the item reference
918 FileSystemObject fso = null;
920 fso = CommandHelper.getFileInfo(this, item.getFullPath(), false, null);
922 throw new NoSuchFileOrDirectory(item.getFullPath());
925 } catch (Exception e) {
927 ExceptionUtil.translateException(this, e);
930 if (e instanceof FileNotFoundException || e instanceof NoSuchFileOrDirectory) {
936 ActionsDialog dialog = new ActionsDialog(this, null, fso, false, true);
937 dialog.setOnRequestRefreshListener(this);
942 * Method that removes the {@link FileSystemObject} reference
944 * @param fso The file system object
946 private void removeItem(FileSystemObject fso) {
947 SearchResultAdapter adapter =
948 (SearchResultAdapter)this.mSearchListView.getAdapter();
949 if (adapter != null) {
950 int pos = adapter.getPosition(fso);
952 SearchResult sr = adapter.getItem(pos);
957 toggleResults(adapter.getCount() > 0, true);
958 setFoundItems(adapter.getCount(), this.mSearchDirectory);
966 public void onRequestRefresh(Object o, boolean clearSelection) {
967 // Refresh only the item
968 SearchResultAdapter adapter =
969 (SearchResultAdapter)this.mSearchListView.getAdapter();
970 if (adapter != null) {
971 if (o instanceof FileSystemObject) {
973 FileSystemObject fso = (FileSystemObject)o;
974 int pos = adapter.getPosition(fso);
976 SearchResult sr = adapter.getItem(pos);
979 } else if (o == null) {
981 List<SearchResult> results = adapter.getData();
982 this.mResultList = new ArrayList<FileSystemObject>(results.size());
983 int cc = results.size();
984 for (int i = 0; i < cc; i++) {
985 this.mResultList.add(results.get(i).getFso());
996 public void onRequestRemove(Object o, boolean clearSelection) {
997 if (o instanceof FileSystemObject) {
998 removeItem((FileSystemObject)o);
1006 public void onNavigateTo(Object o) {
1007 if (o instanceof FileSystemObject) {
1008 back(false, (FileSystemObject)o, true);
1013 * Method that returns to previous activity.
1015 * @param cancelled Indicates if the activity was cancelled
1016 * @param item The fso
1017 * @param isChecked If the fso was fully retrieve previously to this call. Otherwise, a
1018 * getFileInfo call is done to complete the fso information
1021 void back(final boolean cancelled, FileSystemObject item, boolean isChecked) {
1022 final Context ctx = SearchActivity.this;
1023 final Intent intent = new Intent();
1024 boolean finish = true;
1026 if (SearchActivity.this.mDrawingSearchResultTask != null
1027 && SearchActivity.this.mDrawingSearchResultTask.isRunning()) {
1028 SearchActivity.this.mDrawingSearchResultTask.cancel(true);
1030 if (this.mRestoreState != null) {
1032 NavigationActivity.EXTRA_SEARCH_LAST_SEARCH_DATA,
1033 (Parcelable)this.mRestoreState);
1035 setResult(RESULT_CANCELED, intent);
1037 // Check that the bookmark exists
1038 FileSystemObject fso = item;
1041 fso = CommandHelper.getFileInfo(ctx, item.getFullPath(), null);
1043 finish = navigateTo(fso, intent);
1045 } catch (Exception e) {
1046 // Capture the exception
1047 final FileSystemObject fFso = fso;
1048 final OnRelaunchCommandResult relaunchListener = new OnRelaunchCommandResult() {
1050 public void onSuccess() {
1051 if (navigateTo(fFso, intent)) {
1056 public void onFailed(Throwable cause) {
1057 ExceptionUtil.translateException(ctx, cause, false, false);
1060 public void onCancelled() { /** NON BLOCK**/}
1062 ExceptionUtil.translateException(ctx, e, false, true, relaunchListener);
1063 if (!(e instanceof RelaunchableException)) {
1064 if (e instanceof NoSuchFileOrDirectory || e instanceof FileNotFoundException) {
1065 // The fso not exists, delete the fso from the search
1068 } catch (Exception ex) {/**NON BLOCK**/}
1075 // End this activity
1082 * Method invoked when the activity needs to exit
1084 private void exit() {
1085 if (this.mSearchListView.getAdapter() != null) {
1086 ((SearchResultAdapter)this.mSearchListView.getAdapter()).dispose();
1092 * Method that navigate to the file system used the intent (NavigationActivity)
1094 * @param fso The file system object to navigate to
1095 * @param intent The intent used to navigate to
1096 * @return boolean If the action implies finish this activity
1098 boolean navigateTo(FileSystemObject fso, Intent intent) {
1100 if (FileHelper.isDirectory(fso)) {
1101 intent.putExtra(NavigationActivity.EXTRA_SEARCH_ENTRY_SELECTION, fso);
1103 NavigationActivity.EXTRA_SEARCH_LAST_SEARCH_DATA,
1104 (Parcelable)createSearchInfo());
1105 setResult(RESULT_OK, intent);
1109 // Open the file here, so when focus back to the app, the search activity
1110 // its in top of the stack
1111 IntentsActionPolicy.openFileSystemObject(this, fso, false, null, null);
1113 // The fso not exists, delete the fso from the search
1116 } catch (Exception ex) {/**NON BLOCK**/}
1125 public void onAsyncStart() {
1126 runOnUiThread(new Runnable() {
1129 SearchActivity.this.toggleResults(false, false);
1138 public void onAsyncEnd(boolean cancelled) {
1139 this.mSearchListView.post(new Runnable() {
1143 //Dismiss the dialog
1144 if (SearchActivity.this.mDialog != null) {
1145 SearchActivity.this.mDialog.dismiss();
1148 // Resolve the symlinks
1149 FileHelper.resolveSymlinks(
1150 SearchActivity.this, SearchActivity.this.mResultList);
1155 } catch (Throwable ex) {
1156 Log.e(TAG, "onAsyncEnd method fails", ex); //$NON-NLS-1$
1166 @SuppressWarnings("unchecked")
1167 public void onPartialResult(final Object partialResults) {
1168 //Saved in the global result list, for save at the end
1169 if (partialResults instanceof FileSystemObject) {
1170 SearchActivity.this.mResultList.add((FileSystemObject)partialResults);
1172 SearchActivity.this.mResultList.addAll((List<FileSystemObject>)partialResults);
1176 this.mSearchListView.post(new Runnable() {
1179 if (SearchActivity.this.mDialog != null) {
1180 int progress = SearchActivity.this.mResultList.size();
1181 setProgressMsg(progress);
1191 public void onAsyncExitCode(int exitCode) {/**NON BLOCK**/}
1197 public void onException(Exception cause) {
1198 //Capture the exception
1199 ExceptionUtil.translateException(this, cause);
1203 * Method that draw the results in the listview
1206 void drawResults() {
1208 this.toggleResults(this.mResultList.size() > 0, true);
1209 setFoundItems(this.mResultList.size(), this.mSearchDirectory);
1211 //Create the task for drawing the data
1212 this.mDrawingSearchResultTask =
1213 new SearchResultDrawingAsyncTask(
1214 this.mSearchListView,
1215 this.mSearchWaiting,
1218 this.mDrawingSearchResultTask.execute();
1222 * Method that creates a {@link SearchInfoParcelable} reference from
1225 * @return SearchInfoParcelable The search info reference
1227 private SearchInfoParcelable createSearchInfo() {
1228 SearchInfoParcelable parcel = new SearchInfoParcelable();
1229 parcel.setSearchDirectory(this.mSearchDirectory);
1230 parcel.setSearchResultList(
1231 ((SearchResultAdapter)this.mSearchListView.getAdapter()).getData());
1232 parcel.setSearchQuery(this.mQuery);
1237 * Method that set the progress of the search
1239 * @param progress The progress
1242 void setProgressMsg(int progress) {
1244 getResources().getQuantityString(
1245 R.plurals.search_found_items,
1247 Integer.valueOf(progress));
1248 SearchActivity.this.mDialog.setProgress(Html.fromHtml(msg));
1252 * Method that applies the current theme to the activity
1256 Theme theme = ThemeManager.getCurrentTheme(this);
1257 theme.setBaseTheme(this, false);
1260 theme.setTitlebarDrawable(this, getActionBar(), "titlebar_drawable"); //$NON-NLS-1$
1261 View v = getActionBar().getCustomView().findViewById(R.id.customtitle_title);
1262 theme.setTextColor(this, (TextView)v, "text_color"); //$NON-NLS-1$
1263 v = findViewById(R.id.ab_button1);
1264 theme.setImageDrawable(this, (ImageView)v, "ic_config_drawable"); //$NON-NLS-1$
1266 theme.setBackgroundDrawable(
1267 this, getWindow().getDecorView(), "background_drawable"); //$NON-NLS-1$
1269 v = findViewById(R.id.search_status);
1270 theme.setBackgroundDrawable(this, v, "statusbar_drawable"); //$NON-NLS-1$
1271 v = findViewById(R.id.search_status_found_items);
1272 theme.setTextColor(this, (TextView)v, "text_color"); //$NON-NLS-1$
1273 v = findViewById(R.id.search_status_query_terms);
1274 theme.setTextColor(this, (TextView)v, "text_color"); //$NON-NLS-1$
1276 if (this.mSearchListView.getAdapter() != null) {
1277 ((SearchResultAdapter)this.mSearchListView.getAdapter()).notifyDataSetChanged();
1279 this.mSearchListView.setDivider(
1280 theme.getDrawable(this, "horizontal_divider_drawable")); //$NON-NLS-1$
1281 this.mSearchListView.invalidate();