CodePointInputMethod.java 15.3 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
15
 *   - Neither the name of Oracle nor the names of its
D
duke 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.sun.inputmethods.internal.codepointim;
32

D
duke 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

import java.awt.AWTEvent;
import java.awt.Toolkit;
import java.awt.Rectangle;
import java.awt.event.InputMethodEvent;
import java.awt.event.KeyEvent;
import java.awt.font.TextAttribute;
import java.awt.font.TextHitInfo;
import java.awt.im.InputMethodHighlight;
import java.awt.im.spi.InputMethod;
import java.awt.im.spi.InputMethodContext;
import java.io.IOException;
import java.text.AttributedString;
import java.util.Locale;

48

D
duke 已提交
49 50 51 52 53 54 55 56 57
/**
 * The Code Point Input Method is a simple input method that allows Unicode
 * characters to be entered using their code point or code unit values. See the
 * accompanying file README.txt for more information.
 *
 * @author Brian Beck
 */
public class CodePointInputMethod implements InputMethod {

58 59 60 61
    private static final int UNSET = 0;
    private static final int ESCAPE = 1; // \u0000       - \uFFFF
    private static final int SPECIAL_ESCAPE = 2; // \U000000     - \U10FFFF
    private static final int SURROGATE_PAIR = 3; // \uD800\uDC00 - \uDBFF\uDFFF
D
duke 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    private InputMethodContext context;
    private Locale locale;
    private StringBuffer buffer;
    private int insertionPoint;
    private int format = UNSET;

    public CodePointInputMethod() throws IOException {
    }

    /**
     * This is the input method's main routine.  The composed text is stored
     * in buffer.
     */
    public void dispatchEvent(AWTEvent event) {
        // This input method handles KeyEvent only.
        if (!(event instanceof KeyEvent)) {
            return;
        }

        KeyEvent e = (KeyEvent) event;
        int eventID = event.getID();
        boolean notInCompositionMode = buffer.length() == 0;

        if (eventID == KeyEvent.KEY_PRESSED) {
            // If we are not in composition mode, pass through
87
            if (notInCompositionMode) {
D
duke 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
                return;
            }

            switch (e.getKeyCode()) {
                case KeyEvent.VK_LEFT:
                    moveCaretLeft();
                    break;
                case KeyEvent.VK_RIGHT:
                    moveCaretRight();
                    break;
            }
        } else if (eventID == KeyEvent.KEY_TYPED) {
            char c = e.getKeyChar();

            // If we are not in composition mode, wait a back slash
103
            if (notInCompositionMode) {
D
duke 已提交
104 105 106 107 108 109 110 111
                // If the type character is not a back slash, pass through
                if (c != '\\') {
                    return;
                }

                startComposition();     // Enter to composition mode
            } else {
                switch (c) {
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
                    case ' ':       // Exit from composition mode
                        finishComposition();
                        break;
                    case '\u007f':  // Delete
                        deleteCharacter();
                        break;
                    case '\b':      // BackSpace
                        deletePreviousCharacter();
                        break;
                    case '\u001b':  // Escape
                        cancelComposition();
                        break;
                    case '\n':      // Return
                    case '\t':      // Tab
                        sendCommittedText();
                        break;
                    default:
                        composeUnicodeEscape(c);
                        break;
D
duke 已提交
131 132 133 134
                }
            }
        } else {  // KeyEvent.KEY_RELEASED
            // If we are not in composition mode, pass through
135
            if (notInCompositionMode) {
D
duke 已提交
136 137 138 139 140 141 142 143 144
                return;
            }
        }

        e.consume();
    }

    private void composeUnicodeEscape(char c) {
        switch (buffer.length()) {
145
            case 1:  // \\
D
duke 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
                waitEscapeCharacter(c);
                break;
            case 2:  // \\u or \\U
            case 3:  // \\ux or \\Ux
            case 4:  // \\uxx or \\Uxx
                waitDigit(c);
                break;
            case 5:  // \\uxxx or \\Uxxx
                if (format == SPECIAL_ESCAPE) {
                    waitDigit(c);
                } else {
                    waitDigit2(c);
                }
                break;
            case 6:  // \\uxxxx or \\Uxxxx
                if (format == SPECIAL_ESCAPE) {
                    waitDigit(c);
                } else if (format == SURROGATE_PAIR) {
                    waitBackSlashOrLowSurrogate(c);
                } else {
                    beep();
                }
                break;
            case 7:  // \\Uxxxxx
                // Only SPECIAL_ESCAPE format uses this state.
                // Since the second "\\u" of SURROGATE_PAIR format is inserted
                // automatically, users don't have to type these keys.
                waitDigit(c);
                break;
            case 8:  // \\uxxxx\\u
            case 9:  // \\uxxxx\\ux
            case 10: // \\uxxxx\\uxx
            case 11: // \\uxxxx\\uxxx
                if (format == SURROGATE_PAIR) {
                    waitDigit(c);
                } else {
                    beep();
                }
                break;
            default:
                beep();
                break;
        }
    }

