@Override public boolean setInputConnectionHandler(Handler handler) { if (handler == mIcPostHandler) { return true; } if (!mFocused) { return false; } if (DEBUG) { assertOnIcThread(); } // There are three threads at this point: Gecko thread, old IC thread, and new IC // thread, and we want to safely switch from old IC thread to new IC thread. // We first send a TYPE_SET_HANDLER action to the Gecko thread; this ensures that // the Gecko thread is stopped at a known point. At the same time, the old IC // thread blocks on the action; this ensures that the old IC thread is stopped at // a known point. Finally, inside the Gecko thread, we post a Runnable to the old // IC thread; this Runnable switches from old IC thread to new IC thread. We // switch IC thread on the old IC thread to ensure any pending Runnables on the // old IC thread are processed before we switch over. Inside the Gecko thread, we // also post a Runnable to the new IC thread; this Runnable blocks until the // switch is complete; this ensures that the new IC thread won't accept // InputConnection calls until after the switch. mActionQueue.offer(Action.newSetHandler(handler)); mActionQueue.syncWithGecko(); return true; }
public void actionPerformed(ActionEvent e) { boolean isOffline = !Main.pref.getBoolean(ConfigKeys.OSB_API_OFFLINE); // inform the dialog about the connection mode dialog.setConnectionMode(isOffline); // set the new value in the preferences Main.pref.put(ConfigKeys.OSB_API_OFFLINE, isOffline); // toggle the tooltip text if (e.getSource() != null && e.getSource() instanceof JToggleButton) { JToggleButton button = (JToggleButton) e.getSource(); if (isOffline) { button.setToolTipText(MSG_ONLINE); if (Main.pref.getBoolean(ConfigKeys.OSB_BUTTON_LABELS)) { button.setText(MSG_ONLINE); } } else { button.setToolTipText(MSG_OFFLINE); if (Main.pref.getBoolean(ConfigKeys.OSB_BUTTON_LABELS)) { button.setText(MSG_OFFLINE); } } } if (!isOffline) { if (actionQueue.getSize() == 0) { dialog.hideQueuePanel(); return; } // if we switch to online mode, ask if the queue should be processed int result = JOptionPane.showConfirmDialog( Main.parent, tr("You have unsaved changes in your queue. Do you want to submit them now?"), tr("OpenStreetBugs"), JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { try { actionQueue.processQueue(); // toggle queue panel visibility, if now error occurred dialog.hideQueuePanel(); // refresh, if the api is enabled if (!Main.pref.getBoolean(ConfigKeys.OSB_API_DISABLED)) { plugin.updateData(); } } catch (Exception e1) { System.err.println("Couldn't process action queue"); e1.printStackTrace(); } } } else { dialog.showQueuePanel(); } }
private void geckoActionReply() { if (DEBUG) { // GeckoEditableListener methods should all be called from the Gecko thread ThreadUtils.assertOnGeckoThread(); } final Action action = mActionQueue.peek(); if (action == null) { throw new IllegalStateException("empty actions queue"); } if (DEBUG) { Log.d(LOGTAG, "reply: Action(" + getConstantName(Action.class, "TYPE_", action.mType) + ")"); } switch (action.mType) { case Action.TYPE_SET_SELECTION: final int len = mText.length(); final int curStart = Selection.getSelectionStart(mText); final int curEnd = Selection.getSelectionEnd(mText); // start == -1 when the start offset should remain the same // end == -1 when the end offset should remain the same final int selStart = Math.min(action.mStart < 0 ? curStart : action.mStart, len); final int selEnd = Math.min(action.mEnd < 0 ? curEnd : action.mEnd, len); if (selStart < action.mStart || selEnd < action.mEnd) { Log.w(LOGTAG, "IME sync error: selection out of bounds"); } Selection.setSelection(mText, selStart, selEnd); geckoPostToIc( new Runnable() { @Override public void run() { mActionQueue.syncWithGecko(); final int start = Selection.getSelectionStart(mText); final int end = Selection.getSelectionEnd(mText); if (selStart == start && selEnd == end) { // There has not been another new selection in the mean time that // made this notification out-of-date mListener.onSelectionChange(start, end); } } }); break; case Action.TYPE_SET_SPAN: mText.setSpan(action.mSpanObject, action.mStart, action.mEnd, action.mSpanFlags); break; case Action.TYPE_REMOVE_SPAN: mText.removeSpan(action.mSpanObject); break; case Action.TYPE_SET_HANDLER: geckoSetIcHandler(action.mHandler); break; } if (action.mShouldUpdate) { geckoUpdateGecko(false); } }
@Override public Editable replace(int st, int en, CharSequence source, int start, int end) { CharSequence text = source; if (start < 0 || start > end || end > text.length()) { Log.e( LOGTAG, "invalid replace offsets: " + start + " to " + end + ", length: " + text.length()); throw new IllegalArgumentException("invalid replace offsets"); } if (start != 0 || end != text.length()) { text = text.subSequence(start, end); } if (mFilters != null) { // Filter text before sending the request to Gecko for (int i = 0; i < mFilters.length; ++i) { final CharSequence cs = mFilters[i].filter(text, 0, text.length(), mProxy, st, en); if (cs != null) { text = cs; } } } if (text == source) { // Always create a copy text = new SpannableString(source); } mActionQueue.offer(Action.newReplaceText(text, Math.min(st, en), Math.max(st, en))); return mProxy; }
@Override public void setSpan(Object what, int start, int end, int flags) { if (what == Selection.SELECTION_START) { if ((flags & Spanned.SPAN_INTERMEDIATE) != 0) { // We will get the end offset next, just save the start for now mSavedSelectionStart = start; } else { mActionQueue.offer(Action.newSetSelection(start, -1)); } } else if (what == Selection.SELECTION_END) { mActionQueue.offer(Action.newSetSelection(mSavedSelectionStart, end)); mSavedSelectionStart = -1; } else { mActionQueue.offer(Action.newSetSpan(what, start, end, flags)); } }
@Override public void removeSpan(Object what) { if (what == Selection.SELECTION_START || what == Selection.SELECTION_END) { Log.w(LOGTAG, "selection removed with removeSpan()"); } mActionQueue.offer(Action.newRemoveSpan(what)); }
@WrapForJNI @Override public void onSelectionChange(final int start, final int end) { if (DEBUG) { // GeckoEditableListener methods should all be called from the Gecko thread ThreadUtils.assertOnGeckoThread(); Log.d(LOGTAG, "onSelectionChange(" + start + ", " + end + ")"); } if (start < 0 || start > mText.length() || end < 0 || end > mText.length()) { Log.e( LOGTAG, "invalid selection notification range: " + start + " to " + end + ", length: " + mText.length()); throw new IllegalArgumentException("invalid selection notification range"); } final int seqnoWhenPosted = ++mGeckoUpdateSeqno; /* An event (keypress, etc.) has potentially changed the selection, synchronize the selection here. There is not a race with the IC thread because the IC thread should be blocked on the event action */ final Action action = mActionQueue.peek(); if (action != null && action.mType == Action.TYPE_EVENT) { Selection.setSelection(mText, start, end); return; } geckoPostToIc( new Runnable() { @Override public void run() { mActionQueue.syncWithGecko(); /* check to see there has not been another action that potentially changed the selection. If so, we can skip this update because we know there is another update right after this one that will replace the effect of this update */ if (mGeckoUpdateSeqno == seqnoWhenPosted) { /* In this case, Gecko's selection has changed and it's notifying us to change Java's selection. In the normal case, whenever Java's selection changes, we go back and set Gecko's selection as well. However, in this case, since Gecko's selection is already up-to-date, we skip this step. */ boolean oldUpdateGecko = mUpdateGecko; mUpdateGecko = false; Selection.setSelection(mProxy, start, end); mUpdateGecko = oldUpdateGecko; } } }); }
@Override public void sendKeyEvent(final KeyEvent event, int action, int metaState) { if (DEBUG) { assertOnIcThread(); Log.d(LOGTAG, "sendKeyEvent(" + event + ", " + action + ", " + metaState + ")"); } /* We are actually sending two events to Gecko here, 1. Event from the event parameter (key event) 2. Sync event from the mActionQueue.offer call The first event is a normal event that does not reply back to us, the second sync event will have a reply, during which we see that there is a pending event-type action, and update the selection/composition/etc. accordingly. */ onKeyEvent(event, action, metaState, /* isSynthesizedImeKey */ false); mActionQueue.offer(new Action(Action.TYPE_EVENT)); }
@WrapForJNI @Override public void notifyIME(final int type) { if (DEBUG) { // GeckoEditableListener methods should all be called from the Gecko thread ThreadUtils.assertOnGeckoThread(); // NOTIFY_IME_REPLY_EVENT is logged separately, inside geckoActionReply() if (type != NOTIFY_IME_REPLY_EVENT) { Log.d( LOGTAG, "notifyIME(" + getConstantName(GeckoEditableListener.class, "NOTIFY_IME_", type) + ")"); } } if (type == NOTIFY_IME_REPLY_EVENT) { try { if (mGeckoFocused) { // When mGeckoFocused is false, the reply is for a stale action, // and we should not do anything geckoActionReply(); } else if (DEBUG) { Log.d(LOGTAG, "discarding stale reply"); } } finally { // Ensure action is always removed from queue // even if stale action results in exception in geckoActionReply mActionQueue.poll(); } return; } else if (type == NOTIFY_IME_TO_COMMIT_COMPOSITION) { notifyCommitComposition(); return; } else if (type == NOTIFY_IME_TO_CANCEL_COMPOSITION) { notifyCancelComposition(); return; } geckoPostToIc( new Runnable() { @Override public void run() { if (type == NOTIFY_IME_OF_FOCUS) { mFocused = true; // Unmask events on the Gecko side mActionQueue.offer(new Action(Action.TYPE_ACKNOWLEDGE_FOCUS)); } // Make sure there are no other things going on. If we sent // Action.TYPE_ACKNOWLEDGE_FOCUS, this line also makes us // wait for Gecko to update us on the newly focused content mActionQueue.syncWithGecko(); mListener.notifyIME(type); // Unset mFocused after we call syncWithGecko because // syncWithGecko becomes a no-op when mFocused is false. if (type == NOTIFY_IME_OF_BLUR) { mFocused = false; } } }); // Register/unregister Gecko-side text selection listeners // and update the mGeckoFocused flag. if (type == NOTIFY_IME_OF_BLUR && mGeckoFocused) { // Check for focus here because Gecko may send us a blur before a focus in some // cases, and we don't want to unregister an event that was not registered. mGeckoFocused = false; mSuppressCompositions = false; EventDispatcher.getInstance() .unregisterGeckoThreadListener(this, "TextSelection:DraggingHandle"); } else if (type == NOTIFY_IME_OF_FOCUS) { mGeckoFocused = true; mSuppressCompositions = false; EventDispatcher.getInstance() .registerGeckoThreadListener(this, "TextSelection:DraggingHandle"); } }
private void icUpdateGecko(boolean force) { // Skip if receiving a repeated request, or // if suppressing compositions during text selection. if ((!force && mIcUpdateSeqno == mLastIcUpdateSeqno) || mSuppressCompositions) { if (DEBUG) { Log.d(LOGTAG, "icUpdateGecko() skipped"); } return; } mLastIcUpdateSeqno = mIcUpdateSeqno; mActionQueue.syncWithGecko(); if (DEBUG) { Log.d(LOGTAG, "icUpdateGecko()"); } final int selStart = mText.getSpanStart(Selection.SELECTION_START); final int selEnd = mText.getSpanEnd(Selection.SELECTION_END); int composingStart = mText.length(); int composingEnd = 0; Object[] spans = mText.getSpans(0, composingStart, Object.class); for (Object span : spans) { if ((mText.getSpanFlags(span) & Spanned.SPAN_COMPOSING) != 0) { composingStart = Math.min(composingStart, mText.getSpanStart(span)); composingEnd = Math.max(composingEnd, mText.getSpanEnd(span)); } } if (DEBUG) { Log.d(LOGTAG, " range = " + composingStart + "-" + composingEnd); Log.d(LOGTAG, " selection = " + selStart + "-" + selEnd); } if (composingStart >= composingEnd) { if (selStart >= 0 && selEnd >= 0) { onImeSetSelection(selStart, selEnd); } else { onImeRemoveComposition(); } return; } if (selEnd >= composingStart && selEnd <= composingEnd) { onImeAddCompositionRange( selEnd - composingStart, selEnd - composingStart, IME_RANGE_CARETPOSITION, 0, 0, false, 0, 0, 0); } int rangeStart = composingStart; TextPaint tp = new TextPaint(); TextPaint emptyTp = new TextPaint(); // set initial foreground color to 0, because we check for tp.getColor() == 0 // below to decide whether to pass a foreground color to Gecko emptyTp.setColor(0); do { int rangeType, rangeStyles = 0, rangeLineStyle = IME_RANGE_LINE_NONE; boolean rangeBoldLine = false; int rangeForeColor = 0, rangeBackColor = 0, rangeLineColor = 0; int rangeEnd = mText.nextSpanTransition(rangeStart, composingEnd, Object.class); if (selStart > rangeStart && selStart < rangeEnd) { rangeEnd = selStart; } else if (selEnd > rangeStart && selEnd < rangeEnd) { rangeEnd = selEnd; } CharacterStyle[] styleSpans = mText.getSpans(rangeStart, rangeEnd, CharacterStyle.class); if (DEBUG) { Log.d(LOGTAG, " found " + styleSpans.length + " spans @ " + rangeStart + "-" + rangeEnd); } if (styleSpans.length == 0) { rangeType = (selStart == rangeStart && selEnd == rangeEnd) ? IME_RANGE_SELECTEDRAWTEXT : IME_RANGE_RAWINPUT; } else { rangeType = (selStart == rangeStart && selEnd == rangeEnd) ? IME_RANGE_SELECTEDCONVERTEDTEXT : IME_RANGE_CONVERTEDTEXT; tp.set(emptyTp); for (CharacterStyle span : styleSpans) { span.updateDrawState(tp); } int tpUnderlineColor = 0; float tpUnderlineThickness = 0.0f; // These TextPaint fields only exist on Android ICS+ and are not in the SDK. if (Versions.feature14Plus) { tpUnderlineColor = (Integer) getField(tp, "underlineColor", 0); tpUnderlineThickness = (Float) getField(tp, "underlineThickness", 0.0f); } if (tpUnderlineColor != 0) { rangeStyles |= IME_RANGE_UNDERLINE | IME_RANGE_LINECOLOR; rangeLineColor = tpUnderlineColor; // Approximately translate underline thickness to what Gecko understands if (tpUnderlineThickness <= 0.5f) { rangeLineStyle = IME_RANGE_LINE_DOTTED; } else { rangeLineStyle = IME_RANGE_LINE_SOLID; if (tpUnderlineThickness >= 2.0f) { rangeBoldLine = true; } } } else if (tp.isUnderlineText()) { rangeStyles |= IME_RANGE_UNDERLINE; rangeLineStyle = IME_RANGE_LINE_SOLID; } if (tp.getColor() != 0) { rangeStyles |= IME_RANGE_FORECOLOR; rangeForeColor = tp.getColor(); } if (tp.bgColor != 0) { rangeStyles |= IME_RANGE_BACKCOLOR; rangeBackColor = tp.bgColor; } } onImeAddCompositionRange( rangeStart - composingStart, rangeEnd - composingStart, rangeType, rangeStyles, rangeLineStyle, rangeBoldLine, rangeForeColor, rangeBackColor, rangeLineColor); rangeStart = rangeEnd; if (DEBUG) { Log.d( LOGTAG, " added " + rangeType + " : " + Integer.toHexString(rangeStyles) + " : " + Integer.toHexString(rangeForeColor) + " : " + Integer.toHexString(rangeBackColor)); } } while (rangeStart < composingEnd); onImeUpdateComposition(composingStart, composingEnd); }
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object target; final Class<?> methodInterface = method.getDeclaringClass(); if (DEBUG) { // Editable methods should all be called from the IC thread assertOnIcThread(); } if (methodInterface == Editable.class || methodInterface == Appendable.class || methodInterface == Spannable.class) { // Method alters the Editable; route calls to our implementation target = this; } else { // Method queries the Editable; must sync with Gecko first // then call on the inner Editable itself mActionQueue.syncWithGecko(); target = mText; } Object ret; try { ret = method.invoke(target, args); } catch (InvocationTargetException e) { // Bug 817386 // Most likely Gecko has changed the text while GeckoInputConnection is // trying to access the text. If we pass through the exception here, Fennec // will crash due to a lack of exception handler. Log the exception and // return an empty value instead. if (!(e.getCause() instanceof IndexOutOfBoundsException)) { // Only handle IndexOutOfBoundsException for now, // as other exceptions might signal other bugs throw e; } Log.w(LOGTAG, "Exception in GeckoEditable." + method.getName(), e.getCause()); Class<?> retClass = method.getReturnType(); if (retClass == Character.TYPE) { ret = '\0'; } else if (retClass == Integer.TYPE) { ret = 0; } else if (retClass == String.class) { ret = ""; } else { ret = null; } } if (DEBUG) { StringBuilder log = new StringBuilder(method.getName()); log.append("("); if (args != null) { for (Object arg : args) { debugAppend(log, arg).append(", "); } if (args.length > 0) { log.setLength(log.length() - 2); } } if (method.getReturnType().equals(Void.TYPE)) { log.append(")"); } else { debugAppend(log.append(") = "), ret); } Log.d(LOGTAG, log.toString()); } return ret; }
@WrapForJNI @Override public void onTextChange( final CharSequence text, final int start, final int unboundedOldEnd, final int unboundedNewEnd) { if (DEBUG) { // GeckoEditableListener methods should all be called from the Gecko thread ThreadUtils.assertOnGeckoThread(); StringBuilder sb = new StringBuilder("onTextChange("); debugAppend(sb, text); sb.append(", ") .append(start) .append(", ") .append(unboundedOldEnd) .append(", ") .append(unboundedNewEnd) .append(")"); Log.d(LOGTAG, sb.toString()); } if (start < 0 || start > unboundedOldEnd) { Log.e(LOGTAG, "invalid text notification range: " + start + " to " + unboundedOldEnd); throw new IllegalArgumentException("invalid text notification range"); } /* For the "end" parameters, Gecko can pass in a large number to denote "end of the text". Fix that here */ final int oldEnd = unboundedOldEnd > mText.length() ? mText.length() : unboundedOldEnd; // new end should always match text if (start != 0 && unboundedNewEnd != (start + text.length())) { Log.e( LOGTAG, "newEnd does not match text: " + unboundedNewEnd + " vs " + (start + text.length())); throw new IllegalArgumentException("newEnd does not match text"); } final int newEnd = start + text.length(); final Action action = mActionQueue.peek(); /* Text changes affect the selection as well, and we may not receive another selection update as a result of selection notification masking on the Gecko side; therefore, in order to prevent previous stale selection notifications from occurring, we need to increment the seqno here as well */ ++mGeckoUpdateSeqno; if (action != null && action.mType == Action.TYPE_ACKNOWLEDGE_FOCUS) { // Simply replace the text for newly-focused editors. mText.replace(0, mText.length(), text); } else { mChangedText.clearSpans(); mChangedText.replace(0, mChangedText.length(), text); // Preserve as many spans as possible TextUtils.copySpansFrom( mText, start, Math.min(oldEnd, newEnd), Object.class, mChangedText, 0); if (action != null && (action.mType == Action.TYPE_REPLACE_TEXT || action.mType == Action.TYPE_COMPOSE_TEXT) && start <= action.mStart && action.mStart + action.mSequence.length() <= newEnd) { // actionNewEnd is the new end of the original replacement action final int actionNewEnd = action.mStart + action.mSequence.length(); int selStart = Selection.getSelectionStart(mText); int selEnd = Selection.getSelectionEnd(mText); // Replace old spans with new spans mChangedText.replace(action.mStart - start, actionNewEnd - start, action.mSequence); geckoReplaceText(start, oldEnd, mChangedText); // delete/insert above might have moved our selection to somewhere else // this happens when the Gecko text change covers a larger range than // the original replacement action. Fix selection here if (selStart >= start && selStart <= oldEnd) { selStart = selStart < action.mStart ? selStart : selStart < action.mEnd ? actionNewEnd : selStart + actionNewEnd - action.mEnd; mText.setSpan(Selection.SELECTION_START, selStart, selStart, Spanned.SPAN_POINT_POINT); } if (selEnd >= start && selEnd <= oldEnd) { selEnd = selEnd < action.mStart ? selEnd : selEnd < action.mEnd ? actionNewEnd : selEnd + actionNewEnd - action.mEnd; mText.setSpan(Selection.SELECTION_END, selEnd, selEnd, Spanned.SPAN_POINT_POINT); } } else { // Gecko side initiated the text change. if (isSameText(start, oldEnd, mChangedText)) { // Nothing to do because the text is the same. // This could happen when the composition is updated for example. return; } geckoReplaceText(start, oldEnd, mChangedText); } } geckoPostToIc( new Runnable() { @Override public void run() { mListener.onTextChange(text, start, oldEnd, newEnd); } }); }