summaryrefslogtreecommitdiffstats
path: root/src/plugins/platforms/cocoa/qnsview_complextext.mm
blob: c1e1364f3224fd5853f26ed299f7c5d698c98291 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
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
218
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
/****************************************************************************
**
** Copyright (C) 2021 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

// This file is included from qnsview.mm, and only used to organize the code

@implementation QNSView (ComplexText)

// ------------- Text insertion -------------

/*
    Inserts the given text, potentially replacing existing text.

    The text input management system calls this as a result of:

     - A normal key press, via [NSView interpretKeyEvents:] or
       [NSInputContext handleEvent:]

     - An input method finishing (confirming) composition

     - Pressing a key in the Keyboard Viewer panel

     - Confirming an inline input area (accent popup e.g.)

    \a replacementRange refers to the existing text to replace.
    Under normal circumstances this is {NSNotFound, 0}, and the
    implementation should replace either the existing marked text,
    the current selection, or just insert the text at the current
    cursor location.
*/
- (void)insertText:(id)text replacementRange:(NSRange)replacementRange
{
    qCDebug(lcQpaKeys).nospace() << "Inserting \"" << text << "\""
        << ", replacing range " << replacementRange;

    if (m_composingText.isEmpty()) {
        // The input method may have transformed the incoming key event
        // to text that doesn't match what the original key event would
        // have produced, for example when 'Pinyin - Simplified' does smart
        // replacement of quotes. If that's the case we can't rely on
        // handleKeyEvent for sending the text.
        auto *currentEvent = NSApp.currentEvent;
        NSString *eventText = currentEvent.type == NSEventTypeKeyDown
                           || currentEvent.type == NSEventTypeKeyUp
                                ? currentEvent.characters : nil;

        if ([text isEqualToString:eventText]) {
            // We do not send input method events for simple text input,
            // and instead let handleKeyEvent send the key event.
            qCDebug(lcQpaKeys) << "Ignoring text insertion for simple text";
            m_sendKeyEvent = true;
            return;
        }
    }

    QObject *focusObject = m_platformWindow->window()->focusObject();
    if (queryInputMethod(focusObject)) {
        QInputMethodEvent inputMethodEvent;

        const bool isAttributedString = [text isKindOfClass:NSAttributedString.class];
        QString commitString = QString::fromNSString(isAttributedString ? [text string] : text);

        // Ensure we have a valid replacement range
        replacementRange = [self sanitizeReplacementRange:replacementRange];

        // Qt's QInputMethodEvent has different semantics for the replacement
        // range than AppKit does, so we need to sanitize the range first.
        auto [replaceFrom, replaceLength] = [self inputMethodRangeForRange:replacementRange];

        if (replaceFrom == NSNotFound) {
            qCWarning(lcQpaKeys) << "Failed to compute valid replacement range for text insertion";
            inputMethodEvent.setCommitString(commitString);
        } else {
            qCDebug(lcQpaKeys) << "Replacing from" << replaceFrom << "with length" << replaceLength
                << "based on replacement range" << replacementRange;
            inputMethodEvent.setCommitString(commitString, replaceFrom, replaceLength);
        }

        QCoreApplication::sendEvent(focusObject, &inputMethodEvent);
    }

    m_composingText.clear();
    m_composingFocusObject = nullptr;
}

- (void)insertNewline:(id)sender
{
    Q_UNUSED(sender);

    // Depending on the input method, pressing enter may
    // result in simply dismissing the input method editor,
    // without confirming the composition. In other cases
    // it may confirm the composition as well. And in some
    // cases the IME will produce an explicit new line, which
    // brings us here.

    // Semantically, the input method has asked us to insert
    // a newline, and we should do so via an QInputMethodEvent,
    // either directly or via [self insertText:@"\r"]. This is
    // also how NSTextView handles the command. But, if we did,
    // we would bypass all the code in Qt (and clients) that
    // assume that pressing the return key results in a key
    // event, for example the QLineEdit::returnPressed logic.
    // To ensure that clients will still see the Qt::Key_Return
    // key event, we send it as a normal key event.

    // But, we can not fall back to handleKeyEvent for this,
    // as the original key event may have text that reflects
    // the combination of the inserted text and the newline,
    // e.g. "~\r". We have already inserted the composition,
    // so we need to follow up with a single newline event.

    KeyEvent newlineEvent(m_currentlyInterpretedKeyEvent ?
        m_currentlyInterpretedKeyEvent : NSApp.currentEvent);
    newlineEvent.type = QEvent::KeyPress;
    newlineEvent.key = Qt::Key_Return;
    newlineEvent.text = QLatin1Char(kReturnCharCode);
    newlineEvent.nativeVirtualKey = kVK_Return;
    qCDebug(lcQpaKeys) << "Inserting newline via" << newlineEvent;
    newlineEvent.sendWindowSystemEvent(m_platformWindow->window());
}

