File: editor.cpp

package info (click to toggle)
khtml 5.54.0-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 18,940 kB
  • sloc: cpp: 206,281; java: 4,060; ansic: 2,829; perl: 2,313; yacc: 1,497; python: 339; sh: 141; xml: 37; makefile: 7
file content (617 lines) | stat: -rw-r--r-- 17,198 bytes parent folder | download
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
/* This file is part of the KDE project
 *
 * Copyright (C) 2004 Leo Savernik <l.savernik@aon.at>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include "editor.h"

#include "jsediting.h"
#include "htmlediting_impl.h"

#include "css/css_renderstyledeclarationimpl.h"
#include "css/css_valueimpl.h"
#include "xml/dom_selection.h"
#include "xml/dom_docimpl.h"
#include "xml/dom_elementimpl.h"
#include "xml/dom_textimpl.h"
#include "xml/dom2_rangeimpl.h"
#include "khtml_part.h"
#include "khtml_ext.h"
#include "khtmlpart_p.h"

#include <QStack>
#include <QKeyEvent>

#ifndef APPLE_CHANGES
#  ifdef assert
#    undef assert
#  endif
#  define assert(x) Q_ASSERT(x)
#endif

#define PREPARE_JSEDITOR_CALL(command, retval) \
    JSEditor *js = m_part->xmlDocImpl() ? m_part->xmlDocImpl()->jsEditor() : 0; \
    if (!js) return retval; \
    const CommandImp *imp = js->commandImp(command)

#define DEBUG_COMMANDS

using namespace WTF;

using namespace DOM;

using khtml::RenderStyleDeclarationImpl;
using khtml::EditCommandImpl;
using khtml::ApplyStyleCommandImpl;
using khtml::TypingCommandImpl;
using khtml::EditorContext;
using khtml::IndentOutdentCommandImpl;

// --------------------------------------------------------------------------

namespace DOM
{

static const int sMaxUndoSteps = 1000;

class EditorPrivate
{
public:
    void registerUndo(EditCommandImpl *cmd, bool clearRedoStack = true)
    {
        if (m_undo.count() >= sMaxUndoSteps) {
            m_undo.pop_front();
        }
        if (clearRedoStack) {
            m_redo.clear();
        }
        m_undo.push(cmd);
    }
    void registerRedo(EditCommandImpl *cmd)
    {
        if (m_redo.count() >= sMaxUndoSteps) {
            m_redo.pop_front();
        }
        m_redo.push(cmd);
    }
    RefPtr<EditCommandImpl> m_lastEditCommand;
    QStack<RefPtr<EditCommandImpl> > m_undo;
    QStack<RefPtr<EditCommandImpl> > m_redo;
};

}

// ==========================================================================

Editor::Editor(KHTMLPart *part)
    : d(new EditorPrivate), m_typingStyle(nullptr), m_part(part)
{
}

Editor::~Editor()
{
    if (m_typingStyle) {
        m_typingStyle->deref();
    }
    delete d;
}

bool Editor::execCommand(const DOMString &command, bool userInterface, const DOMString &value)
{
    PREPARE_JSEDITOR_CALL(command, false);
    return js->execCommand(imp, userInterface, value);
}

bool Editor::queryCommandEnabled(const DOMString &command)
{
    PREPARE_JSEDITOR_CALL(command, false);
    return js->queryCommandEnabled(imp);
}

bool Editor::queryCommandIndeterm(const DOMString &command)
{
    PREPARE_JSEDITOR_CALL(command, false);
    return js->queryCommandIndeterm(imp);
}

bool Editor::queryCommandState(const DOMString &command)
{
    PREPARE_JSEDITOR_CALL(command, false);
    return js->queryCommandState(imp);
}

bool Editor::queryCommandSupported(const DOMString &command)
{
    PREPARE_JSEDITOR_CALL(command, false);
    return js->queryCommandSupported(imp);
}

DOMString Editor::queryCommandValue(const DOMString &command)
{
    PREPARE_JSEDITOR_CALL(command, DOMString());
    return js->queryCommandValue(imp);
}

bool Editor::execCommand(EditorCommand command, bool userInterface, const DOMString &value)
{
    PREPARE_JSEDITOR_CALL(command, false);
    return js->execCommand(imp, userInterface, value);
}

bool Editor::queryCommandEnabled(EditorCommand command)
{
    PREPARE_JSEDITOR_CALL(command, false);
    return js->queryCommandEnabled(imp);
}

bool Editor::queryCommandIndeterm(EditorCommand command)
{
    PREPARE_JSEDITOR_CALL(command, false);
    return js->queryCommandIndeterm(imp);
}

bool Editor::queryCommandState(EditorCommand command)
{
    PREPARE_JSEDITOR_CALL(command, false);
    return js->queryCommandState(imp);
}

bool Editor::queryCommandSupported(EditorCommand command)
{
    PREPARE_JSEDITOR_CALL(command, false);
    return js->queryCommandSupported(imp);
}

DOMString Editor::queryCommandValue(EditorCommand command)
{
    PREPARE_JSEDITOR_CALL(command, DOMString());
    return js->queryCommandValue(imp);
}

void Editor::copy()
{
    static_cast<KHTMLPartBrowserExtension *>(m_part->browserExtension())->copy();
}

void Editor::cut()
{
    // ###
    static_cast<KHTMLPartBrowserExtension *>(m_part->browserExtension())->cut();
}

void Editor::paste()
{
    // ###
    // security?
    // static_cast<KHTMLPartBrowserExtension*>(m_part->browserExtension())->paste();
}

void Editor::print()
{
    static_cast<KHTMLPartBrowserExtension *>(m_part->browserExtension())->print();
}

bool Editor::canPaste() const
{
    // ###
    return false;
}

void Editor::redo()
{
    if (d->m_redo.isEmpty()) {
        return;
    }
    RefPtr<EditCommandImpl> e = d->m_redo.pop();
    e->reapply();
}

void Editor::undo()
{
    if (d->m_undo.isEmpty()) {
        return;
    }
    RefPtr<EditCommandImpl> e = d->m_undo.pop();
    e->unapply();
}

bool Editor::canRedo() const
{
    return !d->m_redo.isEmpty();
}

bool Editor::canUndo() const
{
    return !d->m_undo.isEmpty();
}

void Editor::applyStyle(CSSStyleDeclarationImpl *style)
{
    switch (m_part->caret().state()) {
    case Selection::NONE:
        // do nothing
        break;
    case Selection::CARET:
        // FIXME: This blows away all the other properties of the typing style.
        setTypingStyle(style);
        break;
    case Selection::RANGE:
        if (m_part->xmlDocImpl() && style) {
#ifdef DEBUG_COMMANDS
            // qCDebug(KHTML_LOG) << "[create ApplyStyleCommand]";
#endif
            // FIXME
            (new ApplyStyleCommandImpl(m_part->xmlDocImpl(), style))->apply();
        }
        break;
    }
}

static void updateState(CSSStyleDeclarationImpl *desiredStyle, CSSStyleDeclarationImpl *computedStyle, bool &atStart, Editor::TriState &state)
{
    QListIterator<CSSProperty *> it(*desiredStyle->values());
    while (it.hasNext()) {
        int propertyID = it.next()->id();
        DOMString desiredProperty = desiredStyle->getPropertyValue(propertyID);
        DOMString computedProperty = computedStyle->getPropertyValue(propertyID);
        Editor::TriState propertyState = strcasecmp(desiredProperty, computedProperty) == 0
                                         ? Editor::TrueTriState : Editor::FalseTriState;
        if (atStart) {
            state = propertyState;
            atStart = false;
        } else if (state != propertyState) {
            state = Editor::MixedTriState;
            break;
        }
    }
}

Editor::TriState Editor::selectionHasStyle(CSSStyleDeclarationImpl *style) const
{
    bool atStart = true;
    TriState state = FalseTriState;

    EditorContext *ctx = m_part->editorContext();
    if (ctx->m_selection.state() != Selection::RANGE) {
        NodeImpl *nodeToRemove;
        CSSStyleDeclarationImpl *selectionStyle = selectionComputedStyle(nodeToRemove);
        if (!selectionStyle) {
            return FalseTriState;
        }
        selectionStyle->ref();
        updateState(style, selectionStyle, atStart, state);
        selectionStyle->deref();
        if (nodeToRemove) {
            int exceptionCode = 0;
            nodeToRemove->remove(exceptionCode);
            assert(exceptionCode == 0);
        }
    } else {
        for (NodeImpl *node = ctx->m_selection.start().node(); node; node = node->traverseNextNode()) {
            if (node->isHTMLElement()) {
                CSSStyleDeclarationImpl *computedStyle = new RenderStyleDeclarationImpl(node);
                computedStyle->ref();
                updateState(style, computedStyle, atStart, state);
                computedStyle->deref();
                if (state == MixedTriState) {
                    break;
                }
            }
            if (node == ctx->m_selection.end().node()) {
                break;
            }
        }
    }

    return state;
}

bool Editor::selectionStartHasStyle(CSSStyleDeclarationImpl *style) const
{
    NodeImpl *nodeToRemove;
    CSSStyleDeclarationImpl *selectionStyle = selectionComputedStyle(nodeToRemove);
    if (!selectionStyle) {
        return false;
    }

    selectionStyle->ref();

    bool match = true;

    QListIterator<CSSProperty *> it(*style->values());
    while (it.hasNext()) {
        int propertyID = it.next()->id();
        DOMString desiredProperty = style->getPropertyValue(propertyID);
        DOMString selectionProperty = selectionStyle->getPropertyValue(propertyID);
        if (strcasecmp(selectionProperty, desiredProperty) != 0) {
            match = false;
            break;
        }
    }

    selectionStyle->deref();

    if (nodeToRemove) {
        int exceptionCode = 0;
        nodeToRemove->remove(exceptionCode);
        assert(exceptionCode == 0);
    }

    return match;
}

DOMString Editor::selectionStartStylePropertyValue(int stylePropertyID) const
{
    NodeImpl *nodeToRemove;
    CSSStyleDeclarationImpl *selectionStyle = selectionComputedStyle(nodeToRemove);
    if (!selectionStyle) {
        return DOMString();
    }

    selectionStyle->ref();
    DOMString value = selectionStyle->getPropertyValue(stylePropertyID);
    selectionStyle->deref();

    if (nodeToRemove) {
        int exceptionCode = 0;
        nodeToRemove->remove(exceptionCode);
        assert(exceptionCode == 0);
    }

    return value;
}

CSSStyleDeclarationImpl *Editor::selectionComputedStyle(NodeImpl *&nodeToRemove) const
{
    nodeToRemove = nullptr;

    if (!m_part->xmlDocImpl()) {
        return nullptr;
    }

    EditorContext *ctx = m_part->editorContext();
    if (ctx->m_selection.state() == Selection::NONE) {
        return nullptr;
    }

    Range range(ctx->m_selection.toRange());
    Position pos(range.startContainer().handle(), range.startOffset());
    assert(pos.notEmpty());
    ElementImpl *elem = pos.element();
    ElementImpl *styleElement = elem;
    int exceptionCode = 0;

    if (m_typingStyle) {
        styleElement = m_part->xmlDocImpl()->createHTMLElement("SPAN");
//     assert(exceptionCode == 0);

        styleElement->setAttribute(ATTR_STYLE, m_typingStyle->cssText().implementation());
//     assert(exceptionCode == 0);

        TextImpl *text = m_part->xmlDocImpl()->createEditingTextNode("");
        styleElement->appendChild(text, exceptionCode);
        assert(exceptionCode == 0);

        elem->appendChild(styleElement, exceptionCode);
        assert(exceptionCode == 0);

        nodeToRemove = styleElement;
    }

    return new RenderStyleDeclarationImpl(styleElement);
}

PassRefPtr<EditCommandImpl> Editor::lastEditCommand() const
{
    return d->m_lastEditCommand;
}

void Editor::appliedEditing(EditCommandImpl *cmd)
{
#ifdef DEBUG_COMMANDS
    // qCDebug(KHTML_LOG) << "[Applied editing]";
#endif
    // make sure we have all the changes in rendering tree applied with relayout if needed before setting caret
    // in particular that could be required for inline boxes recomputation when inserting text
    m_part->xmlDocImpl()->updateLayout();

    m_part->setCaret(cmd->endingSelection(), false);
    // Command will be equal to last edit command only in the case of typing
    if (d->m_lastEditCommand == cmd) {
        assert(cmd->isTypingCommand());
    } else {
        // Only register a new undo command if the command passed in is
        // different from the last command
        d->registerUndo(cmd);
        d->m_lastEditCommand = cmd;
    }
    m_part->editorContext()->m_selection.setNeedsLayout(true);
    m_part->selectionLayoutChanged();
    // ### only emit if caret pos changed
    m_part->emitCaretPositionChanged(cmd->endingSelection().caretPos());
}

void Editor::unappliedEditing(EditCommandImpl *cmd)
{
    // see comment in appliedEditing()
    m_part->xmlDocImpl()->updateLayout();

    m_part->setCaret(cmd->startingSelection());
    d->registerRedo(cmd);
#ifdef APPLE_CHANGES
    KWQ(this)->respondToChangedContents();
#else
    m_part->editorContext()->m_selection.setNeedsLayout(true);
    m_part->selectionLayoutChanged();
    // ### only emit if caret pos changed
    m_part->emitCaretPositionChanged(cmd->startingSelection().caretPos());
#endif
    d->m_lastEditCommand = nullptr;
}

void Editor::reappliedEditing(EditCommandImpl *cmd)
{
    // see comment in appliedEditing()
    m_part->xmlDocImpl()->updateLayout();

    m_part->setCaret(cmd->endingSelection());
    d->registerUndo(cmd, false /*clearRedoStack*/);
