diff --git a/src/klineedit.cpp b/src/klineedit.cpp index f417902..88e3e92 100644 --- a/src/klineedit.cpp +++ b/src/klineedit.cpp @@ -1,1685 +1,1680 @@ /* This file is part of the KDE libraries Copyright (C) 1997 Sven Radej (sven.radej@iname.com) Copyright (c) 1999 Patrick Ward Copyright (c) 1999 Preston Brown Re-designed for KDE 2.x by Copyright (c) 2000, 2001 Dawit Alemayehu Copyright (c) 2000, 2001 Carsten Pfeiffer This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "klineedit.h" #include "klineedit_p.h" #include #include #include #include #include #include #include #include #include #include #include #include class KLineEditStyle; KLineEditPrivate::~KLineEditPrivate() { // causes a weird crash in KWord at least, so let Qt delete it for us. // delete completionBox; delete style.data(); } void KLineEditPrivate::_k_textChanged(const QString &text) { Q_Q(KLineEdit); // COMPAT (as documented): emit userTextChanged whenever textChanged is emitted // KDE5: remove userTextChanged signal, textEdited does the same... if (!completionRunning && (text != userText)) { userText = text; #ifndef KCOMPLETION_NO_DEPRECATED emit q->userTextChanged(text); #endif } } // Call this when a completion operation changes the lineedit text // "as if it had been edited by the user". void KLineEditPrivate::_k_updateUserText(const QString &text) { Q_Q(KLineEdit); if (!completionRunning && (text != userText)) { userText = text; q->setModified(true); #ifndef KCOMPLETION_NO_DEPRECATED emit q->userTextChanged(text); #endif emit q->textEdited(text); emit q->textChanged(text); } } // This is called when the lineedit is readonly. // Either from setReadOnly() itself, or when we realize that // we became readonly and setReadOnly() wasn't called (because it's not virtual) // Typical case: comboBox->lineEdit()->setReadOnly(true) void KLineEditPrivate::adjustForReadOnly() { if (style && style.data()->m_overlap) { style.data()->m_overlap = 0; } } QRect KLineEditStyle::subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const { if (element == SE_LineEditContents) { KLineEditStyle *unconstThis = const_cast(this); if (m_sentinel) { // we are recursing: we're wrapping a style that wraps us! unconstThis->m_subStyle.clear(); } unconstThis->m_sentinel = true; QStyle *s = m_subStyle ? m_subStyle.data() : baseStyle(); QRect rect = s->subElementRect(SE_LineEditContents, option, widget); unconstThis->m_sentinel = false; if (option->direction == Qt::LeftToRight) { return rect.adjusted(0, 0, -m_overlap, 0); } else { return rect.adjusted(m_overlap, 0, 0, 0); } } return QProxyStyle::subElementRect(element, option, widget); } bool KLineEditPrivate::s_backspacePerformsCompletion = false; bool KLineEditPrivate::s_initialized = false; void KLineEditPrivate::init() { Q_Q(KLineEdit); //--- completionBox = 0L; handleURLDrops = true; trapReturnKeyEvents = false; userSelection = true; autoSuggest = false; disableRestoreSelection = false; enableSqueezedText = false; completionRunning = false; if (!s_initialized) { KConfigGroup config(KSharedConfig::openConfig(), "General"); s_backspacePerformsCompletion = config.readEntry("Backspace performs completion", false); s_initialized = true; } clearButton = 0; clickInClear = false; wideEnoughForClear = true; urlDropEventFilter = new LineEditUrlDropEventFilter(q); // i18n: Placeholder text in line edit widgets is the text appearing // before any user input, briefly explaining to the user what to type // (e.g. "Enter search pattern"). // By default the text is set in italic, which may not be appropriate // for some languages and scripts (e.g. for CJK ideographs). QString metaMsg = KLineEdit::tr("1", "Italic placeholder text in line edits: 0 no, 1 yes"); italicizePlaceholder = (metaMsg.trimmed() != QString('0')); //--- possibleTripleClick = false; bgRole = q->backgroundRole(); // Enable the context menu by default. q->QLineEdit::setContextMenuPolicy(Qt::DefaultContextMenu); KCursor::setAutoHideCursor(q, true, true); KCompletion::CompletionMode mode = q->completionMode(); autoSuggest = (mode == KCompletion::CompletionMan || mode == KCompletion::CompletionPopupAuto || mode == KCompletion::CompletionAuto); q->connect(q, SIGNAL(selectionChanged()), q, SLOT(slotRestoreSelectionColors())); if (handleURLDrops) { q->installEventFilter(urlDropEventFilter); } const QPalette p = q->palette(); if (!previousHighlightedTextColor.isValid()) { previousHighlightedTextColor = p.color(QPalette::Normal, QPalette::HighlightedText); } if (!previousHighlightColor.isValid()) { previousHighlightColor = p.color(QPalette::Normal, QPalette::Highlight); } style = new KLineEditStyle(q->style()); q->setStyle(style.data()); q->connect(q, SIGNAL(textChanged(QString)), q, SLOT(_k_textChanged(QString))); } KLineEdit::KLineEdit(const QString &string, QWidget *parent) : QLineEdit(string, parent), d_ptr(new KLineEditPrivate(this)) { Q_D(KLineEdit); d->init(); } KLineEdit::KLineEdit(QWidget *parent) : QLineEdit(parent), d_ptr(new KLineEditPrivate(this)) { Q_D(KLineEdit); d->init(); } KLineEdit::~KLineEdit() { } #ifndef KCOMPLETION_NO_DEPRECATED QString KLineEdit::clickMessage() const { return placeholderText(); } #endif void KLineEdit::setClearButtonShown(bool show) { Q_D(KLineEdit); if (show) { if (d->clearButton) { return; } d->clearButton = new KLineEditButton(this); d->clearButton->setObjectName("KLineEditButton"); d->clearButton->setCursor(Qt::ArrowCursor); d->clearButton->setToolTip(tr("Clear text", "@action:button Clear current text in the line edit")); d->updateClearButtonIcon(text()); d->updateClearButton(); connect(this, SIGNAL(textChanged(QString)), this, SLOT(updateClearButtonIcon(QString))); } else { disconnect(this, SIGNAL(textChanged(QString)), this, SLOT(updateClearButtonIcon(QString))); delete d->clearButton; d->clearButton = 0; d->clickInClear = false; if (d->style) { d->style.data()->m_overlap = 0; } } } bool KLineEdit::isClearButtonShown() const { Q_D(const KLineEdit); return d->clearButton != 0; } QSize KLineEdit::clearButtonUsedSize() const { Q_D(const KLineEdit); QSize s; if (d->clearButton) { const int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth, 0, this); s = d->clearButton->sizeHint(); s.rwidth() += frameWidth; } return s; } // Decides whether to show or hide the icon; called when the text changes void KLineEditPrivate::updateClearButtonIcon(const QString &text) { Q_Q(KLineEdit); if (!clearButton) { return; } if (q->isReadOnly()) { adjustForReadOnly(); return; } // set proper icon if necessary if (clearButton->pixmap().isNull()) { QString iconName = q->layoutDirection() == Qt::LeftToRight ? "edit-clear-locationbar-rtl" : "edit-clear-locationbar-ltr"; int size = clearButton->style()->pixelMetric(QStyle::PM_SmallIconSize, 0, q); clearButton->setPixmap(QIcon::fromTheme(iconName).pixmap(size, size)); } // trigger animation if (wideEnoughForClear && text.length() > 0) { clearButton->animateVisible(true); } else { clearButton->animateVisible(false); } } // Determine geometry of clear button. Called initially, and on resizeEvent. void KLineEditPrivate::updateClearButton() { Q_Q(KLineEdit); if (!clearButton) { return; } if (q->isReadOnly()) { adjustForReadOnly(); return; } const QSize geom = q->size(); const int frameWidth = q->style()->pixelMetric(QStyle::PM_DefaultFrameWidth, 0, q); const int buttonWidth = clearButton->sizeHint().width(); const QSize newButtonSize(buttonWidth, geom.height()); const QFontMetrics fm(q->font()); const int em = fm.width("m"); // make sure we have enough room for the clear button // no point in showing it if we can't also see a few characters as well const bool wideEnough = geom.width() > 4 * em + buttonWidth + frameWidth; if (newButtonSize != clearButton->size()) { clearButton->resize(newButtonSize); } if (style) { style.data()->m_overlap = wideEnough ? buttonWidth + frameWidth : 0; } if (q->layoutDirection() == Qt::LeftToRight) { clearButton->move(geom.width() - frameWidth - buttonWidth - 1, 0); } else { clearButton->move(frameWidth + 1, 0); } if (wideEnough != wideEnoughForClear) { // we may (or may not) have been showing the button, but now our // positiong on that matter has shifted, so let's ensure that it // is properly visible (or not) wideEnoughForClear = wideEnough; updateClearButtonIcon(q->text()); } } void KLineEdit::setCompletionMode(KCompletion::CompletionMode mode) { Q_D(KLineEdit); KCompletion::CompletionMode oldMode = completionMode(); if (oldMode != mode && (oldMode == KCompletion::CompletionPopup || oldMode == KCompletion::CompletionPopupAuto) && d->completionBox && d->completionBox->isVisible()) { d->completionBox->hide(); } // If the widgets echo mode is not Normal, no completion // feature will be enabled even if one is requested. if (echoMode() != QLineEdit::Normal) { mode = KCompletion::CompletionNone; // Override the request. } if (!KAuthorized::authorize("lineedit_text_completion")) { mode = KCompletion::CompletionNone; } if (mode == KCompletion::CompletionPopupAuto || mode == KCompletion::CompletionAuto || mode == KCompletion::CompletionMan) { d->autoSuggest = true; } else { d->autoSuggest = false; } KCompletionBase::setCompletionMode(mode); } void KLineEdit::setCompletionModeDisabled(KCompletion::CompletionMode mode, bool disable) { Q_D(KLineEdit); d->disableCompletionMap[ mode ] = disable; } void KLineEdit::setCompletedText(const QString &t, bool marked) { Q_D(KLineEdit); if (!d->autoSuggest) { return; } const QString txt = text(); if (t != txt) { setText(t); if (marked) { setSelection(t.length(), txt.length() - t.length()); } setUserSelection(false); } else { setUserSelection(true); } } void KLineEdit::setCompletedText(const QString &text) { KCompletion::CompletionMode mode = completionMode(); const bool marked = (mode == KCompletion::CompletionAuto || mode == KCompletion::CompletionMan || mode == KCompletion::CompletionPopup || mode == KCompletion::CompletionPopupAuto); setCompletedText(text, marked); } void KLineEdit::rotateText(KCompletionBase::KeyBindingType type) { KCompletion *comp = compObj(); if (comp && (type == KCompletionBase::PrevCompletionMatch || type == KCompletionBase::NextCompletionMatch)) { QString input; if (type == KCompletionBase::PrevCompletionMatch) { input = comp->previousMatch(); } else { input = comp->nextMatch(); } // Skip rotation if previous/next match is null or the same text if (input.isEmpty() || input == displayText()) { return; } setCompletedText(input, hasSelectedText()); } } void KLineEdit::makeCompletion(const QString &text) { Q_D(KLineEdit); KCompletion *comp = compObj(); KCompletion::CompletionMode mode = completionMode(); if (!comp || mode == KCompletion::CompletionNone) { return; // No completion object... } const QString match = comp->makeCompletion(text); if (mode == KCompletion::CompletionPopup || mode == KCompletion::CompletionPopupAuto) { if (match.isEmpty()) { if (d->completionBox) { d->completionBox->hide(); d->completionBox->clear(); } } else { setCompletedItems(comp->allMatches()); } } else { // Auto, ShortAuto (Man) and Shell // all other completion modes // If no match or the same match, simply return without completing. if (match.isEmpty() || match == text) { return; } if (mode != KCompletion::CompletionShell) { setUserSelection(false); } if (d->autoSuggest) { setCompletedText(match); } } } void KLineEdit::setReadOnly(bool readOnly) { Q_D(KLineEdit); // Do not do anything if nothing changed... if (readOnly == isReadOnly()) { return; } QLineEdit::setReadOnly(readOnly); if (readOnly) { d->bgRole = backgroundRole(); setBackgroundRole(QPalette::Window); if (d->enableSqueezedText && d->squeezedText.isEmpty()) { d->squeezedText = text(); d->setSqueezedText(); } if (d->clearButton) { d->clearButton->animateVisible(false); d->adjustForReadOnly(); } } else { if (!d->squeezedText.isEmpty()) { setText(d->squeezedText); d->squeezedText.clear(); } setBackgroundRole(d->bgRole); d->updateClearButton(); } } void KLineEdit::setSqueezedText(const QString &text) { setSqueezedTextEnabled(true); setText(text); } void KLineEdit::setSqueezedTextEnabled(bool enable) { Q_D(KLineEdit); d->enableSqueezedText = enable; } bool KLineEdit::isSqueezedTextEnabled() const { Q_D(const KLineEdit); return d->enableSqueezedText; } void KLineEdit::setText(const QString &text) { Q_D(KLineEdit); if (d->enableSqueezedText && isReadOnly()) { d->squeezedText = text; d->setSqueezedText(); return; } QLineEdit::setText(text); } void KLineEditPrivate::setSqueezedText() { Q_Q(KLineEdit); squeezedStart = 0; squeezedEnd = 0; const QString fullText = squeezedText; const int fullLength = fullText.length(); const QFontMetrics fm(q->fontMetrics()); const int labelWidth = q->size().width() - 2 * q->style()->pixelMetric(QStyle::PM_DefaultFrameWidth) - 2; const int textWidth = fm.width(fullText); if (textWidth > labelWidth) { // start with the dots only QString squeezedText = "..."; int squeezedWidth = fm.width(squeezedText); // estimate how many letters we can add to the dots on both sides int letters = fullText.length() * (labelWidth - squeezedWidth) / textWidth / 2; squeezedText = fullText.left(letters) + "..." + fullText.right(letters); squeezedWidth = fm.width(squeezedText); if (squeezedWidth < labelWidth) { // we estimated too short // add letters while text < label do { letters++; squeezedText = fullText.left(letters) + "..." + fullText.right(letters); squeezedWidth = fm.width(squeezedText); } while (squeezedWidth < labelWidth && letters <= fullLength / 2); letters--; squeezedText = fullText.left(letters) + "..." + fullText.right(letters); } else if (squeezedWidth > labelWidth) { // we estimated too long // remove letters while text > label do { letters--; squeezedText = fullText.left(letters) + "..." + fullText.right(letters); squeezedWidth = fm.width(squeezedText); } while (squeezedWidth > labelWidth && letters >= 5); } if (letters < 5) { // too few letters added -> we give up squeezing q->QLineEdit::setText(fullText); } else { q->QLineEdit::setText(squeezedText); squeezedStart = letters; squeezedEnd = fullText.length() - letters; } q->setToolTip(fullText); } else { q->QLineEdit::setText(fullText); q->setToolTip(""); QToolTip::showText(q->pos(), QString()); // hide } q->setCursorPosition(0); } void KLineEdit::copy() const { Q_D(const KLineEdit); if (!d->copySqueezedText(true)) { QLineEdit::copy(); } } bool KLineEditPrivate::copySqueezedText(bool copy) const { Q_Q(const KLineEdit); if (!squeezedText.isEmpty() && squeezedStart) { KLineEdit *that = const_cast(q); if (!that->hasSelectedText()) { return false; } int start = q->selectionStart(), end = start + q->selectedText().length(); if (start >= squeezedStart + 3) { start = start - 3 - squeezedStart + squeezedEnd; } else if (start > squeezedStart) { start = squeezedStart; } if (end >= squeezedStart + 3) { end = end - 3 - squeezedStart + squeezedEnd; } else if (end > squeezedStart) { end = squeezedEnd; } if (start == end) { return false; } QString t = squeezedText; t = t.mid(start, end - start); q->disconnect(QApplication::clipboard(), SIGNAL(selectionChanged()), q, 0); QApplication::clipboard()->setText(t, copy ? QClipboard::Clipboard : QClipboard::Selection); q->connect(QApplication::clipboard(), SIGNAL(selectionChanged()), q, SLOT(_q_clipboardChanged())); return true; } return false; } void KLineEdit::resizeEvent(QResizeEvent *ev) { Q_D(KLineEdit); if (!d->squeezedText.isEmpty()) { d->setSqueezedText(); } d->updateClearButton(); QLineEdit::resizeEvent(ev); } void KLineEdit::keyPressEvent(QKeyEvent *e) { Q_D(KLineEdit); const int key = e->key() | e->modifiers(); if (KStandardShortcut::copy().contains(key)) { copy(); return; } else if (KStandardShortcut::paste().contains(key)) { // TODO: // we should restore the original text (not autocompleted), otherwise the paste // will get into troubles Bug: 134691 if (!isReadOnly()) { paste(); } return; } else if (KStandardShortcut::pasteSelection().contains(key)) { QString text = QApplication::clipboard()->text(QClipboard::Selection); insert(text); deselect(); return; } else if (KStandardShortcut::cut().contains(key)) { if (!isReadOnly()) { cut(); } return; } else if (KStandardShortcut::undo().contains(key)) { if (!isReadOnly()) { undo(); } return; } else if (KStandardShortcut::redo().contains(key)) { if (!isReadOnly()) { redo(); } return; } else if (KStandardShortcut::deleteWordBack().contains(key)) { cursorWordBackward(true); if (hasSelectedText()) { del(); } e->accept(); return; } else if (KStandardShortcut::deleteWordForward().contains(key)) { // Workaround for QT bug where cursorWordForward(true); if (hasSelectedText()) { del(); } e->accept(); return; } else if (KStandardShortcut::backwardWord().contains(key)) { cursorWordBackward(false); e->accept(); return; } else if (KStandardShortcut::forwardWord().contains(key)) { cursorWordForward(false); e->accept(); return; } else if (KStandardShortcut::beginningOfLine().contains(key)) { home(false); e->accept(); return; } else if (KStandardShortcut::endOfLine().contains(key)) { end(false); e->accept(); return; } // Filter key-events if EchoMode is normal and // completion mode is not set to CompletionNone if (echoMode() == QLineEdit::Normal && completionMode() != KCompletion::CompletionNone) { if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) { const bool trap = (d->completionBox && d->completionBox->isVisible()); const bool stopEvent = (trap || (d->trapReturnKeyEvents && (e->modifiers() == Qt::NoButton || e->modifiers() == Qt::KeypadModifier))); if (stopEvent) { emit QLineEdit::returnPressed(); e->accept(); } emit returnPressed(displayText()); if (trap) { d->completionBox->hide(); deselect(); setCursorPosition(text().length()); } // Eat the event if the user asked for it, or if a completionbox was visible if (stopEvent) { return; } } const KeyBindingMap keys = keyBindingMap(); const KCompletion::CompletionMode mode = completionMode(); const bool noModifier = (e->modifiers() == Qt::NoButton || e->modifiers() == Qt::ShiftModifier || e->modifiers() == Qt::KeypadModifier); if ((mode == KCompletion::CompletionAuto || mode == KCompletion::CompletionPopupAuto || mode == KCompletion::CompletionMan) && noModifier) { if (!d->userSelection && hasSelectedText() && (e->key() == Qt::Key_Right || e->key() == Qt::Key_Left) && e->modifiers() == Qt::NoButton) { const QString old_txt = text(); d->disableRestoreSelection = true; const int start = selectionStart(); deselect(); QLineEdit::keyPressEvent(e); const int cPosition = cursorPosition(); setText(old_txt); // keep cursor at cPosition setSelection(old_txt.length(), cPosition - old_txt.length()); if (e->key() == Qt::Key_Right && cPosition > start) { //the user explicitly accepted the autocompletion d->_k_updateUserText(text()); } d->disableRestoreSelection = false; return; } if (e->key() == Qt::Key_Escape) { if (hasSelectedText() && !d->userSelection) { del(); setUserSelection(true); } // Don't swallow the Escape press event for the case // of dialogs, which have Escape associated to Cancel e->ignore(); return; } } if ((mode == KCompletion::CompletionAuto || mode == KCompletion::CompletionMan) && noModifier) { const QString keycode = e->text(); if (!keycode.isEmpty() && (keycode.unicode()->isPrint() || e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Delete)) { const bool hasUserSelection = d->userSelection; const bool hadSelection = hasSelectedText(); bool cursorNotAtEnd = false; const int start = selectionStart(); const int cPos = cursorPosition(); // When moving the cursor, we want to keep the autocompletion as an // autocompletion, so we want to process events at the cursor position // as if there was no selection. After processing the key event, we // can set the new autocompletion again. if (hadSelection && !hasUserSelection && start > cPos) { del(); setCursorPosition(cPos); cursorNotAtEnd = true; } d->disableRestoreSelection = true; QLineEdit::keyPressEvent(e); d->disableRestoreSelection = false; QString txt = text(); int len = txt.length(); if (!hasSelectedText() && len /*&& cursorPosition() == len */) { if (e->key() == Qt::Key_Backspace) { if (hadSelection && !hasUserSelection && !cursorNotAtEnd) { backspace(); txt = text(); len = txt.length(); } if (!d->s_backspacePerformsCompletion || !len) { d->autoSuggest = false; } } if (e->key() == Qt::Key_Delete) { d->autoSuggest = false; } doCompletion(txt); if ((e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Delete)) { d->autoSuggest = true; } e->accept(); } return; } } else if ((mode == KCompletion::CompletionPopup || mode == KCompletion::CompletionPopupAuto) && noModifier && !e->text().isEmpty()) { const QString old_txt = text(); const bool hasUserSelection = d->userSelection; const bool hadSelection = hasSelectedText(); bool cursorNotAtEnd = false; const int start = selectionStart(); const int cPos = cursorPosition(); const QString keycode = e->text(); // When moving the cursor, we want to keep the autocompletion as an // autocompletion, so we want to process events at the cursor position // as if there was no selection. After processing the key event, we // can set the new autocompletion again. if (hadSelection && !hasUserSelection && start > cPos && ((!keycode.isEmpty() && keycode.unicode()->isPrint()) || e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Delete)) { del(); setCursorPosition(cPos); cursorNotAtEnd = true; } const int selectedLength = selectedText().length(); d->disableRestoreSelection = true; QLineEdit::keyPressEvent(e); d->disableRestoreSelection = false; if ((selectedLength != selectedText().length()) && !hasUserSelection) { d->slotRestoreSelectionColors(); // and set userSelection to true } QString txt = text(); int len = txt.length(); if ((txt != old_txt || txt != e->text()) && len/* && ( cursorPosition() == len || force )*/ && ((!keycode.isEmpty() && keycode.unicode()->isPrint()) || e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Delete)) { if (e->key() == Qt::Key_Backspace) { if (hadSelection && !hasUserSelection && !cursorNotAtEnd) { backspace(); txt = text(); len = txt.length(); } if (!d->s_backspacePerformsCompletion) { d->autoSuggest = false; } } if (e->key() == Qt::Key_Delete) { d->autoSuggest = false; } if (d->completionBox) { d->completionBox->setCancelledText(txt); } doCompletion(txt); if ((e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Delete) && mode == KCompletion::CompletionPopupAuto) { d->autoSuggest = true; } e->accept(); } else if (!len && d->completionBox && d->completionBox->isVisible()) { d->completionBox->hide(); } return; } else if (mode == KCompletion::CompletionShell) { // Handles completion. QList cut; if (keys[TextCompletion].isEmpty()) { cut = KStandardShortcut::shortcut(KStandardShortcut::TextCompletion); } else { cut = keys[TextCompletion]; } if (cut.contains(key)) { // Emit completion if the completion mode is CompletionShell // and the cursor is at the end of the string. const QString txt = text(); const int len = txt.length(); if (cursorPosition() == len && len != 0) { doCompletion(txt); return; } } else if (d->completionBox) { d->completionBox->hide(); } } // handle rotation if (mode != KCompletion::CompletionNone) { // Handles previous match QList cut; if (keys[PrevCompletionMatch].isEmpty()) { cut = KStandardShortcut::shortcut(KStandardShortcut::PrevCompletion); } else { cut = keys[PrevCompletionMatch]; } if (cut.contains(key)) { if (emitSignals()) { emit textRotation(KCompletionBase::PrevCompletionMatch); } if (handleSignals()) { rotateText(KCompletionBase::PrevCompletionMatch); } return; } // Handles next match if (keys[NextCompletionMatch].isEmpty()) { cut = KStandardShortcut::shortcut(KStandardShortcut::NextCompletion); } else { cut = keys[NextCompletionMatch]; } if (cut.contains(key)) { if (emitSignals()) { emit textRotation(KCompletionBase::NextCompletionMatch); } if (handleSignals()) { rotateText(KCompletionBase::NextCompletionMatch); } return; } } // substring completion if (compObj()) { QList cut; if (keys[SubstringCompletion].isEmpty()) { cut = KStandardShortcut::shortcut(KStandardShortcut::SubstringCompletion); } else { cut = keys[SubstringCompletion]; } if (cut.contains(key)) { if (emitSignals()) { emit substringCompletion(text()); } if (handleSignals()) { setCompletedItems(compObj()->substringCompletion(text())); e->accept(); } return; } } } const int selectedLength = selectedText().length(); // Let QLineEdit handle any other keys events. QLineEdit::keyPressEvent(e); if (selectedLength != selectedText().length()) { d->slotRestoreSelectionColors(); // and set userSelection to true } } void KLineEdit::mouseDoubleClickEvent(QMouseEvent *e) { Q_D(KLineEdit); if (e->button() == Qt::LeftButton) { d->possibleTripleClick = true; QTimer::singleShot(QApplication::doubleClickInterval(), this, SLOT(tripleClickTimeout())); } QLineEdit::mouseDoubleClickEvent(e); } void KLineEdit::mousePressEvent(QMouseEvent *e) { Q_D(KLineEdit); if ((e->button() == Qt::LeftButton || e->button() == Qt::MidButton) && d->clearButton) { d->clickInClear = (d->clearButton == childAt(e->pos()) || d->clearButton->underMouse()); if (d->clickInClear) { d->possibleTripleClick = false; } } if (e->button() == Qt::LeftButton && d->possibleTripleClick) { selectAll(); e->accept(); return; } // if middle clicking and if text is present in the clipboard then clear the selection // to prepare paste operation if (e->button() == Qt::MidButton) { if (hasSelectedText() && !isReadOnly()) { if (QApplication::clipboard()->text(QClipboard::Selection).length() > 0) { backspace(); } } } QLineEdit::mousePressEvent(e); } void KLineEdit::mouseReleaseEvent(QMouseEvent *e) { Q_D(KLineEdit); if (d->clickInClear) { if (d->clearButton == childAt(e->pos()) || d->clearButton->underMouse()) { QString newText; if (e->button() == Qt::MidButton) { newText = QApplication::clipboard()->text(QClipboard::Selection); setText(newText); } else { setSelection(0, text().size()); del(); emit clearButtonClicked(); } emit textChanged(newText); } d->clickInClear = false; e->accept(); return; } QLineEdit::mouseReleaseEvent(e); if (QApplication::clipboard()->supportsSelection()) { if (e->button() == Qt::LeftButton) { // Fix copying of squeezed text if needed d->copySqueezedText(false); } } } void KLineEditPrivate::tripleClickTimeout() { possibleTripleClick = false; } QMenu *KLineEdit::createStandardContextMenu() { Q_D(KLineEdit); QMenu *popup = QLineEdit::createStandardContextMenu(); if (!isReadOnly()) { // FIXME: This code depends on Qt's action ordering. const QList actionList = popup->actions(); enum { UndoAct, RedoAct, Separator1, CutAct, CopyAct, PasteAct, DeleteAct, ClearAct, Separator2, SelectAllAct, NCountActs }; QAction *separatorAction = 0L; // separator we want is right after Delete right now. const int idx = actionList.indexOf(actionList[DeleteAct]) + 1; if (idx < actionList.count()) { separatorAction = actionList.at(idx); } if (separatorAction) { QAction *clearAllAction = new QAction(QIcon::fromTheme("edit-clear"), tr("C&lear"), this); clearAllAction->setShortcuts(QKeySequence::keyBindings(QKeySequence::DeleteCompleteLine)); connect(clearAllAction, SIGNAL(triggered(bool)), SLOT(clear())); if (text().isEmpty()) { clearAllAction->setEnabled(false); } popup->insertAction(separatorAction, clearAllAction); } } // If a completion object is present and the input // widget is not read-only, show the Text Completion // menu item. if (compObj() && !isReadOnly() && KAuthorized::authorize("lineedit_text_completion")) { QMenu *subMenu = popup->addMenu(QIcon::fromTheme("text-completion"), tr("Text Completion", "@title:menu")); connect(subMenu, SIGNAL(triggered(QAction*)), this, SLOT(completionMenuActivated(QAction*))); popup->addSeparator(); QActionGroup *ag = new QActionGroup(this); d->noCompletionAction = ag->addAction(tr("None", "@item:inmenu Text Completion")); d->shellCompletionAction = ag->addAction(tr("Manual", "@item:inmenu Text Completion")); d->autoCompletionAction = ag->addAction(tr("Automatic", "@item:inmenu Text Completion")); d->popupCompletionAction = ag->addAction(tr("Dropdown List", "@item:inmenu Text Completion")); d->shortAutoCompletionAction = ag->addAction(tr("Short Automatic", "@item:inmenu Text Completion")); d->popupAutoCompletionAction = ag->addAction(tr("Dropdown List && Automatic", "@item:inmenu Text Completion")); subMenu->addActions(ag->actions()); //subMenu->setAccel( KStandardShortcut::completion(), ShellCompletion ); d->shellCompletionAction->setCheckable(true); d->noCompletionAction->setCheckable(true); d->popupCompletionAction->setCheckable(true); d->autoCompletionAction->setCheckable(true); d->shortAutoCompletionAction->setCheckable(true); d->popupAutoCompletionAction->setCheckable(true); d->shellCompletionAction->setEnabled(!d->disableCompletionMap[ KCompletion::CompletionShell ]); d->noCompletionAction->setEnabled(!d->disableCompletionMap[ KCompletion::CompletionNone ]); d->popupCompletionAction->setEnabled(!d->disableCompletionMap[ KCompletion::CompletionPopup ]); d->autoCompletionAction->setEnabled(!d->disableCompletionMap[ KCompletion::CompletionAuto ]); d->shortAutoCompletionAction->setEnabled(!d->disableCompletionMap[ KCompletion::CompletionMan ]); d->popupAutoCompletionAction->setEnabled(!d->disableCompletionMap[ KCompletion::CompletionPopupAuto ]); const KCompletion::CompletionMode mode = completionMode(); d->noCompletionAction->setChecked(mode == KCompletion::CompletionNone); d->shellCompletionAction->setChecked(mode == KCompletion::CompletionShell); d->popupCompletionAction->setChecked(mode == KCompletion::CompletionPopup); d->autoCompletionAction->setChecked(mode == KCompletion::CompletionAuto); d->shortAutoCompletionAction->setChecked(mode == KCompletion::CompletionMan); d->popupAutoCompletionAction->setChecked(mode == KCompletion::CompletionPopupAuto); const KCompletion::CompletionMode defaultMode = KCompletion::CompletionPopup; if (mode != defaultMode && !d->disableCompletionMap[ defaultMode ]) { subMenu->addSeparator(); d->defaultAction = subMenu->addAction(tr("Default", "@item:inmenu Text Completion")); } } return popup; } void KLineEdit::contextMenuEvent(QContextMenuEvent *e) { if (QLineEdit::contextMenuPolicy() != Qt::DefaultContextMenu) { return; } QMenu *popup = createStandardContextMenu(); // ### do we really need this? Yes, Please do not remove! This // allows applications to extend the popup menu without having to // inherit from this class! (DA) emit aboutToShowContextMenu(popup); popup->exec(e->globalPos()); delete popup; } void KLineEditPrivate::completionMenuActivated(QAction *act) { Q_Q(KLineEdit); KCompletion::CompletionMode oldMode = q->completionMode(); if (act == noCompletionAction) { q->setCompletionMode(KCompletion::CompletionNone); } else if (act == shellCompletionAction) { q->setCompletionMode(KCompletion::CompletionShell); } else if (act == autoCompletionAction) { q->setCompletionMode(KCompletion::CompletionAuto); } else if (act == popupCompletionAction) { q->setCompletionMode(KCompletion::CompletionPopup); } else if (act == shortAutoCompletionAction) { q->setCompletionMode(KCompletion::CompletionMan); } else if (act == popupAutoCompletionAction) { q->setCompletionMode(KCompletion::CompletionPopupAuto); } else if (act == defaultAction) { q->setCompletionMode(KCompletion::CompletionPopup); } else { return; } if (oldMode != q->completionMode()) { if ((oldMode == KCompletion::CompletionPopup || oldMode == KCompletion::CompletionPopupAuto) && completionBox && completionBox->isVisible()) { completionBox->hide(); } emit q->completionModeChanged(q->completionMode()); } } bool KLineEdit::event(QEvent *ev) { Q_D(KLineEdit); KCursor::autoHideEventFilter(this, ev); if (ev->type() == QEvent::ShortcutOverride) { QKeyEvent *e = static_cast(ev); if (d->overrideShortcut(e)) { ev->accept(); } } else if (ev->type() == QEvent::ApplicationPaletteChange || ev->type() == QEvent::PaletteChange) { // Assume the widget uses the application's palette QPalette p = QApplication::palette(); d->previousHighlightedTextColor = p.color(QPalette::Normal, QPalette::HighlightedText); d->previousHighlightColor = p.color(QPalette::Normal, QPalette::Highlight); setUserSelection(d->userSelection); } else if (ev->type() == QEvent::StyleChange) { // since we have our own style and it relies on this style to Get Things Right, // if a style is set specifically on the widget (which would replace our own style!) // hang on to this special style and re-instate our own style. //FIXME: Qt currently has a grave bug where already deleted QStyleSheetStyle objects // will get passed back in if we set a new style on it here. remove the qstrmcp test // when this is fixed in Qt (or a better approach is found) if (!qobject_cast(style()) && qstrcmp(style()->metaObject()->className(), "QStyleSheetStyle") != 0 && QLatin1String(style()->metaObject()->className()) != d->lastStyleClass) { KLineEditStyle *kleStyle = d->style.data(); if (!kleStyle) { d->style = kleStyle = new KLineEditStyle(style()); } kleStyle->m_subStyle = style(); // this guards against "wrap around" where another style, e.g. QStyleSheetStyle, // is setting the style on QEvent::StyleChange d->lastStyleClass = QLatin1String(style()->metaObject()->className()); setStyle(kleStyle); d->lastStyleClass.clear(); } } else if (ev->type() == QEvent::ApplicationLayoutDirectionChange || ev->type() == QEvent::LayoutDirectionChange) { d->updateClearButtonIcon(text()); d->updateClearButton(); } return QLineEdit::event(ev); } #ifndef KCOMPLETION_NO_DEPRECATED void KLineEdit::setUrlDropsEnabled(bool enable) { Q_D(KLineEdit); if (enable && !d->handleURLDrops) { installEventFilter(d->urlDropEventFilter); d->handleURLDrops = true; } else if (!enable && d->handleURLDrops) { removeEventFilter(d->urlDropEventFilter); d->handleURLDrops = false; } } #endif bool KLineEdit::urlDropsEnabled() const { Q_D(const KLineEdit); return d->handleURLDrops; } void KLineEdit::setTrapReturnKey(bool trap) { Q_D(KLineEdit); d->trapReturnKeyEvents = trap; } bool KLineEdit::trapReturnKey() const { Q_D(const KLineEdit); return d->trapReturnKeyEvents; } void KLineEdit::setUrl(const QUrl &url) { setText(url.toDisplayString()); } void KLineEdit::setCompletionBox(KCompletionBox *box) { Q_D(KLineEdit); if (d->completionBox) { return; } d->completionBox = box; if (handleSignals()) { connect(d->completionBox, SIGNAL(currentTextChanged(QString)), SLOT(_k_slotCompletionBoxTextChanged(QString))); connect(d->completionBox, SIGNAL(userCancelled(QString)), SLOT(userCancelled(QString))); connect(d->completionBox, SIGNAL(activated(QString)), SIGNAL(completionBoxActivated(QString))); connect(d->completionBox, SIGNAL(activated(QString)), SIGNAL(textEdited(QString))); } } /* * Set the line edit text without changing the modified flag. By default * calling setText resets the modified flag to false. */ static void setEditText(KLineEdit *edit, const QString &text) { if (!edit) { return; } const bool wasModified = edit->isModified(); edit->setText(text); edit->setModified(wasModified); } void KLineEdit::userCancelled(const QString &cancelText) { Q_D(KLineEdit); if (completionMode() != KCompletion::CompletionPopupAuto) { setEditText(this, cancelText); } else if (hasSelectedText()) { if (d->userSelection) { deselect(); } else { d->autoSuggest = false; const int start = selectionStart(); const QString s = text().remove(selectionStart(), selectedText().length()); setEditText(this, s); setCursorPosition(start); d->autoSuggest = true; } } } bool KLineEditPrivate::overrideShortcut(const QKeyEvent *e) { Q_Q(KLineEdit); QList scKey; const int key = e->key() | e->modifiers(); const KLineEdit::KeyBindingMap keys = q->keyBindingMap(); if (keys[KLineEdit::TextCompletion].isEmpty()) { scKey = KStandardShortcut::shortcut(KStandardShortcut::TextCompletion); } else { scKey = keys[KLineEdit::TextCompletion]; } if (scKey.contains(key)) { return true; } if (keys[KLineEdit::NextCompletionMatch].isEmpty()) { scKey = KStandardShortcut::shortcut(KStandardShortcut::NextCompletion); } else { scKey = keys[KLineEdit::NextCompletionMatch]; } if (scKey.contains(key)) { return true; } if (keys[KLineEdit::PrevCompletionMatch].isEmpty()) { scKey = KStandardShortcut::shortcut(KStandardShortcut::PrevCompletion); } else { scKey = keys[KLineEdit::PrevCompletionMatch]; } if (scKey.contains(key)) { return true; } // Override all the text manupilation accelerators... if (KStandardShortcut::copy().contains(key)) { return true; } else if (KStandardShortcut::paste().contains(key)) { return true; } else if (KStandardShortcut::cut().contains(key)) { return true; } else if (KStandardShortcut::undo().contains(key)) { return true; } else if (KStandardShortcut::redo().contains(key)) { return true; } else if (KStandardShortcut::deleteWordBack().contains(key)) { return true; } else if (KStandardShortcut::deleteWordForward().contains(key)) { return true; } else if (KStandardShortcut::forwardWord().contains(key)) { return true; } else if (KStandardShortcut::backwardWord().contains(key)) { return true; } else if (KStandardShortcut::beginningOfLine().contains(key)) { return true; } else if (KStandardShortcut::endOfLine().contains(key)) { return true; } // Shortcut overrides for shortcuts that QLineEdit handles // but doesn't dare force as "stronger than kaction shortcuts"... else if (e->matches(QKeySequence::SelectAll)) { return true; } else if (qApp->platformName() == "xcb" && (key == Qt::CTRL + Qt::Key_E || key == Qt::CTRL + Qt::Key_U)) { return true; } if (completionBox && completionBox->isVisible()) { const int key = e->key(); const Qt::KeyboardModifiers modifiers = e->modifiers(); if ((key == Qt::Key_Backtab || key == Qt::Key_Tab) && (modifiers == Qt::NoModifier || (modifiers & Qt::ShiftModifier))) { return true; } } return false; } void KLineEdit::setCompletedItems(const QStringList &items, bool autoSuggest) { Q_D(KLineEdit); QString txt; if (d->completionBox && d->completionBox->isVisible()) { // The popup is visible already - do the matching on the initial string, // not on the currently selected one. txt = completionBox()->cancelledText(); } else { txt = text(); } if (!items.isEmpty() && !(items.count() == 1 && txt == items.first())) { // create completion box if non-existent completionBox(); if (d->completionBox->isVisible()) { QListWidgetItem *currentItem = d->completionBox->currentItem(); QString currentSelection; if (currentItem != 0) { currentSelection = currentItem->text(); } d->completionBox->setItems(items); const QList matchedItems = d->completionBox->findItems(currentSelection, Qt::MatchExactly); QListWidgetItem *matchedItem = matchedItems.isEmpty() ? 0 : matchedItems.first(); if (matchedItem) { const bool blocked = d->completionBox->blockSignals(true); d->completionBox->setCurrentItem(matchedItem); d->completionBox->blockSignals(blocked); } else { d->completionBox->setCurrentRow(-1); } } else { // completion box not visible yet -> show it if (!txt.isEmpty()) { d->completionBox->setCancelledText(txt); } d->completionBox->setItems(items); d->completionBox->popup(); } if (d->autoSuggest && autoSuggest) { const int index = items.first().indexOf(txt); const QString newText = items.first().mid(index); setUserSelection(false); // can be removed? setCompletedText sets it anyway setCompletedText(newText, true); } } else { if (d->completionBox && d->completionBox->isVisible()) { d->completionBox->hide(); } } } KCompletionBox *KLineEdit::completionBox(bool create) { Q_D(KLineEdit); if (create && !d->completionBox) { setCompletionBox(new KCompletionBox(this)); d->completionBox->setObjectName("completion box"); d->completionBox->setFont(font()); } return d->completionBox; } void KLineEdit::setCompletionObject(KCompletion *comp, bool hsig) { KCompletion *oldComp = compObj(); if (oldComp && handleSignals()) disconnect(oldComp, SIGNAL(matches(QStringList)), this, SLOT(setCompletedItems(QStringList))); if (comp && hsig) connect(comp, SIGNAL(matches(QStringList)), this, SLOT(setCompletedItems(QStringList))); KCompletionBase::setCompletionObject(comp, hsig); } void KLineEdit::setUserSelection(bool userSelection) { Q_D(KLineEdit); //if !d->userSelection && userSelection we are accepting a completion, //so trigger an update if (!d->userSelection && userSelection) { d->_k_updateUserText(text()); } QPalette p = palette(); if (userSelection) { p.setColor(QPalette::Highlight, d->previousHighlightColor); p.setColor(QPalette::HighlightedText, d->previousHighlightedTextColor); } else { QColor color = p.color(QPalette::Disabled, QPalette::Text); p.setColor(QPalette::HighlightedText, color); color = p.color(QPalette::Active, QPalette::Base); p.setColor(QPalette::Highlight, color); } d->userSelection = userSelection; setPalette(p); } void KLineEditPrivate::slotRestoreSelectionColors() { Q_Q(KLineEdit); if (disableRestoreSelection) { return; } q->setUserSelection(true); } -void KLineEdit::clear() -{ - setText(QString()); -} - void KLineEditPrivate::_k_slotCompletionBoxTextChanged(const QString &text) { Q_Q(KLineEdit); if (!text.isEmpty()) { q->setText(text); q->setModified(true); q->end(false); // force cursor at end } } QString KLineEdit::originalText() const { Q_D(const KLineEdit); if (d->enableSqueezedText && isReadOnly()) { return d->squeezedText; } return text(); } QString KLineEdit::userText() const { Q_D(const KLineEdit); return d->userText; } bool KLineEdit::autoSuggest() const { Q_D(const KLineEdit); return d->autoSuggest; } void KLineEdit::paintEvent(QPaintEvent *ev) { Q_D(KLineEdit); if (echoMode() == Password && d->threeStars) { // ### hack alert! // QLineEdit has currently no hooks to modify the displayed string. // When we call setText(), an update() is triggered and we get // into an infinite recursion. // Qt offers the setUpdatesEnabled() method, but when we re-enable // them, update() is triggered, and we get into the same recursion. // To work around this problem, we set/clear the internal Qt flag which // marks the updatesDisabled state manually. setAttribute(Qt::WA_UpdatesDisabled, true); blockSignals(true); const QString oldText = text(); const bool isModifiedState = isModified(); // save modified state because setText resets it setText(oldText + oldText + oldText); QLineEdit::paintEvent(ev); setText(oldText); setModified(isModifiedState); blockSignals(false); setAttribute(Qt::WA_UpdatesDisabled, false); } else { QLineEdit::paintEvent(ev); } } #ifndef KCOMPLETION_NO_DEPRECATED void KLineEdit::setClickMessage(const QString &msg) { setPlaceholderText(msg); } #endif #ifndef KCOMPLETION_NO_DEPRECATED void KLineEdit::setContextMenuEnabled(bool showMenu) { QLineEdit::setContextMenuPolicy(showMenu ? Qt::DefaultContextMenu : Qt::NoContextMenu); } #endif #ifndef KCOMPLETION_NO_DEPRECATED bool KLineEdit::isContextMenuEnabled() const { return (contextMenuPolicy() == Qt::DefaultContextMenu); } #endif void KLineEdit::setPasswordMode(bool passwordMode) { Q_D(KLineEdit); if (passwordMode) { KConfigGroup cg(KSharedConfig::openConfig(), "Passwords"); const QString val = cg.readEntry("EchoMode", "OneStar"); if (val == "NoEcho") { setEchoMode(NoEcho); } else { d->threeStars = (val == "ThreeStars"); setEchoMode(Password); } } else { setEchoMode(Normal); } } bool KLineEdit::passwordMode() const { return echoMode() == NoEcho || echoMode() == Password; } void KLineEdit::doCompletion(const QString &text) { Q_D(KLineEdit); if (emitSignals()) { emit completion(text); // emit when requested... } d->completionRunning = true; if (handleSignals()) { makeCompletion(text); // handle when requested... } d->completionRunning = false; } #include "moc_klineedit.cpp" #include "moc_klineedit_p.cpp" diff --git a/src/klineedit.h b/src/klineedit.h index ca7e105..4227d4d 100644 --- a/src/klineedit.h +++ b/src/klineedit.h @@ -1,643 +1,637 @@ /* This file is part of the KDE libraries This class was originally inspired by Torben Weis' fileentry.cpp for KFM II. Copyright (C) 1997 Sven Radej Copyright (c) 1999 Patrick Ward Copyright (c) 1999 Preston Brown Completely re-designed: Copyright (c) 2000,2001 Dawit Alemayehu This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KLINEEDIT_H #define KLINEEDIT_H #include #include #include #include class QAction; class QMenu; class KCompletionBox; class QUrl; class KLineEditPrivate; /** * An enhanced QLineEdit widget for inputting text. * * \b Detail \n * * This widget inherits from QLineEdit and implements the following * additional functionalities: a completion object that provides both * automatic and manual text completion as well as multiple match iteration * features, configurable key-bindings to activate these features and a * popup-menu item that can be used to allow the user to set text completion * modes on the fly based on their preference. * * To support these new features KLineEdit also emits a few more * additional signals. These are: completion( const QString& ), * textRotation( KeyBindingType ), and returnPressed( const QString& ). * The completion signal can be connected to a slot that will assist the * user in filling out the remaining text. The text rotation signal is * intended to be used to iterate through the list of all possible matches * whenever there is more than one match for the entered text. The * @p returnPressed( const QString& ) signals are the same as QLineEdit's * except it provides the current text in the widget as its argument whenever * appropriate. * * This widget by default creates a completion object when you invoke * the completionObject( bool ) member function for the first time or * use setCompletionObject( KCompletion*, bool ) to assign your own * completion object. Additionally, to make this widget more functional, * KLineEdit will by default handle the text rotation and completion * events internally when a completion object is created through either one * of the methods mentioned above. If you do not need this functionality, * simply use KCompletionBase::setHandleSignals( bool ) or set the * boolean parameter in the above functions to false. * * The default key-bindings for completion and rotation is determined * from the global settings in KStandardShortcut. These values, however, * can be overridden locally by invoking KCompletionBase::setKeyBinding(). * The values can easily be reverted back to the default setting, by simply * calling useGlobalSettings(). An alternate method would be to default * individual key-bindings by using setKeyBinding() with the default * second argument. * * If @p EchoMode for this widget is set to something other than @p QLineEdit::Normal, * the completion mode will always be defaulted to CompletionNone. * This is done purposefully to guard against protected entries such as passwords being * cached in KCompletion's list. Hence, if the @p EchoMode is not QLineEdit::Normal, the * completion mode is automatically disabled. * * A read-only KLineEdit will have the same background color as a * disabled KLineEdit, but its foreground color will be the one used * for the read-write mode. This differs from QLineEdit's implementation * and is done to give visual distinction between the three different modes: * disabled, read-only, and read-write. * * KLineEdit has also a password mode which depends of globals KDE settings. Use * KLineEdit::setPasswordMode instead of QLineEdit::echoMode property to have a password field. * * \b Usage \n * * To enable the basic completion feature: * * \code * KLineEdit *edit = new KLineEdit( this ); * KCompletion *comp = edit->completionObject(); * // Connect to the return pressed signal - optional * connect(edit,SIGNAL(returnPressed(const QString&)),comp,SLOT(addItem(const QString&))); * \endcode * * To use a customized completion objects or your * own completion object: * * \code * KLineEdit *edit = new KLineEdit( this ); * KUrlCompletion *comp = new KUrlCompletion(); * edit->setCompletionObject( comp ); * // Connect to the return pressed signal - optional * connect(edit,SIGNAL(returnPressed(const QString&)),comp,SLOT(addItem(const QString&))); * \endcode * * Note if you specify your own completion object you have to either delete * it when you don't need it anymore, or you can tell KLineEdit to delete it * for you: * \code * edit->setAutoDeleteCompletionObject( true ); * \endcode * * Miscellaneous function calls :\n * * \code * // Tell the widget to not handle completion and iteration automatically. * edit->setHandleSignals( false ); * * // Set your own key-bindings for a text completion mode. * edit->setKeyBinding( KCompletionBase::TextCompletion, Qt::End ); * * // Hide the context (popup) menu * edit->setContextMenuPolicy( Qt::NoContextMenu ); * * // Default the key-bindings back to the default system settings. * edit->useGlobalKeyBindings(); * \endcode * * \image html klineedit.png "KDE Line Edit Widgets with clear-button" * * @author Dawit Alemayehu */ class KCOMPLETION_EXPORT KLineEdit : public QLineEdit, public KCompletionBase //krazy:exclude=qclasses { friend class KComboBox; friend class KLineEditStyle; Q_OBJECT Q_DECLARE_PRIVATE(KLineEdit) #ifndef KCOMPLETION_NO_DEPRECATED Q_PROPERTY(bool contextMenuEnabled READ isContextMenuEnabled WRITE setContextMenuEnabled) #endif #ifndef KCOMPLETION_NO_DEPRECATED Q_PROPERTY(bool urlDropsEnabled READ urlDropsEnabled WRITE setUrlDropsEnabled) #endif Q_PROPERTY(bool trapEnterKeyEvent READ trapReturnKey WRITE setTrapReturnKey) Q_PROPERTY(bool squeezedTextEnabled READ isSqueezedTextEnabled WRITE setSqueezedTextEnabled) #ifndef KCOMPLETION_NO_DEPRECATED Q_PROPERTY(QString clickMessage READ clickMessage WRITE setClickMessage) #endif Q_PROPERTY(bool showClearButton READ isClearButtonShown WRITE setClearButtonShown) Q_PROPERTY(bool passwordMode READ passwordMode WRITE setPasswordMode) public: /** * Constructs a KLineEdit object with a default text, a parent, * and a name. * * @param string Text to be shown in the edit widget. * @param parent The parent widget of the line edit. */ explicit KLineEdit(const QString &string, QWidget *parent = 0); /** * Constructs a line edit * @param parent The parent widget of the line edit. */ explicit KLineEdit(QWidget *parent = 0); /** * Destructor. */ virtual ~KLineEdit(); /** * Sets @p url into the lineedit. It uses QUrl::toDisplayString() so * that the url is properly decoded for displaying. */ void setUrl(const QUrl &url); /** * Re-implemented from KCompletionBase for internal reasons. * * This function is re-implemented in order to make sure that * the EchoMode is acceptable before we set the completion mode. * * See KCompletionBase::setCompletionMode */ virtual void setCompletionMode(KCompletion::CompletionMode mode); /** * Disables completion modes by makeing them non-checkable. * * The context menu allows to change the completion mode. * This method allows to disable some modes. */ void setCompletionModeDisabled(KCompletion::CompletionMode mode, bool disable = true); /** * Enables/disables the popup (context) menu. * * This method only works if this widget is editable, i.e. read-write and * allows you to enable/disable the context menu. It does nothing if invoked * for a none-editable combo-box. * * By default, the context menu is created if this widget is editable. * Call this function with the argument set to false to disable the popup * menu. * * @param showMenu If @p true, show the context menu. * @deprecated since 4.5, use setContextMenuPolicy instead */ #ifndef KCOMPLETION_NO_DEPRECATED virtual KCOMPLETION_DEPRECATED void setContextMenuEnabled(bool showMenu); #endif /** * Returns @p true when the context menu is enabled. * @deprecated since 4.5, use contextMenuPolicy instead */ #ifndef KCOMPLETION_NO_DEPRECATED KCOMPLETION_DEPRECATED bool isContextMenuEnabled() const; #endif /** * Enables/Disables handling of URL drops. If enabled and the user * drops an URL, the decoded URL will be inserted. Otherwise the default * behavior of QLineEdit is used, which inserts the encoded URL. * * @param enable If @p true, insert decoded URLs * @deprecated since 5.0. Use installEventFilter with a LineEditUrlDropEventFilter */ #ifndef KCOMPLETION_NO_DEPRECATED KCOMPLETION_DEPRECATED void setUrlDropsEnabled(bool enable); #endif /** * Returns @p true when decoded URL drops are enabled */ bool urlDropsEnabled() const; /** * By default, KLineEdit recognizes @p Key_Return and @p Key_Enter and emits * the returnPressed() signals, but it also lets the event pass, * for example causing a dialog's default-button to be called. * * Call this method with @p trap = @p true to make @p KLineEdit stop these * events. The signals will still be emitted of course. * * @see trapReturnKey() */ void setTrapReturnKey(bool trap); /** * @returns @p true if keyevents of @p Key_Return or * @p Key_Enter will be stopped or if they will be propagated. * * @see setTrapReturnKey () */ bool trapReturnKey() const; /** * @returns the completion-box, that is used in completion mode * CompletionPopup. * This method will create a completion-box if none is there, yet. * * @param create Set this to false if you don't want the box to be created * i.e. to test if it is available. */ virtual KCompletionBox *completionBox(bool create = true); /** * Reimplemented for internal reasons, the API is not affected. */ virtual void setCompletionObject(KCompletion *, bool hsig = true); /** * Reimplemented for internal reasons, the API is not affected. */ virtual void copy() const; /** * Enable text squeezing whenever the supplied text is too long. * Only works for "read-only" mode. * * Note that once text squeezing is enabled, QLineEdit::text() * and QLineEdit::displayText() return the squeezed text. If * you want the original text, use @ref originalText. * * @see QLineEdit */ void setSqueezedTextEnabled(bool enable); /** * Returns true if text squeezing is enabled. * This is only valid when the widget is in read-only mode. */ bool isSqueezedTextEnabled() const; /** * Returns the original text if text squeezing is enabled. * If the widget is not in "read-only" mode, this function * returns the same thing as QLineEdit::text(). * * @see QLineEdit */ QString originalText() const; /** * Returns the text as given by the user (i.e. not autocompleted) * if the widget has autocompletion disabled, this function * returns the same as QLineEdit::text(). * @since 4.2.2 */ QString userText() const; /** * Set the completion-box to be used in completion mode * CompletionPopup. * This will do nothing if a completion-box already exists. * * @param box The KCompletionBox to set */ void setCompletionBox(KCompletionBox *box); /** * This makes the line edit display a grayed-out hinting text as long as * the user didn't enter any text. It is often used as indication about * the purpose of the line edit. * @deprecated since 5.0, use QLineEdit::setPlaceholderText instead. */ #ifndef KCOMPLETION_NO_DEPRECATED KCOMPLETION_DEPRECATED void setClickMessage(const QString &msg); #endif /** * @return the message set with setClickMessage * @deprecated since 5.0, use QLineEdit::placeholderText instead. */ #ifndef KCOMPLETION_NO_DEPRECATED KCOMPLETION_DEPRECATED QString clickMessage() const; #endif /** * This makes the line edit display an icon on one side of the line edit * which, when clicked, clears the contents of the line edit. * This is useful for such things as location or search bars. **/ void setClearButtonShown(bool show); /** * @return whether or not the clear button is shown **/ bool isClearButtonShown() const; /** * @return the size used by the clear button * @since 4.1 **/ QSize clearButtonUsedSize() const; /** * Do completion now. This is called automatically when typing a key for instance. * Emits completion() and/or calls makeCompletion(), depending on * emitSignals and handleSignals. * * @since 4.2.1 */ void doCompletion(const QString &text); Q_SIGNALS: /** * Emitted whenever the completion box is activated. */ void completionBoxActivated(const QString &); /** * Emitted when the user presses the return key. * * The argument is the current text. Note that this * signal is @em not emitted if the widget's @p EchoMode is set to * QLineEdit::EchoMode. */ void returnPressed(const QString &); /** * Emitted when the completion key is pressed. * * Please note that this signal is @em not emitted if the * completion mode is set to @p CompletionNone or @p EchoMode is * @em normal. */ void completion(const QString &); /** * Emitted when the shortcut for substring completion is pressed. */ void substringCompletion(const QString &); /** * Emitted when the text is changed NOT by the suggested autocompletion: * either when the user is physically typing keys, or when the text is changed programmatically, * for example, by calling setText(). * But not when automatic completion changes the text temporarily. * * @since 4.2.2 * @deprecated since 4.5. You probably want to connect to textEdited() instead, * which is emitted whenever the text is actually changed by the user * (by typing or accepting autocompletion), without side effects from * suggested autocompletion either. userTextChanged isn't needed anymore. */ #ifndef KCOMPLETION_NO_DEPRECATED QT_MOC_COMPAT void userTextChanged(const QString &); #endif /** * Emitted when the text rotation key-bindings are pressed. * * The argument indicates which key-binding was pressed. * In KLineEdit's case this can be either one of two values: * PrevCompletionMatch or NextCompletionMatch. See * KCompletionBase::setKeyBinding for details. * * Note that this signal is @em not emitted if the completion * mode is set to @p CompletionNone or @p echoMode() is @em not normal. */ void textRotation(KCompletionBase::KeyBindingType); /** * Emitted when the user changed the completion mode by using the * popupmenu. */ void completionModeChanged(KCompletion::CompletionMode); /** * Emitted before the context menu is displayed. * * The signal allows you to add your own entries into the * the context menu that is created on demand. * * NOTE: Do not store the pointer to the QMenu * provided through since it is created and deleted * on demand. * * @param contextMenu the context menu about to be displayed */ void aboutToShowContextMenu(QMenu *contextMenu); /** * Emitted when the user clicked on the clear button */ void clearButtonClicked(); public Q_SLOTS: /** * Sets the lineedit to read-only. Similar to QLineEdit::setReadOnly * but also takes care of the background color, and the clear button. */ virtual void setReadOnly(bool); /** * Iterates through all possible matches of the completed text or * the history list. * * This function simply iterates over all possible matches in case * multiple matches are found as a result of a text completion request. * It will have no effect if only a single match is found. * * @param type The key-binding invoked. */ void rotateText(KCompletionBase::KeyBindingType type); /** * See KCompletionBase::setCompletedText. */ virtual void setCompletedText(const QString &); /** * Same as the above function except it allows you to temporarily * turn off text completion in CompletionPopupAuto mode. * * * @param items list of completion matches to be shown in the completion box. * @param autoSuggest true if you want automatic text completion (suggestion) enabled. */ void setCompletedItems(const QStringList &items, bool autoSuggest = true); - /** - * Reimplemented to workaround a buggy QLineEdit::clear() - * (changing the clipboard to the text we just had in the lineedit) - */ - virtual void clear(); // ### KDE 5: check if still required - /** * Squeezes @p text into the line edit. * This can only be used with read-only line-edits. */ void setSqueezedText(const QString &text); /** * Re-implemented to enable text squeezing. API is not affected. */ virtual void setText(const QString &); /** * @brief set the line edit in password mode. * this change the EchoMode according to KDE preferences. * @param passwordMode true to set in password mode */ void setPasswordMode(bool passwordMode = true); /** * @return returns true if the lineedit is set to password mode echoing */ bool passwordMode() const; protected Q_SLOTS: /** * Completes the remaining text with a matching one from * a given list. */ virtual void makeCompletion(const QString &); /** * Resets the current displayed text. * Call this function to revert a text completion if the user * cancels the request. Mostly applies to popup completions. */ void userCancelled(const QString &cancelText); protected: /** * Re-implemented for internal reasons. API not affected. */ virtual bool event(QEvent *); /** * Re-implemented for internal reasons. API not affected. * * See QLineEdit::resizeEvent(). */ virtual void resizeEvent(QResizeEvent *); /** * Re-implemented for internal reasons. API not affected. * * See QLineEdit::keyPressEvent(). */ virtual void keyPressEvent(QKeyEvent *); /** * Re-implemented for internal reasons. API not affected. * * See QLineEdit::mousePressEvent(). */ virtual void mousePressEvent(QMouseEvent *); /** * Re-implemented for internal reasons. API not affected. * * See QLineEdit::mouseReleaseEvent(). */ virtual void mouseReleaseEvent(QMouseEvent *); /** * Re-implemented for internal reasons. API not affected. * * See QWidget::mouseDoubleClickEvent(). */ virtual void mouseDoubleClickEvent(QMouseEvent *); /** * Re-implemented for internal reasons. API not affected. * * See QLineEdit::contextMenuEvent(). */ virtual void contextMenuEvent(QContextMenuEvent *); /** * Re-implemented for internal reasons. API not affected. * * See QLineEdit::createStandardContextMenu(). */ QMenu *createStandardContextMenu(); /** * This function simply sets the lineedit text and * highlights the text appropriately if the boolean * value is set to true. * * @param text * @param marked */ virtual void setCompletedText(const QString & /*text*/, bool /*marked*/); /** * Sets the widget in userSelection mode or in automatic completion * selection mode. This changes the colors of selections. */ void setUserSelection(bool userSelection); /** * Whether in current state text should be auto-suggested */ bool autoSuggest() const; virtual void paintEvent(QPaintEvent *ev); private: const QScopedPointer d_ptr; Q_PRIVATE_SLOT(d_func(), void _k_textChanged(const QString &)) Q_PRIVATE_SLOT(d_func(), void completionMenuActivated(QAction *)) Q_PRIVATE_SLOT(d_func(), void tripleClickTimeout()) Q_PRIVATE_SLOT(d_func(), void slotRestoreSelectionColors()) Q_PRIVATE_SLOT(d_func(), void _k_slotCompletionBoxTextChanged(const QString &)) Q_PRIVATE_SLOT(d_func(), void updateClearButtonIcon(const QString &)) }; #endif