// ------------- Text composition -------------

/*
    Updates the composed text, potentially replacing existing text.

    The NSTextInputClient protocol refers to composed text as "marked",
    since it is "marked differently from the selection, using temporary
    attributes that affect only display, not layout or storage.""

    The concept maps to the preeditString of our QInputMethodEvent.

    \a selectedRange refers to the part of the marked text that
    is considered selected, for example when composing text with
    multiple clause segments (Hiragana - Kana e.g.).

    \a replacementRange refers to the existing text to replace.
    Under normal circumstances this is {NSNotFound, 0}, and the
    implementation should replace either the existing marked text,
    the current selection, or just insert the text at the current
    cursor location. But when initiating composition of existing
    committed text (Hiragana - Kana e.g.), the range will be valid.
*/
- (void)setMarkedText:(id)text selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange
{
    qCDebug(lcQpaKeys).nospace() << "Marking \"" << text << "\""
        << " with selected range " << selectedRange
        << ", replacing range " << replacementRange;

    const bool isAttributedString = [text isKindOfClass:NSAttributedString.class];
    QString preeditString = QString::fromNSString(isAttributedString ? [text string] : text);

    QList<QInputMethodEvent::Attribute> preeditAttributes;

    // The QInputMethodEvent::Cursor specifies that the length
    // determines whether the cursor is visible or not, but uses
    // logic opposite of that of native AppKit application, where
    // the cursor is visible if there's no selection, and hidden
    // if there's a selection. Instead of passing on the length
    // directly we need to inverse the logic.
    const bool showCursor = !selectedRange.length;
    preeditAttributes << QInputMethodEvent::Attribute(
        QInputMethodEvent::Cursor, selectedRange.location, showCursor);

    // QInputMethodEvent::Selection unfortunately doesn't apply to the
    // preedit text, and QInputMethodEvent::Cursor which does, doesn't
    // support setting a selection. Until we've introduced attributes
    // that allow us to propagate the preedit selection semantically
    // we resort to styling the selection via the TextFormat attribute,
    // so that the preedit selection is visible to the user.
    QTextCharFormat selectionFormat;
    auto *platformTheme = QGuiApplicationPrivate::platformTheme();
    auto *systemPalette = platformTheme->palette();
    selectionFormat.setBackground(systemPalette->color(QPalette::Highlight));
    preeditAttributes << QInputMethodEvent::Attribute(
        QInputMethodEvent::TextFormat,
        selectedRange.location, selectedRange.length,
        selectionFormat);

    int index = 0;
    int composingLength = preeditString.length();
    while (index < composingLength) {
        NSRange range = NSMakeRange(index, composingLength - index);

        static NSDictionary *defaultMarkedTextAttributes = []{
            NSTextView *textView = [[NSTextView new] autorelease];
            return [textView.markedTextAttributes retain];
        }();

        NSDictionary *attributes = isAttributedString
            ? [text attributesAtIndex:index longestEffectiveRange:&range inRange:range]
            : defaultMarkedTextAttributes;

        qCDebug(lcQpaKeys) << "Decorating range" << range << "based on" << attributes;
        QTextCharFormat format;

        if (NSNumber *underlineStyle = attributes[NSUnderlineStyleAttributeName]) {
            format.setFontUnderline(true);
            NSUnderlineStyle style = underlineStyle.integerValue;
            if (style & NSUnderlineStylePatternDot)
                format.setUnderlineStyle(QTextCharFormat::DotLine);
            else if (style & NSUnderlineStylePatternDash)
                format.setUnderlineStyle(QTextCharFormat::DashUnderline);
            else if (style & NSUnderlineStylePatternDashDot)
                format.setUnderlineStyle(QTextCharFormat::DashDotLine);
            if (style & NSUnderlineStylePatternDashDotDot)
                format.setUnderlineStyle(QTextCharFormat::DashDotDotLine);
            else
                format.setUnderlineStyle(QTextCharFormat::SingleUnderline);

            // Unfortunately QTextCharFormat::UnderlineStyle does not distinguish
            // between NSUnderlineStyle{Single,Thick,Double}, which is used by CJK
            // input methods to highlight the selected clause segments.
        }
        if (NSColor *underlineColor = attributes[NSUnderlineColorAttributeName])
            format.setUnderlineColor(qt_mac_toQColor(underlineColor));
        if (NSColor *foregroundColor = attributes[NSForegroundColorAttributeName])
            format.setForeground(qt_mac_toQColor(foregroundColor));
        if (NSColor *backgroundColor = attributes[NSBackgroundColorAttributeName])
            format.setBackground(qt_mac_toQColor(backgroundColor));

        if (format != QTextCharFormat()) {
            preeditAttributes << QInputMethodEvent::Attribute(
                QInputMethodEvent::TextFormat, range.location, range.length, format);
        }

        index = range.location + range.length;
    }

    // Ensure we have a valid replacement range
    replacementRange = [self sanitizeReplacementRange:replacementRange];

    // Qt's QInputMethodEvent has different semantics for the replacement
    // range than AppKit does, so we need to sanitize the range first.
    auto [replaceFrom, replaceLength] = [self inputMethodRangeForRange:replacementRange];

    // Update the composition, now that we've computed the replacement range
    m_composingText = preeditString;

    if (QObject *focusObject = m_platformWindow->window()->focusObject()) {
        m_composingFocusObject = focusObject;
        if (queryInputMethod(focusObject)) {
            QInputMethodEvent event(preeditString, preeditAttributes);
            if (replaceLength > 0) {
                // The input method may extend the preedit into already
                // committed text. If so, we need to replace existing text
                // by committing an empty string.
                qCDebug(lcQpaKeys) << "Replacing from" << replaceFrom << "with length"
                    << replaceLength << "based on replacement range" << replacementRange;
                event.setCommitString(QString(), replaceFrom, replaceLength);
            }
            QCoreApplication::sendEvent(focusObject, &event);
        }
    }
}

