basetexteditor.h 18.4 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2 3 4
**
** This file is part of Qt Creator
**
con's avatar
con committed
5
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
hjk's avatar
hjk committed
7
** Contact: Nokia Corporation (info@qt.nokia.com)
con's avatar
con committed
8
**
9
**
10
** GNU Lesser General Public License Usage
11
**
hjk's avatar
hjk committed
12 13 14 15 16 17
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21 22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23 24 25 26 27
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
con's avatar
con committed
28 29
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
con's avatar
con committed
30
**
31
**************************************************************************/
hjk's avatar
hjk committed
32

con's avatar
con committed
33 34 35
#ifndef BASETEXTEDITOR_H
#define BASETEXTEDITOR_H

36
#include "itexteditor.h"
37
#include "icompletioncollector.h"
con's avatar
con committed
38

39 40
#include <find/ifindsupport.h>

41 42
#include <coreplugin/editormanager/editormanager.h>

con's avatar
con committed
43 44 45 46
#include <QtGui/QPlainTextEdit>

QT_BEGIN_NAMESPACE
class QToolBar;
47
class QTimeLine;
con's avatar
con committed
48 49
QT_END_NAMESPACE

50 51
namespace Utils {
    class LineColumnLabel;
52
    class ChangeSet;
con's avatar
con committed
53 54 55
}

namespace TextEditor {
56
class TabSettings;
57 58
class RefactorOverlay;
struct RefactorMarker;
con's avatar
con committed
59 60 61

namespace Internal {
    class BaseTextEditorPrivate;
62
    class TextEditorOverlay;
63
    typedef QList<RefactorMarker> RefactorMarkers;
64
    typedef QString (QString::*TransformationMethod)() const;
con's avatar
con committed
65 66 67 68 69
}

class ITextMarkable;

class BaseTextDocument;
70
class BaseTextEditor;
con's avatar
con committed
71
class FontSettings;
72 73 74 75
class BehaviorSettings;
class CompletionSettings;
class DisplaySettings;
class StorageSettings;
76
class Indenter;
77
class AutoCompleter;
78
class ExtraEncodingSettings;
con's avatar
con committed
79

80 81 82 83 84 85 86
class TEXTEDITOR_EXPORT BaseTextEditorAnimator : public QObject
{
    Q_OBJECT

public:
    BaseTextEditorAnimator(QObject *parent);

87 88
    inline void setPosition(int position) { m_position = position; }
    inline int position() const { return m_position; }
89 90 91 92 93 94

    void setData(QFont f, QPalette pal, const QString &text);

    void draw(QPainter *p, const QPointF &pos);
    QRectF rect() const;

95 96
    inline qreal value() const { return m_value; }
    inline QPointF lastDrawPos() const { return m_lastDrawPos; }
97 98 99

