Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1708)

Unified Diff: content/public/android/java/src/org/chromium/content/browser/SelectionPopupController.java

Issue 2740103006: Implement SmartText selection. (Closed)
Patch Set: Renamed isReady -> isActionModeSupported, added synchronized in ContentClassFactory Created 3 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: content/public/android/java/src/org/chromium/content/browser/SelectionPopupController.java
diff --git a/content/public/android/java/src/org/chromium/content/browser/SelectionPopupController.java b/content/public/android/java/src/org/chromium/content/browser/SelectionPopupController.java
index 679523249b08b25c8a1cf50a9441352dc7952ea9..be44f4cb55c484a657c3f8ca3ba0358c7a5a4f96 100644
--- a/content/public/android/java/src/org/chromium/content/browser/SelectionPopupController.java
+++ b/content/public/android/java/src/org/chromium/content/browser/SelectionPopupController.java
@@ -54,7 +54,7 @@ import java.util.List;
*/
@TargetApi(Build.VERSION_CODES.M)
public class SelectionPopupController extends ActionModeCallbackHelper {
- private static final String TAG = "cr.SelectionPopCtlr"; // 20 char limit
+ private static final String TAG = "SelectionPopupCtlr"; // 20 char limit
/**
* Android Intent size limitations prevent sending over a megabyte of data. Limit
@@ -115,6 +115,16 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
// The client that processes textual selection, or null if none exists.
private SelectionClient mSelectionClient;
+ // The classificaton result of the selected text if the selection exists and
+ // ContextSelectionProvider was able to classify it, otherwise null.
+ private ContextSelectionProvider.Result mClassificationResult;
+
+ // The resource ID for Assist menu item.
+ private int mAssistMenuItemId;
+
+ // This variable is set to true when the classification request is in progress.
+ private boolean mPendingClassificationRequest;
+
/**
* Create {@link SelectionPopupController} instance.
* @param context Context for action mode.
@@ -145,6 +155,13 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
hideActionModeTemporarily(hideDuration);
}
};
+
+ mSelectionClient =
+ ContextSelectionClient.create(new ContextSelectionCallback(), window, webContents);
+
+ // TODO(timav): Use android.R.id.textAssist for the Assist item id once we switch to
+ // Android O SDK and remove |mAssistMenuItemId|.
+ mAssistMenuItemId = mContext.getResources().getIdentifier("textAssist", "id", "android");
}
/**
@@ -174,9 +191,9 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
return mActionMode != null;
}
- // True if action mode is not yet initialized or set to no-op mode.
- private boolean isEmpty() {
- return mCallback == EMPTY_CALLBACK;
+ // True if action mode is initialized to a working (not a no-op) mode.
+ private boolean isActionModeSupported() {
+ return mCallback != EMPTY_CALLBACK;
}
@Override
@@ -189,15 +206,19 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
*
* <p>Action mode in floating mode is tried first, and then falls back to
* a normal one.
- * @return {@code true} if the action mode started successfully or is already on.
+ * <p> If the action mode cannot be created the selection is cleared.
*/
- public boolean showActionMode() {
- if (isEmpty()) return false;
+ public void showActionModeOrClearOnFailure() {
+ if (!isActionModeSupported()) return;
- destroyActionModeAndKeepSelection();
+ // Just refresh the view if action mode already exists.
+ if (isActionModeValid()) {
+ invalidateActionMode();
+ return;
+ }
if (mView.getParent() != null) {
- // On ICS, startActionMode throws an NPE when getParent() is null.
+ // On ICS, startActionMode throws an NPE when getParent() is null.
assert mWebContents != null;
ActionMode actionMode = supportsFloatingActionMode()
? startFloatingActionMode()
@@ -209,7 +230,7 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
mActionMode = actionMode;
}
mUnselectAllOnDismiss = true;
- return isActionModeValid();
+ if (!isActionModeValid()) clearSelection();
}
@TargetApi(Build.VERSION_CODES.M)
@@ -284,6 +305,10 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
*/
@Override
public void finishActionMode() {
+ mPendingClassificationRequest = false;
+ mHidden = false;
+ mView.removeCallbacks(mRepeatingHideRunnable);
+
if (isActionModeValid()) {
mActionMode.finish();
@@ -293,9 +318,31 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
}
/**
+ * @see ActionMode#invalidate()
+ * Note that invalidation will also reset visibility state. The caller
+ * should account for this when making subsequent visibility updates.
+ */
+ private void invalidateActionMode() {
+ if (!isActionModeValid()) return;
+ if (mHidden) {
+ assert canHideActionMode();
+ mHidden = false;
+ unhideActionMode();
+ mPendingInvalidateContentRect = false;
+ }
+
+ // Try/catch necessary for framework bug, crbug.com/446717.
+ try {
+ mActionMode.invalidate();
+ } catch (NullPointerException e) {
+ Log.w(TAG, "Ignoring NPE from ActionMode.invalidate() as workaround for L", e);
+ }
+ }
+
+ /**
* @see ActionMode#invalidateContentRect()
*/
- public void invalidateContentRect() {
+ private void invalidateContentRect() {
if (supportsFloatingActionMode()) {
if (mHidden) {
mPendingInvalidateContentRect = true;
@@ -328,8 +375,7 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
mRepeatingHideRunnable.run();
} else {
mHidden = false;
- mView.removeCallbacks(mRepeatingHideRunnable);
- hideActionModeTemporarily(SHOW_DELAY_MS);
+ unhideActionMode();
if (mPendingInvalidateContentRect) {
mPendingInvalidateContentRect = false;
invalidateContentRect();
@@ -337,6 +383,12 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
}
}
+ private void unhideActionMode() {
+ mView.removeCallbacks(mRepeatingHideRunnable);
+ // To show the action mode that is being hidden call hide() again with a short delay.
+ hideActionModeTemporarily(SHOW_DELAY_MS);
+ }
+
/**
* @see ActionMode#hide(long)
*/
@@ -398,6 +450,7 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
private void createActionMenu(ActionMode mode, Menu menu) {
mNeedsPrepare = false;
initializeMenu(mContext, mode, menu);
+ updateAssistMenuItem(menu);
if (!isSelectionEditable() || !canPaste()) {
menu.removeItem(R.id.select_action_menu_paste);
@@ -440,6 +493,21 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
return clipMgr.hasPrimaryClip();
}
+ private void updateAssistMenuItem(Menu menu) {
+ // The assist menu item ID has to be equal to android.R.id.textAssist. Until we compile
+ // with Android O SDK where this ID is defined we replace the corresponding inflated
+ // item with an item with the proper ID.
+ // TODO(timav): Use android.R.id.textAssist for the Assist item id once we switch to
+ // Android O SDK and remove |mAssistMenuItemId|.
+ menu.removeItem(R.id.select_action_menu_assist);
+ if (mAssistMenuItemId == 0) return;
+
+ if (mClassificationResult != null && mClassificationResult.hasNamedAction()) {
+ menu.add(mAssistMenuItemId, mAssistMenuItemId, 1, mClassificationResult.label)
+ .setIcon(mClassificationResult.icon);
+ }
+ }
+
/**
* Intialize the menu items for processing text, if there is any.
*/
@@ -452,10 +520,12 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
PackageManager packageManager = mContext.getPackageManager();
List<ResolveInfo> supportedActivities =
packageManager.queryIntentActivities(createProcessTextIntent(), 0);
+ // Force text processing menu at the end.
+ final int order = 100;
for (int i = 0; i < supportedActivities.size(); i++) {
ResolveInfo resolveInfo = supportedActivities.get(i);
CharSequence label = resolveInfo.loadLabel(mContext.getPackageManager());
- menu.add(R.id.select_action_menu_text_processing_menus, Menu.NONE, i, label)
+ menu.add(R.id.select_action_menu_text_processing_menus, Menu.NONE, order + i, label)
.setIntent(createProcessTextIntentForResolveInfo(resolveInfo))
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
@@ -481,7 +551,10 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
int id = item.getItemId();
int groupId = item.getGroupId();
- if (id == R.id.select_action_menu_select_all) {
+ if (id == mAssistMenuItemId) {
+ doAssistAction();
+ mode.finish();
+ } else if (id == R.id.select_action_menu_select_all) {
selectAll();
} else if (id == R.id.select_action_menu_cut) {
cut();
@@ -540,11 +613,38 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
}
/**
+ * Perform an action that depends on the semantics of the selected text.
+ */
+ @VisibleForTesting
+ void doAssistAction() {
+ if (mClassificationResult == null || !mClassificationResult.hasNamedAction()) return;
+
+ assert mClassificationResult.onClickListener != null
+ || mClassificationResult.intent != null;
+
+ if (mClassificationResult.onClickListener != null) {
+ mClassificationResult.onClickListener.onClick(mView);
+ return;
+ }
+
+ if (mClassificationResult.intent != null) {
+ Context context = mWindowAndroid.getContext().get();
+ if (context == null) return;
+
+ context.startActivity(mClassificationResult.intent);
+ return;
+ }
+ }
+
+ /**
* Perform a select all action.
*/
@VisibleForTesting
void selectAll() {
mWebContents.selectAll();
+ mClassificationResult = null;
+ mNeedsPrepare = true;
+ invalidateActionMode();
// Even though the above statement logged a SelectAll user action, we want to
// track whether the focus was in an editable field, so log that too.
if (isSelectionEditable()) {
@@ -717,7 +817,7 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
void restoreSelectionPopupsIfNecessary() {
if (mHasSelection && !isActionModeValid()) {
- if (!showActionMode()) clearSelection();
+ showActionModeOrClearOnFailure();
}
}
@@ -734,7 +834,13 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
mSelectionRect.set(left, top, right, bottom);
mHasSelection = true;
mUnselectAllOnDismiss = true;
- if (!showActionMode()) clearSelection();
+ if (mSelectionClient != null && mSelectionClient.sendsSelectionPopupUpdates()) {
+ // Rely on |mSelectionClient| sending a classification request and the request
+ // always calling onClassified() callback.
+ mPendingClassificationRequest = true;
+ } else {
+ showActionModeOrClearOnFailure();
+ }
break;
case SelectionEventType.SELECTION_HANDLES_MOVED:
@@ -754,7 +860,13 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
break;
case SelectionEventType.SELECTION_HANDLE_DRAG_STOPPED:
- hideActionMode(false);
+ if (mSelectionClient != null && mSelectionClient.sendsSelectionPopupUpdates()) {
+ // Rely on |mSelectionClient| sending a classification request and the request
+ // always calling onClassified() callback.
+ mPendingClassificationRequest = true;
+ } else {
+ hideActionMode(false);
+ }
break;
case SelectionEventType.INSERTION_HANDLE_SHOWN:
@@ -815,8 +927,9 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
* end if applicable.
*/
void clearSelection() {
- if (mWebContents == null || isEmpty()) return;
+ if (mWebContents == null || !isActionModeSupported()) return;
mWebContents.collapseSelection();
+ mClassificationResult = null;
}
void onSelectionChanged(String text) {
@@ -829,6 +942,11 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
// The client that implements selection augmenting functionality, or null if none exists.
void setSelectionClient(SelectionClient selectionClient) {
mSelectionClient = selectionClient;
+
+ mClassificationResult = null;
+
+ assert !mPendingClassificationRequest;
+ assert !mHidden;
}
void onShowUnhandledTapUIIfNeeded(int x, int y) {
@@ -883,4 +1001,47 @@ public class SelectionPopupController extends ActionModeCallbackHelper {
return mContext.getPackageManager().queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY).size() > 0;
}
+
+ // The callback class that delivers result from a ContextSelectionClient.
+ private class ContextSelectionCallback implements ContextSelectionProvider.ResultCallback {
+ @Override
+ public void onClassified(ContextSelectionProvider.Result result) {
+ boolean pendingClassificationRequest = mPendingClassificationRequest;
+ mPendingClassificationRequest = false;
+
+ // If the selection does not exist any more, discard |result|.
+ if (!mHasSelection) {
+ assert !mHidden;
+ assert mClassificationResult == null;
+ return;
+ }
+
+ // Determine whether we need to recreate the menu in case we are doing invalidate().
+ final boolean hadOldResult =
+ mClassificationResult != null && mClassificationResult.hasNamedAction();
+ final boolean hasNewResult = result != null && result.hasNamedAction();
+
+ mClassificationResult = result;
+
+ // By the time this methos arrives the action mode might be finished or finished
+ // and recreated again. In both cases |pendingClassificationRequest == false|.
+ // Assume that if acton mode exists we need to invalidate in any case.
+ if (!pendingClassificationRequest && !isActionModeValid()) {
+ assert !mHidden;
+ return;
+ }
+
+ // Update the selection range if needed.
+ if (!(result.startAdjust == 0 && result.endAdjust == 0)) {
+ // This call causes SELECTION_HANDLES_MOVED event
+ mWebContents.adjustSelectionByCharacterOffset(result.startAdjust, result.endAdjust);
+ }
+
+ // For simplicity always recreate the menu if the new result exists.
+ mNeedsPrepare = hasNewResult || hadOldResult;
+
+ // Rely on this method to clear mHidden and unhide the action mode.
+ showActionModeOrClearOnFailure();
+ }
+ };
}

Powered by Google App Engine
This is Rietveld 408576698