- (NSArray<NSString *> *)validAttributesForMarkedText
{
    return @[
        NSUnderlineColorAttributeName,
        NSUnderlineStyleAttributeName,
        NSForegroundColorAttributeName,
        NSBackgroundColorAttributeName
    ];
}

- (BOOL)hasMarkedText
{
    return !m_composingText.isEmpty();
}

/*
    Returns the range of marked text or {cursorPosition, 0} if there's none.

    This maps to the location and length of the current preedit (composited) string.

    The returned range measures from the start of the receiver’s text storage,
    that is, from 0 to the document length.
*/
- (NSRange)markedRange
{
    QObject *focusObject = m_platformWindow->window()->focusObject();
    if (auto queryResult = queryInputMethod(focusObject, Qt::ImAbsolutePosition)) {
        int absoluteCursorPosition = queryResult.value(Qt::ImAbsolutePosition).toInt();

        // The cursor position as reflected by Qt::ImAbsolutePosition is not
        // affected by the offset of the cursor in the preedit area. That means
        // that when composing text, the cursor position stays the same, at the
        // preedit insertion point, regardless of where the cursor is positioned within
        // the preedit string by the QInputMethodEvent::Cursor attribute. This means
        // we can use the cursor position to determine the range of the marked text.

        // The NSTextInputClient documentation says {NSNotFound, 0} should be returned if there
        // is no marked text, but in practice NSTextView seems to report {cursorPosition, 0},
        // so we do the same.
        return NSMakeRange(absoluteCursorPosition, m_composingText.length());
    } else {
        return {NSNotFound, 0};
    }
}