    void finish();

mae's avatar
mae committed
100 101
    bool isRunning() const;

102
signals:
103
    void updateRequest(int position, QPointF lastPos, QRectF rect);
104 105 106 107 108 109 110 111 112


private slots:
    void step(qreal v);

private:
    QTimeLine *m_timeline;
    qreal m_value;
    int m_position;
113
    QPointF m_lastDrawPos;
114 115 116 117 118 119 120
    QFont m_font;
    QPalette m_palette;
    QString m_text;
    QSizeF m_size;
};


121
class TEXTEDITOR_EXPORT BaseTextEditorWidget : public QPlainTextEdit
con's avatar
con committed
122 123
{
    Q_OBJECT
mae's avatar
mae committed
124 125
    Q_PROPERTY(int verticalBlockSelectionFirstColumn READ verticalBlockSelectionFirstColumn)
    Q_PROPERTY(int verticalBlockSelectionLastColumn READ verticalBlockSelectionLastColumn)
con's avatar
con committed
126
public:
127 128
    BaseTextEditorWidget(QWidget *parent);
    ~BaseTextEditorWidget();
con's avatar
con committed
129

130
    static ITextEditor *openEditorAt(const QString &fileName, int line, int column = 0,
131 132
                                     const QString &editorId =  QString(),
                                     Core::EditorManager::OpenEditorFlags flags = Core::EditorManager::IgnoreNavigationHistory,
133
                                     bool *newEditor = 0);
con's avatar
con committed
134

135 136 137
    const Utils::ChangeSet &changeSet() const;
    void setChangeSet(const Utils::ChangeSet &changeSet);

con's avatar
con committed
138 139 140
    // EditorInterface
    Core::IFile * file();
    bool createNew(const QString &contents);
141
    virtual bool open(QString *errorString, const QString &fileName = QString());
con's avatar
con committed
142 143 144 145 146 147
    QByteArray saveState() const;
    bool restoreState(const QByteArray &state);
    QString displayName() const;

    // ITextEditor

148
    void gotoLine(int line, int column = 0);
con's avatar
con committed
149 150 151 152 153 154

    int position(
        ITextEditor::PositionOperation posOp = ITextEditor::Current
        , int at = -1) const;
    void convertPosition(int pos, int *line, int *column) const;

155
    BaseTextEditor *editor() const;
con's avatar
con committed
156 157 158 159 160 161 162 163
    ITextMarkable *markableInterface() const;

    QChar characterAt(int pos) const;

    void print(QPrinter *);

    void setSuggestedFileName(const QString &suggestedFileName);
    QString mimeType() const;
Erik Verbruggen's avatar
Erik Verbruggen committed
164
    virtual void setMimeType(const QString &mt);
con's avatar
con committed
165 166


167 168
    void appendStandardContextMenuActions(QMenu *menu);

con's avatar
con committed
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    // Works only in conjunction with a syntax highlighter that puts
    // parentheses into text block user data
    void setParenthesesMatchingEnabled(bool b);
    bool isParenthesesMatchingEnabled() const;

    void setHighlightCurrentLine(bool b);
    bool highlightCurrentLine() const;

    void setLineNumbersVisible(bool b);
    bool lineNumbersVisible() const;

    void setMarksVisible(bool b);
    bool marksVisible() const;

    void setRequestMarkEnabled(bool b);
    bool requestMarkEnabled() const;

    void setLineSeparatorsAllowed(bool b);
    bool lineSeparatorsAllowed() const;

189
    void updateCodeFoldingVisible();
con's avatar
con committed
190 191
    bool codeFoldingVisible() const;

192 193 194
    void setCodeFoldingSupported(bool b);
    bool codeFoldingSupported() const;

195 196 197
    void setMouseNavigationEnabled(bool b);
    bool mouseNavigationEnabled() const;

198 199 200
    void setScrollWheelZoomingEnabled(bool b);
    bool scrollWheelZoomingEnabled() const;

con's avatar
con committed
201 202 203 204 205 206
    void setRevisionsVisible(bool b);
    bool revisionsVisible() const;

    void setVisibleWrapColumn(int column);
    int visibleWrapColumn() const;

207 208 209
    int columnCount() const;
    int rowCount() const;

con's avatar
con committed
210 211 212 213 214 215 216 217
    void setActionHack(QObject *);
    QObject *actionHack() const;

    void setTextCodec(QTextCodec *codec);
    QTextCodec *textCodec() const;

    void setReadOnly(bool b);

218 219
    void setTextCursor(const QTextCursor &cursor);

mae's avatar
mae committed
220
    void insertCodeSnippet(const QTextCursor &cursor, const QString &snippet);
221

222 223
    void setBlockSelection(bool on);
    bool hasBlockSelection() const;
224

mae's avatar
mae committed
225 226
    int verticalBlockSelectionFirstColumn() const;
    int verticalBlockSelectionLastColumn() const;
227

228 229
    QRegion translatedLineRegion(int lineStart, int lineEnd) const;

230
    void setIndenter(Indenter *indenter);
231
    Indenter *indenter() const;
232

233 234 235
    void setAutoCompleter(AutoCompleter *autoCompleter);
    AutoCompleter *autoCompleter() const;

236 237
    QPoint toolTipPosition(const QTextCursor &c) const;

con's avatar
con committed
238 239 240
public slots:
    void setDisplayName(const QString &title);

mae's avatar
mae committed
241 242
    virtual void paste();
    virtual void cut();
con's avatar
con committed
243 244 245

    void zoomIn(int range = 1);
    void zoomOut(int range = 1);
mae's avatar
mae committed
246
    void zoomReset();
con's avatar
con committed
247

248
    void cutLine();
249
    void copyLine();
con's avatar
con committed
250
    void deleteLine();
mae's avatar
mae committed
251 252 253
    void unfoldAll();
    void fold();
    void unfold();
con's avatar
con committed
254 255
    void selectEncoding();

256 257 258 259 260
    void gotoBlockStart();
    void gotoBlockEnd();
    void gotoBlockStartWithSelection();
    void gotoBlockEndWithSelection();

mae's avatar
mae committed
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
    void gotoLineStart();
    void gotoLineStartWithSelection();
    void gotoLineEnd();
    void gotoLineEndWithSelection();
    void gotoNextLine();
    void gotoNextLineWithSelection();
    void gotoPreviousLine();
    void gotoPreviousLineWithSelection();
    void gotoPreviousCharacter();
    void gotoPreviousCharacterWithSelection();
    void gotoNextCharacter();
    void gotoNextCharacterWithSelection();
    void gotoPreviousWord();
    void gotoPreviousWordWithSelection();
    void gotoNextWord();
    void gotoNextWordWithSelection();
mae's avatar
mae committed
277 278 279 280
    void gotoPreviousWordCamelCase();
    void gotoPreviousWordCamelCaseWithSelection();
    void gotoNextWordCamelCase();
    void gotoNextWordCamelCaseWithSelection();
281

282 283 284
    void selectBlockUp();
    void selectBlockDown();

285 286 287
    void moveLineUp();
    void moveLineDown();

288 289 290
    void copyLineUp();
    void copyLineDown();

291
    void joinLines();
292

293 294 295
    void insertLineAbove();
    void insertLineBelow();

296 297 298
    void uppercaseSelection();
    void lowercaseSelection();

299 300
    void cleanWhitespace();

con's avatar
con committed
301 302 303 304 305 306 307 308 309 310 311
signals:
    void changed();

    // ITextEditor
    void contentsChanged();

protected:
    bool event(QEvent *e);
    void keyPressEvent(QKeyEvent *e);
    void wheelEvent(QWheelEvent *e);
    void changeEvent(QEvent *e);
312
    void focusInEvent(QFocusEvent *e);
mae's avatar
mae committed
313
    void focusOutEvent(QFocusEvent *e);
con's avatar
con committed
314

mae's avatar
mae committed
315 316
    void showEvent(QShowEvent *);

con's avatar
con committed
317 318 319 320 321
    // reimplemented to support block selection
    QMimeData *createMimeDataFromSelection() const;
    bool canInsertFromMimeData(const QMimeData *source) const;
    void insertFromMimeData(const QMimeData *source);

322 323
    static QString msgTextTooLarge(quint64 size);

324 325 326
private:
    void maybeSelectLine();

con's avatar
con committed
327
public:
328
    void duplicateFrom(BaseTextEditorWidget *editor);
329

con's avatar
con committed
330 331 332 333 334 335
protected:
    BaseTextDocument *baseTextDocument() const;
    void setBaseTextDocument(BaseTextDocument *doc);

    void setDefaultPath(const QString &defaultPath);

336
    virtual BaseTextEditor *createEditor() = 0;
con's avatar
con committed
337 338 339

private slots:
    void editorContentsChange(int position, int charsRemoved, int charsAdded);
mae's avatar
mae committed
340 341
    void documentAboutToBeReloaded();
    void documentReloaded();
342
    void highlightSearchResults(const QString &txt, Find::FindFlags findFlags);
mae's avatar
mae committed
343 344 345
    void setFindScope(const QTextCursor &start, const QTextCursor &end, int, int);
    bool inFindScope(const QTextCursor &cursor);
    bool inFindScope(int selectionStart, int selectionEnd);
con's avatar
con committed
346
    void currentEditorChanged(Core::IEditor *editor);
347
    void inSnippetMode(bool *active);
con's avatar
con committed
348 349 350 351

private:
    Internal::BaseTextEditorPrivate *d;
    friend class Internal::BaseTextEditorPrivate;
352
    friend class Internal::TextEditorOverlay;
353
    friend class RefactorOverlay;
con's avatar
con committed
354 355 356 357 358 359

public:
    QWidget *extraArea() const;
    virtual int extraAreaWidth(int *markWidthPtr = 0) const;
    virtual void extraAreaPaintEvent(QPaintEvent *);
    virtual void extraAreaLeaveEvent(QEvent *);
360
    virtual void extraAreaMouseEvent(QMouseEvent *);
con's avatar
con committed
361 362 363 364 365 366 367 368

    const TabSettings &tabSettings() const;
    const DisplaySettings &displaySettings() const;

    void markBlocksAsChanged(QList<int> blockNumbers);

    void ensureCursorVisible();

369 370 371 372 373
    enum ExtraSelectionKind {
        CurrentLineSelection,
        ParenthesesMatchingSelection,
        CodeWarningsSelection,
        CodeSemanticsSelection,
374
        UndefinedSymbolSelection,
Roberto Raggi's avatar
Roberto Raggi committed
375
        UnusedSymbolSelection,
hjk's avatar
hjk committed
376
        FakeVimSelection,
Roberto Raggi's avatar
Roberto Raggi committed
377
        OtherSelection,
378
        SnippetPlaceholderSelection,
Erik Verbruggen's avatar
Erik Verbruggen committed
379
        ObjCSelection,
380 381 382 383
        NExtraSelectionKinds
    };
    void setExtraSelections(ExtraSelectionKind kind, const QList<QTextEdit::ExtraSelection> &selections);
    QList<QTextEdit::ExtraSelection> extraSelections(ExtraSelectionKind kind) const;
384
    QString extraSelectionTooltip(int pos) const;
con's avatar
con committed
385

386 387 388

    void setRefactorMarkers(const Internal::RefactorMarkers &markers);
signals:
389
    void refactorMarkerClicked(const TextEditor::RefactorMarker &marker);
390 391 392

public:

393 394 395 396 397 398
    struct BlockRange
    {
        BlockRange() : first(0), last(-1) {}
        BlockRange(int first_position, int last_position)
          : first(first_position), last(last_position)
        {}
con's avatar
con committed
399 400 401 402 403 404
        int first;
        int last;
        inline bool isNull() const { return last < first; }
    };

    // the blocks list must be sorted
405
    void setIfdefedOutBlocks(const QList<BlockRange> &blocks);
con's avatar
con committed
406 407

public slots:
408
    virtual void format();
409
    virtual void rewrapParagraph();
410 411
    virtual void unCommentSelection();
    virtual void setFontSettings(const TextEditor::FontSettings &);
mae's avatar
mae committed
412
    void setFontSettingsIfVisible(const TextEditor::FontSettings &);
con's avatar
con committed
413 414
    virtual void setTabSettings(const TextEditor::TabSettings &);
    virtual void setDisplaySettings(const TextEditor::DisplaySettings &);
415
    virtual void setBehaviorSettings(const TextEditor::BehaviorSettings &);
416
    virtual void setStorageSettings(const TextEditor::StorageSettings &);
417
    virtual void setCompletionSettings(const TextEditor::CompletionSettings &);
418
    virtual void setExtraEncodingSettings(const TextEditor::ExtraEncodingSettings &);
con's avatar
con committed
419 420 421 422 423 424 425 426 427

protected:
    bool viewportEvent(QEvent *event);

    void resizeEvent(QResizeEvent *);
    void paintEvent(QPaintEvent *);
    void timerEvent(QTimerEvent *);
    void mouseMoveEvent(QMouseEvent *);
    void mousePressEvent(QMouseEvent *);
428 429 430
    void mouseReleaseEvent(QMouseEvent *);
    void leaveEvent(QEvent *);
    void keyReleaseEvent(QKeyEvent *);
con's avatar
con committed
431

432 433
    void dragEnterEvent(QDragEnterEvent *e);

434
public:
435
    void indentInsertedText(const QTextCursor &tc);
436 437
    void indent(QTextDocument *doc, const QTextCursor &cursor, QChar typedChar);
    void reindent(QTextDocument *doc, const QTextCursor &cursor);
con's avatar
con committed
438

439 440 441 442 443
    struct Link
    {
        Link(const QString &fileName = QString(),
             int line = 0,
             int column = 0)
444 445
            : begin(-1)
            , end(-1)
446 447 448 449 450 451
            , fileName(fileName)
            , line(line)
            , column(column)
        {}

        bool isValid() const
452
        { return begin != end; }
453

454
        bool operator==(const Link &other) const
455
        { return begin == other.begin && end == other.end; }
456

457 458
        int begin;           // Link position
        int end;           // Link end position
459 460 461 462 463 464

        QString fileName;  // Target file
        int line;          // Target line
        int column;        // Target column
    };

465
protected:
466 467 468 469 470 471 472 473 474 475
    /*!
       Reimplement this function to enable code navigation.

       \a resolveTarget is set to true when the target of the link is relevant
       (it isn't until the link is used).
     */
    virtual Link findLinkAt(const QTextCursor &, bool resolveTarget = true);

    /*!
       Reimplement this function if you want to customize the way a link is
Tobias Hunger's avatar
Tobias Hunger committed
476
       opened. Returns whether the link was opened successfully.
477 478 479
     */
    virtual bool openLink(const Link &link);

480 481
    void maybeClearSomeExtraSelections(const QTextCursor &cursor);

con's avatar
con committed
482 483 484 485 486 487 488 489
protected slots:
    virtual void slotUpdateExtraAreaWidth();
    virtual void slotModificationChanged(bool);
    virtual void slotUpdateRequest(const QRect &r, int dy);
    virtual void slotCursorPositionChanged();
    virtual void slotUpdateBlockNotify(const QTextBlock &);

signals:
mae's avatar
mae committed
490 491
    void requestFontZoom(int zoom);
    void requestZoomReset();
con's avatar
con committed
492 493 494
    void requestBlockUpdate(const QTextBlock &);

private:
495
    void maybeRequestAutoCompletion(const QChar &ch);
con's avatar
con committed
496 497 498
    void indentOrUnindent(bool doIndent);
    void handleHomeKey(bool anchor);
    void handleBackspaceKey();
499
    void moveLineUpDown(bool up);
500
    void copyLineUpDown(bool up);
501
    void saveCurrentCursorPositionForNavigation();
con's avatar
con committed
502
    void updateHighlights();
503
    void updateCurrentLineHighlight();
con's avatar
con committed
504

505 506 507 508 509
    void drawFoldingMarker(QPainter *painter, const QPalette &pal,
                           const QRect &rect,
                           bool expanded,
                           bool active,
                           bool hovered) const;
510

511 512 513 514 515
    void drawCollapsedBlockPopup(QPainter &painter,
                                 const QTextBlock &block,
                                 QPointF offset,
                                 const QRect &clip);

con's avatar
con committed
516
    void toggleBlockVisible(const QTextBlock &block);
mae's avatar
mae committed
517
    QRect foldBox();
con's avatar
con committed
518

mae's avatar
mae committed
519
    QTextBlock foldedBlockAt(const QPoint &pos, QRect *box = 0) const;
con's avatar
con committed
520

521
    void updateLink(QMouseEvent *e);
522 523
    void showLink(const Link &);
    void clearLink();
mae's avatar
mae committed
524

525 526
    void universalHelper(); // test function for development

527 528 529 530
    bool cursorMoveKeyEvent(QKeyEvent *e);
    bool camelCaseRight(QTextCursor &cursor, QTextCursor::MoveMode mode);
    bool camelCaseLeft(QTextCursor &cursor, QTextCursor::MoveMode mode);

531
    void transformSelection(Internal::TransformationMethod method);
532

con's avatar
con committed
533
private slots:
534 535 536
    // auto completion
    void _q_requestAutoCompletion();

mae's avatar
mae committed
537 538
    void handleBlockSelection(int diff_row, int diff_col);

539
    // parentheses matcher
con's avatar
con committed
540
    void _q_matchParentheses();
541
    void _q_highlightBlocks();
con's avatar
con committed
542
    void slotSelectionChanged();
543
    void _q_animateUpdate(int position, QPointF lastPos, QRectF rect);
544
    void doFoo();
con's avatar
con committed
545 546 547
};


548
class TEXTEDITOR_EXPORT BaseTextEditor : public ITextEditor
con's avatar
con committed
549 550
{
    Q_OBJECT
551

con's avatar
con committed
552
public:
553 554
    BaseTextEditor(BaseTextEditorWidget *editorWidget);
    ~BaseTextEditor();
con's avatar
con committed
555

556 557
    friend class BaseTextEditorWidget;
    BaseTextEditorWidget *editorWidget() const { return e; }
con's avatar
con committed
558 559

    // EditorInterface
560
    //QWidget *widget() { return e; }
561 562
    Core::IFile * file() { return e->file(); }
    bool createNew(const QString &contents) { return e->createNew(contents); }
563
    bool open(QString *errorString, const QString &fileName = QString()) { return e->open(errorString, fileName); }
564 565
    QString displayName() const { return e->displayName(); }
    void setDisplayName(const QString &title) { e->setDisplayName(title); emit changed(); }
con's avatar
con committed
566

567 568 569
    QByteArray saveState() const { return e->saveState(); }
    bool restoreState(const QByteArray &state) { return e->restoreState(state); }
    QWidget *toolBar();
con's avatar
con committed
570

571 572 573
    enum Side { Left, Right };
    void insertExtraToolBarWidget(Side side, QWidget *widget);

con's avatar
con committed
574 575 576 577
    // ITextEditor
    int find(const QString &string) const;
    int currentLine() const;
    int currentColumn() const;
578
    void gotoLine(int line, int column = 0) { e->gotoLine(line, column); }
579 580
    int columnCount() const;
    int rowCount() const;
con's avatar
con committed
581

582 583 584 585
    int position(PositionOperation posOp = Current, int at = -1) const
    { return e->position(posOp, at); }
    void convertPosition(int pos, int *line, int *column) const
    { e->convertPosition(pos, line, column); }
con's avatar
con committed
586 587 588 589 590 591 592 593 594 595 596 597
    QRect cursorRect(int pos = -1) const;

    QString contents() const;
    QString selectedText() const;
    QString textAt(int pos, int length) const;
    inline QChar characterAt(int pos) const { return e->characterAt(pos); }

    inline ITextMarkable *markableInterface() { return e->markableInterface(); }

    void setContextHelpId(const QString &id) { m_contextHelpId = id; }
    QString contextHelpId() const; // from IContext

598
    inline void setTextCodec(QTextCodec *codec, TextCodecReason = TextCodecOtherReason) { e->setTextCodec(codec); }
con's avatar
con committed
599 600 601
    inline QTextCodec *textCodec() const { return e->textCodec(); }


602
    // ITextEditor
con's avatar
con committed
603 604 605
    void remove(int length);
    void insert(const QString &string);
    void replace(int length, const QString &string);
606
    void setCursorPosition(int pos);
con's avatar
con committed
607 608 609 610 611 612
    void select(int toPos);

private slots:
    void updateCursorPosition();

private:
613
    BaseTextEditorWidget *e;
con's avatar
con committed
614 615
    mutable QString m_contextHelpId;
    QToolBar *m_toolBar;
616 617
    QWidget *m_stretchWidget;
    QAction *m_cursorPositionLabelAction;
618
    Utils::LineColumnLabel *m_cursorPositionLabel;
con's avatar
con committed
619 620 621 622
};

} // namespace TextEditor

623
Q_DECLARE_METATYPE(TextEditor::BaseTextEditorWidget::Link)
624

con's avatar
con committed
625
#endif // BASETEXTEDITOR_H