    private void waitEscapeCharacter(char c) {
        if (c == 'u' || c == 'U') {
            buffer.append(c);
            insertionPoint++;
            sendComposedText();
            format = (c == 'u') ? ESCAPE : SPECIAL_ESCAPE;
        } else {
            if (c != '\\') {
                buffer.append(c);
                insertionPoint++;
            }
            sendCommittedText();
        }
    }

    private void waitDigit(char c) {
        if (Character.digit(c, 16) != -1) {
            buffer.insert(insertionPoint++, c);
            sendComposedText();
        } else {
            beep();
        }
    }

    private void waitDigit2(char c) {
        if (Character.digit(c, 16) != -1) {
            buffer.insert(insertionPoint++, c);
218
            char codePoint = (char) getCodePoint(buffer, 2, 5);
D
duke 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
            if (Character.isHighSurrogate(codePoint)) {
                format = SURROGATE_PAIR;
                buffer.append("\\u");
                insertionPoint = 8;
            } else {
                format = ESCAPE;
            }
            sendComposedText();
        } else {
            beep();
        }
    }

    private void waitBackSlashOrLowSurrogate(char c) {
        if (insertionPoint == 6) {
            if (c == '\\') {
                buffer.append(c);
                buffer.append('u');
                insertionPoint = 8;
                sendComposedText();
            } else if (Character.digit(c, 16) != -1) {
                buffer.append("\\u");
                buffer.append(c);
                insertionPoint = 9;
                sendComposedText();
            } else {
                beep();
            }
        } else {
            beep();
        }
    }

    /**
     * Send the composed text to the client.
     */
    private void sendComposedText() {
        AttributedString as = new AttributedString(buffer.toString());
        as.addAttribute(TextAttribute.INPUT_METHOD_HIGHLIGHT,
258
                InputMethodHighlight.SELECTED_RAW_TEXT_HIGHLIGHT);
D
duke 已提交
259
        context.dispatchInputMethodEvent(
260 261 262
                InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
                as.getIterator(), 0,
                TextHitInfo.leading(insertionPoint), null);
D
duke 已提交
263 264 265 266 267 268 269 270
    }

    /**
     * Send the committed text to the client.
     */
    private void sendCommittedText() {
        AttributedString as = new AttributedString(buffer.toString());
        context.dispatchInputMethodEvent(
271 272 273
                InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
                as.getIterator(), buffer.length(),
                TextHitInfo.leading(insertionPoint), null);
D
duke 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294

        buffer.setLength(0);
        insertionPoint = 0;
        format = UNSET;
    }

    /**
     * Move the insertion point one position to the left in the composed text.
     * Do not let the caret move to the left of the "\\u" or "\\U".
     */
    private void moveCaretLeft() {
        int len = buffer.length();
        if (--insertionPoint < 2) {
            insertionPoint++;
            beep();
        } else if (format == SURROGATE_PAIR && insertionPoint == 7) {
            insertionPoint = 8;
            beep();
        }

        context.dispatchInputMethodEvent(
295 296 297
                InputMethodEvent.CARET_POSITION_CHANGED,
                null, 0,
                TextHitInfo.leading(insertionPoint), null);
D
duke 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310
    }

    /**
     * Move the insertion point one position to the right in the composed text.
     */
    private void moveCaretRight() {
        int len = buffer.length();
        if (++insertionPoint > len) {
            insertionPoint = len;
            beep();
        }

        context.dispatchInputMethodEvent(
311 312 313
                InputMethodEvent.CARET_POSITION_CHANGED,
                null, 0,
                TextHitInfo.leading(insertionPoint), null);
D
duke 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
    }