/*
    Confirms the marked (composed) text.

    The marked text is accepted as if it had been inserted normally,
    and the preedit string is cleared.

    If there is no marked text this method has no effect.
*/
- (void)unmarkText
{
    // FIXME: Match cancelComposingText in early exit and focus object handling

    qCDebug(lcQpaKeys) << "Unmarking" << m_composingText
        << "for focus object" << m_composingFocusObject;

    if (!m_composingText.isEmpty()) {
        QObject *focusObject = m_platformWindow->window()->focusObject();
        if (queryInputMethod(focusObject)) {
            QInputMethodEvent e;
            e.setCommitString(m_composingText);
            QCoreApplication::sendEvent(focusObject, &e);
        }
    }

    m_composingText.clear();
    m_composingFocusObject = nullptr;
}

/*
    Cancels composition.

    The marked text is discarded, and the preedit string is cleared.

    If there is no marked text this method has no effect.
*/
- (void)cancelComposingText
{
    if (m_composingText.isEmpty())
        return;

    qCDebug(lcQpaKeys) << "Canceling composition" << m_composingText
        << "for focus object" << m_composingFocusObject;

    if (queryInputMethod(m_composingFocusObject)) {
        QInputMethodEvent e;
        QCoreApplication::sendEvent(m_composingFocusObject, &e);
    }

    m_composingText.clear();
    m_composingFocusObject = nullptr;
}

// ------------- Key binding command handling -------------

- (void)doCommandBySelector:(SEL)selector
{
    // Note: if the selector cannot be invoked, then doCommandBySelector:
    // should not pass this message up the responder chain (nor should it
    // call super, as the NSResponder base class would in that case pass
    // the message up the responder chain, which we don't want). We will
    // pass the originating key event up the responder chain if applicable.

    qCDebug(lcQpaKeys) << "Trying to perform command" << selector;
    if (![self tryToPerform:selector with:self])
        m_sendKeyEvent = true;
}

// ------------- Various text properties -------------

/*
    Returns the range of selected text, or {cursorPosition, 0} if there's none.

    The returned range measures from the start of the receiver’s text storage,
    that is, from 0 to the document length.
*/
- (NSRange)selectedRange
{
    QObject *focusObject = m_platformWindow->window()->focusObject();
    if (auto queryResult = queryInputMethod(focusObject,
            Qt::ImCursorPosition | Qt::ImAbsolutePosition | Qt::ImAnchorPosition)) {

        // Unfortunately the Qt::InputMethodQuery values are all relative
        // to the start of the current editing block (paragraph), but we
        // need them in absolute values relative to the entire text.
        // Luckily we have one property, Qt::ImAbsolutePosition, that
        // we can use to compute the offset.
        int cursorPosition = queryResult.value(Qt::ImCursorPosition).toInt();
        int absoluteCursorPosition = queryResult.value(Qt::ImAbsolutePosition).toInt();
        int absoluteOffset = absoluteCursorPosition - cursorPosition;

        int anchorPosition = absoluteOffset + queryResult.value(Qt::ImAnchorPosition).toInt();
        int selectionStart = anchorPosition >= absoluteCursorPosition ? absoluteCursorPosition : anchorPosition;
        int selectionEnd = selectionStart == anchorPosition ? absoluteCursorPosition : anchorPosition;
        int selectionLength = selectionEnd - selectionStart;

        // Note: The cursor position as reflected by these properties are not
        // affected by the offset of the cursor in the preedit area. That means
        // that when composing text, the cursor position stays the same, at the
        // preedit insertion point, regardless of where the cursor is positioned within
        // the preedit string by the QInputMethodEvent::Cursor attribute.

        // The NSTextInputClient documentation says {NSNotFound, 0} should be returned if there is no
        // selection, but in practice NSTextView seems to report {cursorPosition, 0}, so we do the same.
        return NSMakeRange(selectionStart, selectionLength);
    } else {
        return {NSNotFound, 0};
    }
}