#ifdef APPLE_CHANGES
    KWQ(this)->respondToChangedContents();
#else
    m_part->selectionLayoutChanged();
    // ### only emit if caret pos changed
    m_part->emitCaretPositionChanged(cmd->endingSelection().caretPos());
#endif
    d->m_lastEditCommand = nullptr;
}

CSSStyleDeclarationImpl *Editor::typingStyle() const
{
    return m_typingStyle;
}

void Editor::setTypingStyle(CSSStyleDeclarationImpl *style)
{
    CSSStyleDeclarationImpl *old = m_typingStyle;
    m_typingStyle = style;
    if (m_typingStyle) {
        m_typingStyle->ref();
    }
    if (old) {
        old->deref();
    }
}

void Editor::clearTypingStyle()
{
    setTypingStyle(nullptr);
}

void Editor::closeTyping()
{
    EditCommandImpl *lastCommand = lastEditCommand().get();
    if (lastCommand && lastCommand->isTypingCommand()) {
        static_cast<TypingCommandImpl *>(lastCommand)->closeTyping();
    }
}

void Editor::indent()
{
    RefPtr<IndentOutdentCommandImpl> command = new IndentOutdentCommandImpl(m_part->xmlDocImpl(),
            IndentOutdentCommandImpl::Indent);
    command->apply();
}