    /**
     * Delete the character preceding the insertion point in the composed text.
     * If the insertion point is not at the end of the composed text and the
     * preceding text is "\\u" or "\\U", ring the bell.
     */
    private void deletePreviousCharacter() {
        if (insertionPoint == 2) {
            if (buffer.length() == 2) {
                cancelComposition();
            } else {
                // Do not allow deletion of the leading "\\u" or "\\U" if there
                // are other digits in the composed text.
                beep();
            }
        } else if (insertionPoint == 8) {
            if (buffer.length() == 8) {
                if (format == SURROGATE_PAIR) {
                    buffer.deleteCharAt(--insertionPoint);
                }
                buffer.deleteCharAt(--insertionPoint);
                sendComposedText();
            } else {
                // Do not allow deletion of the second "\\u" if there are other
                // digits in the composed text.
                beep();
            }
        } else {
            buffer.deleteCharAt(--insertionPoint);
            if (buffer.length() == 0) {
                sendCommittedText();
            } else {
                sendComposedText();
            }
        }
    }

    /**
     * Delete the character following the insertion point in the composed text.
     * If the insertion point is at the end of the composed text, ring the bell.
     */
    private void deleteCharacter() {
        if (insertionPoint < buffer.length()) {
            buffer.deleteCharAt(insertionPoint);
            sendComposedText();
        } else {
            beep();
        }
    }

    private void startComposition() {
        buffer.append('\\');
        insertionPoint = 1;
        sendComposedText();
    }

    private void cancelComposition() {
        buffer.setLength(0);
        insertionPoint = 0;
        sendCommittedText();
    }

    private void finishComposition() {
        int len = buffer.length();
        if (len == 6 && format != SPECIAL_ESCAPE) {
380
            char codePoint = (char) getCodePoint(buffer, 2, 5);
D
duke 已提交
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
            if (Character.isValidCodePoint(codePoint) && codePoint != 0xFFFF) {
                buffer.setLength(0);
                buffer.append(codePoint);
                sendCommittedText();
                return;
            }
        } else if (len == 8 && format == SPECIAL_ESCAPE) {
            int codePoint = getCodePoint(buffer, 2, 7);
            if (Character.isValidCodePoint(codePoint) && codePoint != 0xFFFF) {
                buffer.setLength(0);
                buffer.appendCodePoint(codePoint);
                sendCommittedText();
                return;
            }
        } else if (len == 12 && format == SURROGATE_PAIR) {
            char[] codePoint = {
397 398
                (char) getCodePoint(buffer, 2, 5),
                (char) getCodePoint(buffer, 8, 11)
D
duke 已提交
399
            };
400 401
            if (Character.isHighSurrogate(codePoint[0]) && Character.
                    isLowSurrogate(codePoint[1])) {
D
duke 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414
                buffer.setLength(0);
                buffer.append(codePoint);
                sendCommittedText();
                return;
            }
        }

        beep();
    }

    private int getCodePoint(StringBuffer sb, int from, int to) {
        int value = 0;
        for (int i = from; i <= to; i++) {
415
            value = (value << 4) + Character.digit(sb.charAt(i), 16);
D
duke 已提交
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
        }
        return value;
    }

    private static void beep() {
        Toolkit.getDefaultToolkit().beep();
    }

    public void activate() {
        if (buffer == null) {
            buffer = new StringBuffer(12);
            insertionPoint = 0;
        }
    }

    public void deactivate(boolean isTemporary) {
        if (!isTemporary) {
            buffer = null;
        }
    }

    public void dispose() {
    }

    public Object getControlObject() {
        return null;
    }

    public void endComposition() {
        sendCommittedText();
    }

    public Locale getLocale() {
        return locale;
    }

    public void hideWindows() {
    }

    public boolean isCompositionEnabled() {
        // always enabled
        return true;
    }

    public void notifyClientWindowChange(Rectangle location) {
    }

    public void reconvert() {
        // not supported yet
        throw new UnsupportedOperationException();
    }

    public void removeNotify() {
    }

    public void setCharacterSubsets(Character.Subset[] subsets) {
    }

    public void setCompositionEnabled(boolean enable) {
        // not supported yet
        throw new UnsupportedOperationException();
    }

    public void setInputMethodContext(InputMethodContext context) {
        this.context = context;
    }

    /*
     * The Code Point Input Method supports all locales.
     */
    public boolean setLocale(Locale locale) {
        this.locale = locale;
        return true;
    }
}