/*
    Returns an attributed string derived from the given range
    in the underlying focus object's text storage.

    Input methods may call this with a proposed range that is
    out of bounds. For example, the InkWell text input service
    may ask for the contents of the text input client that extends
    beyond the document's range. To remedy this we always compute
    the intersection between the proposed range and the available
    text.

    If the intersection is completely outside of the available text
    this method returns nil.
*/
- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)range actualRange:(NSRangePointer)actualRange
{
    QObject *focusObject = m_platformWindow->window()->focusObject();
    if (auto queryResult = queryInputMethod(focusObject,
            Qt::ImAbsolutePosition | Qt::ImTextBeforeCursor | Qt::ImTextAfterCursor)) {
        const int absoluteCursorPosition = queryResult.value(Qt::ImAbsolutePosition).toInt();
        const QString textBeforeCursor = queryResult.value(Qt::ImTextBeforeCursor).toString();
        const QString textAfterCursor = queryResult.value(Qt::ImTextAfterCursor).toString();

        // The documentation doesn't say whether the marked text should be included
        // in the available text, but observing NSTextView shows that this is the
        // case, so we follow suit.
        const QString availableText = textBeforeCursor + m_composingText + textAfterCursor;
        const NSRange availableRange = NSMakeRange(absoluteCursorPosition - textBeforeCursor.length(),
                                  availableText.length());

        const NSRange intersectedRange = NSIntersectionRange(range, availableRange);
        if (actualRange)
            *actualRange = intersectedRange;

        if (!intersectedRange.length)
            return nil;

        NSString *substring = QStringView(availableText).mid(
            intersectedRange.location - availableRange.location,
            intersectedRange.length).toNSString();

        return [[[NSAttributedString alloc] initWithString:substring] autorelease];

    } else {
        return nil;
    }
}

- (NSRect)firstRectForCharacterRange:(NSRange)range actualRange:(NSRangePointer)actualRange
{
    Q_UNUSED(range);
    Q_UNUSED(actualRange);

    QWindow *window = m_platformWindow->window();
    if (queryInputMethod(window->focusObject())) {
        QRect cursorRect = qApp->inputMethod()->cursorRectangle().toRect();
        cursorRect.moveBottomLeft(window->mapToGlobal(cursorRect.bottomLeft()));
        return QCocoaScreen::mapToNative(cursorRect);
    } else {
        return NSZeroRect;
    }
}

- (NSUInteger)characterIndexForPoint:(NSPoint)point
{
    // We don't support cursor movements using mouse while composing.
    Q_UNUSED(point);
    return NSNotFound;
}

// ------------- Helper functions -------------

/*
    Sanitizes the replacement range, ensuring it's valid.

    If \a range is not valid the range of the current
    marked text will be used.

    If there's no marked text the range of the current
    selection will be used.

    If there's no selection the range will be {cursorPosition, 0}.
*/
- (NSRange)sanitizeReplacementRange:(NSRange)range
{
    if (range.location != NSNotFound)
        return range; // Use as is

    // If the replacement range is not specified we are expected to compute
    // the range ourselves, based on the current state of the input context.

    const auto markedRange = [self markedRange];
    if (markedRange.location != NSNotFound)
        return markedRange;
    else
        return [self selectedRange];
}

/*
    Computes the QInputMethodEvent commit string range,
    based on the NSTextInputClient replacement range.

    The two APIs have different semantics.
*/
- (std::pair<long long, long long>)inputMethodRangeForRange:(NSRange)range
{
    long long replaceFrom = range.location;
    long long replaceLength = range.length;

    const auto markedRange = [self markedRange];
    const auto selectedRange = [self selectedRange];

    // The QInputMethodEvent replacement start is relative to the start
    // of the marked text (the location of the preedit string).
    if (markedRange.location != NSNotFound)
        replaceFrom -= markedRange.location;
    else
        replaceFrom = 0;

    // The replacement length of QInputMethodEvent already includes
    // the selection, as the documentation says that "If the widget
    // has selected text, the selected text should get removed."
    replaceLength -= selectedRange.length;

    // The replacement length of QInputMethodEvent already includes
    // the preedit string, as the documentation says that "When doing
    // replacement, the area of the preedit string is ignored".
    replaceLength -= markedRange.length;

    // What we're left with is any _additional_ replacement.
    // Make sure it's valid before passing it on.
    replaceLength = qMax(0ll, replaceLength);

    return {replaceFrom, replaceLength};
}

@end