void Editor::outdent()
{
    RefPtr<IndentOutdentCommandImpl> command = new IndentOutdentCommandImpl(m_part->xmlDocImpl(),
            IndentOutdentCommandImpl::Outdent);
    command->apply();
}

bool Editor::handleKeyEvent(QKeyEvent *_ke)
{
    bool handled = false;

    bool ctrl  = _ke->modifiers() & Qt::ControlModifier;
    bool alt   = _ke->modifiers() & Qt::AltModifier;
    //bool shift = _ke->modifiers() & Qt::ShiftModifier;
    bool meta  = _ke->modifiers() & Qt::MetaModifier;

    if (ctrl || alt || meta) {
        return false;
    }

    switch (_ke->key()) {

    case Qt::Key_Delete: {
        Selection selectionToDelete = m_part->caret();
#ifdef DEBUG_COMMANDS
        // qCDebug(KHTML_LOG) << "========== KEY_DELETE ==========";
#endif
        if (selectionToDelete.state() == Selection::CARET) {
            Position pos(selectionToDelete.start());
#ifdef DEBUG_COMMANDS
            // qCDebug(KHTML_LOG) << "pos.inLastEditableInRootEditableElement " << pos.inLastEditableInRootEditableElement() << " pos.offset " << pos.offset() << " pos.max " << pos.node()->caretMaxRenderedOffset();
#endif
            if (pos.nextCharacterPosition() == pos) {
                // we're at the end of a root editable block...do nothing
#ifdef DEBUG_COMMANDS
                // qCDebug(KHTML_LOG) << "no delete!!!!!!!!!!";
#endif
                break;
            }
            m_part->d->editor_context.m_selection
                = Selection(pos, pos.nextCharacterPosition());
        }
        // fall through
    }
    case Qt::Key_Backspace:
        TypingCommandImpl::deleteKeyPressed0(m_part->xmlDocImpl());
        handled = true;
        break;

    case Qt::Key_Return:
    case Qt::Key_Enter:
//       if (shift)
        TypingCommandImpl::insertNewline0(m_part->xmlDocImpl());
//       else
//         TypingCommand::insertParagraph(m_part->xmlDocImpl());
        handled = true;
        break;

    case Qt::Key_Escape:
    case Qt::Key_Insert:
        // FIXME implement me
        handled = true;
        break;

    default:
// handle_input:
        if (m_part->caret().state() != Selection::CARET) {
            // We didn't get a chance to grab the caret, likely because
            // a script messed with contentEditable in the middle of events
            // acquire it now if there isn't a selection
            // qCDebug(KHTML_LOG) << "Editable node w/o caret!";
            DOM::NodeImpl *focus = m_part->xmlDocImpl()->focusNode();
            if (m_part->caret().state() == Selection::NONE) {
                if (focus) {
                    m_part->setCaret(Position(focus, focus->caretMinOffset()));
                } else {
                    break;
                }
            }
        }

        if (!_ke->text().isEmpty()) {
            TypingCommandImpl::insertText0(m_part->xmlDocImpl(), _ke->text());
            handled = true;
        }

    }

    //if (handled) {
    // ### check when to emit it
//     m_part->emitSelectionChanged();
    //}

    return handled;

}