KDEUI
klineedit.cpp
Go to the documentation of this file.
00001 /* This file is part of the KDE libraries 00002 00003 Copyright (C) 1997 Sven Radej (sven.radej@iname.com) 00004 Copyright (c) 1999 Patrick Ward <PAT_WARD@HP-USA-om5.om.hp.com> 00005 Copyright (c) 1999 Preston Brown <pbrown@kde.org> 00006 00007 Re-designed for KDE 2.x by 00008 Copyright (c) 2000, 2001 Dawit Alemayehu <adawit@kde.org> 00009 Copyright (c) 2000, 2001 Carsten Pfeiffer <pfeiffer@kde.org> 00010 00011 This library is free software; you can redistribute it and/or 00012 modify it under the terms of the GNU Lesser General Public 00013 License (LGPL) as published by the Free Software Foundation; 00014 either version 2 of the License, or (at your option) any later 00015 version. 00016 00017 This library is distributed in the hope that it will be useful, 00018 but WITHOUT ANY WARRANTY; without even the implied warranty of 00019 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 00020 Lesser General Public License for more details. 00021 00022 You should have received a copy of the GNU Lesser General Public License 00023 along with this library; see the file COPYING.LIB. If not, write to 00024 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 00025 Boston, MA 02110-1301, USA. 00026 */ 00027 00028 #include "klineedit.h" 00029 #include "klineedit_p.h" 00030 00031 #include <kaction.h> 00032 #include <kapplication.h> 00033 #include <kauthorized.h> 00034 #include <kconfig.h> 00035 #include <kconfiggroup.h> 00036 #include <kcursor.h> 00037 #include <kdebug.h> 00038 #include <kcompletionbox.h> 00039 #include <kicontheme.h> 00040 #include <kicon.h> 00041 #include <klocale.h> 00042 #include <kmenu.h> 00043 #include <kstandardaction.h> 00044 #include <kstandardshortcut.h> 00045 00046 #include <QtCore/QTimer> 00047 #include <QtGui/QClipboard> 00048 #include <QtGui/QStyleOption> 00049 #include <QtGui/QToolTip> 00050 00051 class KLineEditStyle; 00052 00053 class KLineEditPrivate 00054 { 00055 public: 00056 KLineEditPrivate(KLineEdit* qq) 00057 : q(qq) 00058 { 00059 completionBox = 0L; 00060 handleURLDrops = true; 00061 grabReturnKeyEvents = false; 00062 00063 userSelection = true; 00064 autoSuggest = false; 00065 disableRestoreSelection = false; 00066 enableSqueezedText = false; 00067 00068 drawClickMsg = false; 00069 enableClickMsg = false; 00070 threeStars = false; 00071 completionRunning = false; 00072 if (!s_initialized) { 00073 KConfigGroup config( KGlobal::config(), "General" ); 00074 s_backspacePerformsCompletion = config.readEntry("Backspace performs completion", false); 00075 s_initialized = true; 00076 } 00077 00078 clearButton = 0; 00079 clickInClear = false; 00080 wideEnoughForClear = true; 00081 00082 // i18n: Placeholder text in line edit widgets is the text appearing 00083 // before any user input, briefly explaining to the user what to type 00084 // (e.g. "Enter search pattern"). 00085 // By default the text is set in italic, which may not be appropriate 00086 // for some languages and scripts (e.g. for CJK ideographs). 00087 QString metaMsg = i18nc("Italic placeholder text in line edits: 0 no, 1 yes", "1"); 00088 italicizePlaceholder = (metaMsg.trimmed() != QString('0')); 00089 } 00090 00091 ~KLineEditPrivate() 00092 { 00093 // causes a weird crash in KWord at least, so let Qt delete it for us. 00094 // delete completionBox; 00095 delete style.data(); 00096 } 00097 00098 void _k_slotSettingsChanged(int category) 00099 { 00100 Q_UNUSED(category); 00101 00102 if (clearButton) { 00103 clearButton->setAnimationsEnabled(KGlobalSettings::graphicEffectsLevel() & KGlobalSettings::SimpleAnimationEffects); 00104 } 00105 } 00106 00107 void _k_textChanged(const QString &txt) 00108 { 00109 // COMPAT (as documented): emit userTextChanged whenever textChanged is emitted 00110 // KDE5: remove userTextChanged signal, textEdited does the same... 00111 if (!completionRunning && (txt != userText)) { 00112 userText = txt; 00113 #ifndef KDE_NO_DEPRECATED 00114 emit q->userTextChanged(txt); 00115 #endif 00116 } 00117 } 00118 00119 // Call this when a completion operation changes the lineedit text 00120 // "as if it had been edited by the user". 00121 void _k_updateUserText(const QString &txt) 00122 { 00123 if (!completionRunning && (txt != userText)) { 00124 userText = txt; 00125 q->setModified(true); 00126 #ifndef KDE_NO_DEPRECATED 00127 emit q->userTextChanged(txt); 00128 #endif 00129 emit q->textEdited(txt); 00130 emit q->textChanged(txt); 00131 } 00132 } 00133 00134 // This is called when the lineedit is readonly. 00135 // Either from setReadOnly() itself, or when we realize that 00136 // we became readonly and setReadOnly() wasn't called (because it's not virtual) 00137 // Typical case: comboBox->lineEdit()->setReadOnly(true) 00138 void adjustForReadOnly() 00139 { 00140 if (style && style.data()->m_overlap) { 00141 style.data()->m_overlap = 0; 00142 } 00143 } 00144 00145 00151 bool overrideShortcut(const QKeyEvent* e); 00152 00153 static bool s_initialized; 00154 static bool s_backspacePerformsCompletion; // Configuration option 00155 00156 QColor previousHighlightColor; 00157 QColor previousHighlightedTextColor; 00158 00159 bool userSelection: 1; 00160 bool autoSuggest : 1; 00161 bool disableRestoreSelection: 1; 00162 bool handleURLDrops:1; 00163 bool grabReturnKeyEvents:1; 00164 bool enableSqueezedText:1; 00165 bool completionRunning:1; 00166 00167 int squeezedEnd; 00168 int squeezedStart; 00169 QPalette::ColorRole bgRole; 00170 QString squeezedText; 00171 QString userText; 00172 00173 QString clickMessage; 00174 bool enableClickMsg:1; 00175 bool drawClickMsg:1; 00176 bool threeStars:1; 00177 00178 bool possibleTripleClick :1; // set in mousePressEvent, deleted in tripleClickTimeout 00179 00180 bool clickInClear:1; 00181 bool wideEnoughForClear:1; 00182 KLineEditButton *clearButton; 00183 QWeakPointer<KLineEditStyle> style; 00184 QString lastStyleClass; 00185 00186 KCompletionBox *completionBox; 00187 00188 bool italicizePlaceholder:1; 00189 00190 QAction *noCompletionAction, *shellCompletionAction, *autoCompletionAction, *popupCompletionAction, *shortAutoCompletionAction, *popupAutoCompletionAction, *defaultAction; 00191 00192 QMap<KGlobalSettings::Completion, bool> disableCompletionMap; 00193 KLineEdit* q; 00194 }; 00195 00196 QStyle *KLineEditStyle::style() const 00197 { 00198 if (m_subStyle) { 00199 return m_subStyle.data(); 00200 } 00201 00202 return KdeUiProxyStyle::style(); 00203 } 00204 00205 QRect KLineEditStyle::subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const 00206 { 00207 if (element == SE_LineEditContents) { 00208 KLineEditStyle *unconstThis = const_cast<KLineEditStyle *>(this); 00209 00210 if (m_sentinel) { 00211 // we are recursing: we're wrapping a style that wraps us! 00212 unconstThis->m_subStyle.clear(); 00213 } 00214 00215 unconstThis->m_sentinel = true; 00216 QStyle *s = m_subStyle ? m_subStyle.data() : style(); 00217 QRect rect = s->subElementRect(SE_LineEditContents, option, widget); 00218 unconstThis->m_sentinel = false; 00219 00220 if (option->direction == Qt::LeftToRight) { 00221 return rect.adjusted(0, 0, -m_overlap, 0); 00222 } else { 00223 return rect.adjusted(m_overlap, 0, 0, 0); 00224 } 00225 } 00226 00227 return KdeUiProxyStyle::subElementRect(element, option, widget); 00228 } 00229 00230 bool KLineEditPrivate::s_backspacePerformsCompletion = false; 00231 bool KLineEditPrivate::s_initialized = false; 00232 00233 00234 KLineEdit::KLineEdit( const QString &string, QWidget *parent ) 00235 : QLineEdit( string, parent ), d(new KLineEditPrivate(this)) 00236 { 00237 init(); 00238 } 00239 00240 KLineEdit::KLineEdit( QWidget *parent ) 00241 : QLineEdit( parent ), d(new KLineEditPrivate(this)) 00242 { 00243 init(); 00244 } 00245 00246 00247 KLineEdit::~KLineEdit () 00248 { 00249 delete d; 00250 } 00251 00252 void KLineEdit::init() 00253 { 00254 d->possibleTripleClick = false; 00255 d->bgRole = backgroundRole(); 00256 00257 // Enable the context menu by default. 00258 QLineEdit::setContextMenuPolicy( Qt::DefaultContextMenu ); 00259 KCursor::setAutoHideCursor( this, true, true ); 00260 00261 KGlobalSettings::Completion mode = completionMode(); 00262 d->autoSuggest = (mode == KGlobalSettings::CompletionMan || 00263 mode == KGlobalSettings::CompletionPopupAuto || 00264 mode == KGlobalSettings::CompletionAuto); 00265 connect( this, SIGNAL(selectionChanged()), this, SLOT(slotRestoreSelectionColors())); 00266 00267 connect(KGlobalSettings::self(), SIGNAL(settingsChanged(int)), this, SLOT(_k_slotSettingsChanged(int))); 00268 00269 const QPalette p = palette(); 00270 if ( !d->previousHighlightedTextColor.isValid() ) 00271 d->previousHighlightedTextColor=p.color(QPalette::Normal,QPalette::HighlightedText); 00272 if ( !d->previousHighlightColor.isValid() ) 00273 d->previousHighlightColor=p.color(QPalette::Normal,QPalette::Highlight); 00274 00275 d->style = new KLineEditStyle(this); 00276 setStyle(d->style.data()); 00277 00278 connect(this, SIGNAL(textChanged(QString)), this, SLOT(_k_textChanged(QString))); 00279 00280 } 00281 00282 QString KLineEdit::clickMessage() const 00283 { 00284 return d->clickMessage; 00285 } 00286 00287 void KLineEdit::setClearButtonShown(bool show) 00288 { 00289 if (show) { 00290 if (d->clearButton) { 00291 return; 00292 } 00293 00294 d->clearButton = new KLineEditButton(this); 00295 d->clearButton->setCursor( Qt::ArrowCursor ); 00296 d->clearButton->setToolTip( i18nc( "@action:button Clear current text in the line edit", "Clear text" ) ); 00297 00298 updateClearButtonIcon(text()); 00299 updateClearButton(); 00300 connect(this, SIGNAL(textChanged(QString)), this, SLOT(updateClearButtonIcon(QString))); 00301 } else { 00302 disconnect(this, SIGNAL(textChanged(QString)), this, SLOT(updateClearButtonIcon(QString))); 00303 delete d->clearButton; 00304 d->clearButton = 0; 00305 d->clickInClear = false; 00306 if (d->style) { 00307 d->style.data()->m_overlap = 0; 00308 } 00309 } 00310 } 00311 00312 bool KLineEdit::isClearButtonShown() const 00313 { 00314 return d->clearButton != 0; 00315 } 00316 00317 QSize KLineEdit::clearButtonUsedSize() const 00318 { 00319 QSize s; 00320 if (d->clearButton) { 00321 const int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth, 0, this); 00322 s = d->clearButton->sizeHint(); 00323 s.rwidth() += frameWidth; 00324 } 00325 return s; 00326 } 00327 00328 // Decides whether to show or hide the icon; called when the text changes 00329 void KLineEdit::updateClearButtonIcon(const QString& text) 00330 { 00331 if (!d->clearButton) { 00332 return; 00333 } 00334 if (isReadOnly()) { 00335 d->adjustForReadOnly(); 00336 return; 00337 } 00338 00339 int clearButtonState = KIconLoader::DefaultState; 00340 00341 if (d->wideEnoughForClear && text.length() > 0) { 00342 d->clearButton->animateVisible(true); 00343 } else { 00344 d->clearButton->animateVisible(false); 00345 } 00346 00347 if (!d->clearButton->pixmap().isNull()) { 00348 return; 00349 } 00350 00351 if (layoutDirection() == Qt::LeftToRight) { 00352 d->clearButton->setPixmap(SmallIcon("edit-clear-locationbar-rtl", 0, clearButtonState)); 00353 } else { 00354 d->clearButton->setPixmap(SmallIcon("edit-clear-locationbar-ltr", 0, clearButtonState)); 00355 } 00356 00357 d->clearButton->setVisible(text.length() > 0); 00358 } 00359 00360 // Determine geometry of clear button. Called initially, and on resizeEvent. 00361 void KLineEdit::updateClearButton() 00362 { 00363 if (!d->clearButton) { 00364 return; 00365 } 00366 if (isReadOnly()) { 00367 d->adjustForReadOnly(); 00368 return; 00369 } 00370 00371 const QSize geom = size(); 00372 const int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth,0,this); 00373 const int buttonWidth = d->clearButton->sizeHint().width(); 00374 const QSize newButtonSize(buttonWidth, geom.height()); 00375 const QFontMetrics fm(font()); 00376 const int em = fm.width("m"); 00377 00378 // make sure we have enough room for the clear button 00379 // no point in showing it if we can't also see a few characters as well 00380 const bool wideEnough = geom.width() > 4 * em + buttonWidth + frameWidth; 00381 00382 if (newButtonSize != d->clearButton->size()) { 00383 d->clearButton->resize(newButtonSize); 00384 } 00385 00386 if (d->style) { 00387 d->style.data()->m_overlap = wideEnough ? buttonWidth + frameWidth : 0; 00388 } 00389 00390 if (layoutDirection() == Qt::LeftToRight ) { 00391 d->clearButton->move(geom.width() - frameWidth - buttonWidth - 1, 0); 00392 } else { 00393 d->clearButton->move(frameWidth + 1, 0); 00394 } 00395 00396 if (wideEnough != d->wideEnoughForClear) { 00397 // we may (or may not) have been showing the button, but now our 00398 // positiong on that matter has shifted, so let's ensure that it 00399 // is properly visible (or not) 00400 d->wideEnoughForClear = wideEnough; 00401 updateClearButtonIcon(text()); 00402 } 00403 } 00404 00405 void KLineEdit::setCompletionMode( KGlobalSettings::Completion mode ) 00406 { 00407 KGlobalSettings::Completion oldMode = completionMode(); 00408 00409 if ( oldMode != mode && (oldMode == KGlobalSettings::CompletionPopup || 00410 oldMode == KGlobalSettings::CompletionPopupAuto ) && 00411 d->completionBox && d->completionBox->isVisible() ) 00412 d->completionBox->hide(); 00413 00414 // If the widgets echo mode is not Normal, no completion 00415 // feature will be enabled even if one is requested. 00416 if ( echoMode() != QLineEdit::Normal ) 00417 mode = KGlobalSettings::CompletionNone; // Override the request. 00418 00419 if ( kapp && !KAuthorized::authorize("lineedit_text_completion") ) 00420 mode = KGlobalSettings::CompletionNone; 00421 00422 if ( mode == KGlobalSettings::CompletionPopupAuto || 00423 mode == KGlobalSettings::CompletionAuto || 00424 mode == KGlobalSettings::CompletionMan ) 00425 d->autoSuggest = true; 00426 else 00427 d->autoSuggest = false; 00428 00429 KCompletionBase::setCompletionMode( mode ); 00430 } 00431 00432 void KLineEdit::setCompletionModeDisabled( KGlobalSettings::Completion mode, bool disable ) 00433 { 00434 d->disableCompletionMap[ mode ] = disable; 00435 } 00436 00437 void KLineEdit::setCompletedText( const QString& t, bool marked ) 00438 { 00439 if ( !d->autoSuggest ) 00440 return; 00441 00442 const QString txt = text(); 00443 00444 if ( t != txt ) 00445 { 00446 setText(t); 00447 if ( marked ) 00448 setSelection(t.length(), txt.length()-t.length()); 00449 setUserSelection(false); 00450 } 00451 else 00452 setUserSelection(true); 00453 00454 } 00455 00456 void KLineEdit::setCompletedText( const QString& text ) 00457 { 00458 KGlobalSettings::Completion mode = completionMode(); 00459 const bool marked = ( mode == KGlobalSettings::CompletionAuto || 00460 mode == KGlobalSettings::CompletionMan || 00461 mode == KGlobalSettings::CompletionPopup || 00462 mode == KGlobalSettings::CompletionPopupAuto ); 00463 setCompletedText( text, marked ); 00464 } 00465 00466 void KLineEdit::rotateText( KCompletionBase::KeyBindingType type ) 00467 { 00468 KCompletion* comp = compObj(); 00469 if ( comp && 00470 (type == KCompletionBase::PrevCompletionMatch || 00471 type == KCompletionBase::NextCompletionMatch ) ) 00472 { 00473 QString input; 00474 00475 if (type == KCompletionBase::PrevCompletionMatch) 00476 input = comp->previousMatch(); 00477 else 00478 input = comp->nextMatch(); 00479 00480 // Skip rotation if previous/next match is null or the same text 00481 if ( input.isEmpty() || input == displayText() ) 00482 return; 00483 setCompletedText( input, hasSelectedText() ); 00484 } 00485 } 00486 00487 void KLineEdit::makeCompletion( const QString& text ) 00488 { 00489 KCompletion *comp = compObj(); 00490 KGlobalSettings::Completion mode = completionMode(); 00491 00492 if ( !comp || mode == KGlobalSettings::CompletionNone ) 00493 return; // No completion object... 00494 00495 const QString match = comp->makeCompletion( text ); 00496 00497 if ( mode == KGlobalSettings::CompletionPopup || 00498 mode == KGlobalSettings::CompletionPopupAuto ) 00499 { 00500 if ( match.isEmpty() ) 00501 { 00502 if ( d->completionBox ) 00503 { 00504 d->completionBox->hide(); 00505 d->completionBox->clear(); 00506 } 00507 } 00508 else 00509 setCompletedItems( comp->allMatches() ); 00510 } 00511 else // Auto, ShortAuto (Man) and Shell 00512 { 00513 // all other completion modes 00514 // If no match or the same match, simply return without completing. 00515 if ( match.isEmpty() || match == text ) 00516 return; 00517 00518 if ( mode != KGlobalSettings::CompletionShell ) 00519 setUserSelection(false); 00520 00521 if ( d->autoSuggest ) 00522 setCompletedText( match ); 00523 } 00524 } 00525 00526 void KLineEdit::setReadOnly(bool readOnly) 00527 { 00528 // Do not do anything if nothing changed... 00529 if (readOnly == isReadOnly ()) { 00530 return; 00531 } 00532 00533 QLineEdit::setReadOnly(readOnly); 00534 00535 if (readOnly) { 00536 d->bgRole = backgroundRole(); 00537 setBackgroundRole(QPalette::Window); 00538 if (d->enableSqueezedText && d->squeezedText.isEmpty()) { 00539 d->squeezedText = text(); 00540 setSqueezedText(); 00541 } 00542 00543 if (d->clearButton) { 00544 d->clearButton->animateVisible(false); 00545 d->adjustForReadOnly(); 00546 } 00547 } else { 00548 if (!d->squeezedText.isEmpty()) { 00549 setText(d->squeezedText); 00550 d->squeezedText.clear(); 00551 } 00552 00553 setBackgroundRole(d->bgRole); 00554 updateClearButton(); 00555 } 00556 } 00557 00558 void KLineEdit::setSqueezedText( const QString &text) 00559 { 00560 setSqueezedTextEnabled(true); 00561 setText(text); 00562 } 00563 00564 void KLineEdit::setSqueezedTextEnabled( bool enable ) 00565 { 00566 d->enableSqueezedText = enable; 00567 } 00568 00569 bool KLineEdit::isSqueezedTextEnabled() const 00570 { 00571 return d->enableSqueezedText; 00572 } 00573 00574 void KLineEdit::setText( const QString& text ) 00575 { 00576 if( d->enableClickMsg ) 00577 { 00578 d->drawClickMsg = text.isEmpty(); 00579 update(); 00580 } 00581 if( d->enableSqueezedText && isReadOnly() ) 00582 { 00583 d->squeezedText = text; 00584 setSqueezedText(); 00585 return; 00586 } 00587 00588 QLineEdit::setText( text ); 00589 } 00590 00591 void KLineEdit::setSqueezedText() 00592 { 00593 d->squeezedStart = 0; 00594 d->squeezedEnd = 0; 00595 const QString fullText = d->squeezedText; 00596 const QFontMetrics fm(fontMetrics()); 00597 const int labelWidth = size().width() - 2*style()->pixelMetric(QStyle::PM_DefaultFrameWidth) - 2; 00598 const int textWidth = fm.width(fullText); 00599 00600 if (textWidth > labelWidth) 00601 { 00602 // start with the dots only 00603 QString squeezedText = "..."; 00604 int squeezedWidth = fm.width(squeezedText); 00605 00606 // estimate how many letters we can add to the dots on both sides 00607 int letters = fullText.length() * (labelWidth - squeezedWidth) / textWidth / 2; 00608 squeezedText = fullText.left(letters) + "..." + fullText.right(letters); 00609 squeezedWidth = fm.width(squeezedText); 00610 00611 if (squeezedWidth < labelWidth) 00612 { 00613 // we estimated too short 00614 // add letters while text < label 00615 do 00616 { 00617 letters++; 00618 squeezedText = fullText.left(letters) + "..." + fullText.right(letters); 00619 squeezedWidth = fm.width(squeezedText); 00620 } while (squeezedWidth < labelWidth); 00621 letters--; 00622 squeezedText = fullText.left(letters) + "..." + fullText.right(letters); 00623 } 00624 else if (squeezedWidth > labelWidth) 00625 { 00626 // we estimated too long 00627 // remove letters while text > label 00628 do 00629 { 00630 letters--; 00631 squeezedText = fullText.left(letters) + "..." + fullText.right(letters); 00632 squeezedWidth = fm.width(squeezedText); 00633 } while (squeezedWidth > labelWidth); 00634 } 00635 00636 if (letters < 5) 00637 { 00638 // too few letters added -> we give up squeezing 00639 QLineEdit::setText(fullText); 00640 } 00641 else 00642 { 00643 QLineEdit::setText(squeezedText); 00644 d->squeezedStart = letters; 00645 d->squeezedEnd = fullText.length() - letters; 00646 } 00647 00648 setToolTip( fullText ); 00649 00650 } 00651 else 00652 { 00653 QLineEdit::setText(fullText); 00654 00655 this->setToolTip( "" ); 00656 QToolTip::showText(pos(), QString()); // hide 00657 } 00658 00659 setCursorPosition(0); 00660 } 00661 00662 void KLineEdit::copy() const 00663 { 00664 if( !copySqueezedText(true)) 00665 QLineEdit::copy(); 00666 } 00667 00668 bool KLineEdit::copySqueezedText(bool clipboard) const 00669 { 00670 if (!d->squeezedText.isEmpty() && d->squeezedStart) 00671 { 00672 KLineEdit *that = const_cast<KLineEdit *>(this); 00673 if (!that->hasSelectedText()) 00674 return false; 00675 int start = selectionStart(), end = start + selectedText().length(); 00676 if (start >= d->squeezedStart+3) 00677 start = start - 3 - d->squeezedStart + d->squeezedEnd; 00678 else if (start > d->squeezedStart) 00679 start = d->squeezedStart; 00680 if (end >= d->squeezedStart+3) 00681 end = end - 3 - d->squeezedStart + d->squeezedEnd; 00682 else if (end > d->squeezedStart) 00683 end = d->squeezedEnd; 00684 if (start == end) 00685 return false; 00686 QString t = d->squeezedText; 00687 t = t.mid(start, end - start); 00688 disconnect( QApplication::clipboard(), SIGNAL(selectionChanged()), this, 0); 00689 QApplication::clipboard()->setText( t, clipboard ? QClipboard::Clipboard : QClipboard::Selection ); 00690 connect( QApplication::clipboard(), SIGNAL(selectionChanged()), this, 00691 SLOT(_q_clipboardChanged()) ); 00692 return true; 00693 } 00694 return false; 00695 } 00696 00697 void KLineEdit::resizeEvent( QResizeEvent * ev ) 00698 { 00699 if (!d->squeezedText.isEmpty()) 00700 setSqueezedText(); 00701 00702 updateClearButton(); 00703 QLineEdit::resizeEvent(ev); 00704 } 00705 00706 00707 void KLineEdit::keyPressEvent( QKeyEvent *e ) 00708 { 00709 const int key = e->key() | e->modifiers(); 00710 00711 if ( KStandardShortcut::copy().contains( key ) ) 00712 { 00713 copy(); 00714 return; 00715 } 00716 else if ( KStandardShortcut::paste().contains( key ) ) 00717 { 00718 // TODO: 00719 // we should restore the original text (not autocompleted), otherwise the paste 00720 // will get into troubles Bug: 134691 00721 if( !isReadOnly() ) 00722 paste(); 00723 return; 00724 } 00725 else if ( KStandardShortcut::pasteSelection().contains( key ) ) 00726 { 00727 QString text = QApplication::clipboard()->text( QClipboard::Selection); 00728 insert( text ); 00729 deselect(); 00730 return; 00731 } 00732 00733 else if ( KStandardShortcut::cut().contains( key ) ) 00734 { 00735 if( !isReadOnly() ) 00736 cut(); 00737 return; 00738 } 00739 else if ( KStandardShortcut::undo().contains( key ) ) 00740 { 00741 if( !isReadOnly() ) 00742 undo(); 00743 return; 00744 } 00745 else if ( KStandardShortcut::redo().contains( key ) ) 00746 { 00747 if( !isReadOnly() ) 00748 redo(); 00749 return; 00750 } 00751 else if ( KStandardShortcut::deleteWordBack().contains( key ) ) 00752 { 00753 cursorWordBackward(true); 00754 if ( hasSelectedText() ) 00755 del(); 00756 00757 e->accept(); 00758 return; 00759 } 00760 else if ( KStandardShortcut::deleteWordForward().contains( key ) ) 00761 { 00762 // Workaround for QT bug where 00763 cursorWordForward(true); 00764 if ( hasSelectedText() ) 00765 del(); 00766 00767 e->accept(); 00768 return; 00769 } 00770 else if ( KStandardShortcut::backwardWord().contains( key ) ) 00771 { 00772 cursorWordBackward(false); 00773 e->accept(); 00774 return; 00775 } 00776 else if ( KStandardShortcut::forwardWord().contains( key ) ) 00777 { 00778 cursorWordForward(false); 00779 e->accept(); 00780 return; 00781 } 00782 else if ( KStandardShortcut::beginningOfLine().contains( key ) ) 00783 { 00784 home(false); 00785 e->accept(); 00786 return; 00787 } 00788 else if ( KStandardShortcut::endOfLine().contains( key ) ) 00789 { 00790 end(false); 00791 e->accept(); 00792 return; 00793 } 00794 00795 00796 // Filter key-events if EchoMode is normal and 00797 // completion mode is not set to CompletionNone 00798 if ( echoMode() == QLineEdit::Normal && 00799 completionMode() != KGlobalSettings::CompletionNone ) 00800 { 00801 const KeyBindingMap keys = getKeyBindings(); 00802 const KGlobalSettings::Completion mode = completionMode(); 00803 const bool noModifier = (e->modifiers() == Qt::NoButton || 00804 e->modifiers() == Qt::ShiftModifier || 00805 e->modifiers() == Qt::KeypadModifier); 00806 00807 if ( (mode == KGlobalSettings::CompletionAuto || 00808 mode == KGlobalSettings::CompletionPopupAuto || 00809 mode == KGlobalSettings::CompletionMan) && noModifier ) 00810 { 00811 if ( !d->userSelection && hasSelectedText() && 00812 ( e->key() == Qt::Key_Right || e->key() == Qt::Key_Left ) && 00813 e->modifiers()==Qt::NoButton ) 00814 { 00815 const QString old_txt = text(); 00816 d->disableRestoreSelection = true; 00817 const int start = selectionStart(); 00818 00819 deselect(); 00820 QLineEdit::keyPressEvent ( e ); 00821 const int cPosition=cursorPosition(); 00822 setText(old_txt); 00823 00824 // keep cursor at cPosition 00825 setSelection(old_txt.length(), cPosition - old_txt.length()); 00826 if (e->key() == Qt::Key_Right && cPosition > start ) 00827 { 00828 //the user explicitly accepted the autocompletion 00829 d->_k_updateUserText(text()); 00830 } 00831 00832 d->disableRestoreSelection = false; 00833 return; 00834 } 00835 00836 if ( e->key() == Qt::Key_Escape ) 00837 { 00838 if (hasSelectedText() && !d->userSelection ) 00839 { 00840 del(); 00841 setUserSelection(true); 00842 } 00843 00844 // Don't swallow the Escape press event for the case 00845 // of dialogs, which have Escape associated to Cancel 00846 e->ignore(); 00847 return; 00848 } 00849 00850 } 00851 00852 if ( (mode == KGlobalSettings::CompletionAuto || 00853 mode == KGlobalSettings::CompletionMan) && noModifier ) 00854 { 00855 const QString keycode = e->text(); 00856 if ( !keycode.isEmpty() && (keycode.unicode()->isPrint() || 00857 e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Delete ) ) 00858 { 00859 const bool hasUserSelection=d->userSelection; 00860 const bool hadSelection=hasSelectedText(); 00861 00862 bool cursorNotAtEnd=false; 00863 00864 const int start = selectionStart(); 00865 const int cPos = cursorPosition(); 00866 00867 // When moving the cursor, we want to keep the autocompletion as an 00868 // autocompletion, so we want to process events at the cursor position 00869 // as if there was no selection. After processing the key event, we 00870 // can set the new autocompletion again. 00871 if ( hadSelection && !hasUserSelection && start>cPos ) 00872 { 00873 del(); 00874 setCursorPosition(cPos); 00875 cursorNotAtEnd=true; 00876 } 00877 00878 d->disableRestoreSelection = true; 00879 QLineEdit::keyPressEvent ( e ); 00880 d->disableRestoreSelection = false; 00881 00882 QString txt = text(); 00883 int len = txt.length(); 00884 if ( !hasSelectedText() && len /*&& cursorPosition() == len */) 00885 { 00886 if ( e->key() == Qt::Key_Backspace ) 00887 { 00888 if ( hadSelection && !hasUserSelection && !cursorNotAtEnd ) 00889 { 00890 backspace(); 00891 txt = text(); 00892 len = txt.length(); 00893 } 00894 00895 if (!d->s_backspacePerformsCompletion || !len) { 00896 d->autoSuggest = false; 00897 } 00898 } 00899 00900 if (e->key() == Qt::Key_Delete ) 00901 d->autoSuggest=false; 00902 00903 doCompletion(txt); 00904 00905 if( (e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Delete) ) 00906 d->autoSuggest=true; 00907 00908 e->accept(); 00909 } 00910 00911 return; 00912 } 00913 00914 } 00915 00916 else if (( mode == KGlobalSettings::CompletionPopup || 00917 mode == KGlobalSettings::CompletionPopupAuto ) && 00918 noModifier && !e->text().isEmpty() ) 00919 { 00920 const QString old_txt = text(); 00921 const bool hasUserSelection=d->userSelection; 00922 const bool hadSelection=hasSelectedText(); 00923 bool cursorNotAtEnd=false; 00924 00925 const int start = selectionStart(); 00926 const int cPos = cursorPosition(); 00927 const QString keycode = e->text(); 00928 00929 // When moving the cursor, we want to keep the autocompletion as an 00930 // autocompletion, so we want to process events at the cursor position 00931 // as if there was no selection. After processing the key event, we 00932 // can set the new autocompletion again. 00933 if (hadSelection && !hasUserSelection && start>cPos && 00934 ( (!keycode.isEmpty() && keycode.unicode()->isPrint()) || 00935 e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Delete ) ) 00936 { 00937 del(); 00938 setCursorPosition(cPos); 00939 cursorNotAtEnd=true; 00940 } 00941 00942 const int selectedLength=selectedText().length(); 00943 00944 d->disableRestoreSelection = true; 00945 QLineEdit::keyPressEvent ( e ); 00946 d->disableRestoreSelection = false; 00947 00948 if (( selectedLength != selectedText().length() ) && !hasUserSelection ) 00949 slotRestoreSelectionColors(); // and set userSelection to true 00950 00951 QString txt = text(); 00952 int len = txt.length(); 00953 if ( ( txt != old_txt || txt != e->text() ) && len/* && ( cursorPosition() == len || force )*/ && 00954 ( (!keycode.isEmpty() && keycode.unicode()->isPrint()) || 00955 e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Delete) ) 00956 { 00957 if ( e->key() == Qt::Key_Backspace ) 00958 { 00959 if ( hadSelection && !hasUserSelection && !cursorNotAtEnd ) 00960 { 00961 backspace(); 00962 txt = text(); 00963 len = txt.length(); 00964 } 00965 00966 if (!d->s_backspacePerformsCompletion) { 00967 d->autoSuggest = false; 00968 } 00969 } 00970 00971 if (e->key() == Qt::Key_Delete ) 00972 d->autoSuggest=false; 00973 00974 if ( d->completionBox ) 00975 d->completionBox->setCancelledText( txt ); 00976 00977 doCompletion(txt); 00978 00979 if ( (e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Delete ) && 00980 mode == KGlobalSettings::CompletionPopupAuto ) 00981 d->autoSuggest=true; 00982 00983 e->accept(); 00984 } 00985 else if (!len && d->completionBox && d->completionBox->isVisible()) 00986 d->completionBox->hide(); 00987 00988 return; 00989 } 00990 00991 else if ( mode == KGlobalSettings::CompletionShell ) 00992 { 00993 // Handles completion. 00994 KShortcut cut; 00995 if ( keys[TextCompletion].isEmpty() ) 00996 cut = KStandardShortcut::shortcut(KStandardShortcut::TextCompletion); 00997 else 00998 cut = keys[TextCompletion]; 00999 01000 if ( cut.contains( key ) ) 01001 { 01002 // Emit completion if the completion mode is CompletionShell 01003 // and the cursor is at the end of the string. 01004 const QString txt = text(); 01005 const int len = txt.length(); 01006 if ( cursorPosition() == len && len != 0 ) 01007 { 01008 doCompletion(txt); 01009 return; 01010 } 01011 } 01012 else if ( d->completionBox ) 01013 d->completionBox->hide(); 01014 } 01015 01016 // handle rotation 01017 if ( mode != KGlobalSettings::CompletionNone ) 01018 { 01019 // Handles previous match 01020 KShortcut cut; 01021 if ( keys[PrevCompletionMatch].isEmpty() ) 01022 cut = KStandardShortcut::shortcut(KStandardShortcut::PrevCompletion); 01023 else 01024 cut = keys[PrevCompletionMatch]; 01025 01026 if ( cut.contains( key ) ) 01027 { 01028 if ( emitSignals() ) 01029 emit textRotation( KCompletionBase::PrevCompletionMatch ); 01030 if ( handleSignals() ) 01031 rotateText( KCompletionBase::PrevCompletionMatch ); 01032 return; 01033 } 01034 01035 // Handles next match 01036 if ( keys[NextCompletionMatch].isEmpty() ) 01037 cut = KStandardShortcut::shortcut(KStandardShortcut::NextCompletion); 01038 else 01039 cut = keys[NextCompletionMatch]; 01040 01041 if ( cut.contains( key ) ) 01042 { 01043 if ( emitSignals() ) 01044 emit textRotation( KCompletionBase::NextCompletionMatch ); 01045 if ( handleSignals() ) 01046 rotateText( KCompletionBase::NextCompletionMatch ); 01047 return; 01048 } 01049 } 01050 01051 // substring completion 01052 if ( compObj() ) 01053 { 01054 KShortcut cut; 01055 if ( keys[SubstringCompletion].isEmpty() ) 01056 cut = KStandardShortcut::shortcut(KStandardShortcut::SubstringCompletion); 01057 else 01058 cut = keys[SubstringCompletion]; 01059 01060 if ( cut.contains( key ) ) 01061 { 01062 if ( emitSignals() ) 01063 emit substringCompletion( text() ); 01064 if ( handleSignals() ) 01065 { 01066 setCompletedItems( compObj()->substringCompletion(text())); 01067 e->accept(); 01068 } 01069 return; 01070 } 01071 } 01072 } 01073 const int selectedLength = selectedText().length(); 01074 01075 // Let QLineEdit handle any other keys events. 01076 QLineEdit::keyPressEvent ( e ); 01077 01078 if ( selectedLength != selectedText().length() ) 01079 slotRestoreSelectionColors(); // and set userSelection to true 01080 } 01081 01082 void KLineEdit::mouseDoubleClickEvent( QMouseEvent* e ) 01083 { 01084 if ( e->button() == Qt::LeftButton ) 01085 { 01086 d->possibleTripleClick=true; 01087 QTimer::singleShot( QApplication::doubleClickInterval(),this, 01088 SLOT(tripleClickTimeout()) ); 01089 } 01090 QLineEdit::mouseDoubleClickEvent( e ); 01091 } 01092 01093 void KLineEdit::mousePressEvent( QMouseEvent* e ) 01094 { 01095 if ( (e->button() == Qt::LeftButton || 01096 e->button() == Qt::MidButton ) && 01097 d->clearButton ) { 01098 d->clickInClear = d->clearButton == childAt( e->pos() ); 01099 01100 if ( d->clickInClear ) { 01101 d->possibleTripleClick = false; 01102 } 01103 } 01104 01105 if ( e->button() == Qt::LeftButton && d->possibleTripleClick ) { 01106 selectAll(); 01107 e->accept(); 01108 return; 01109 } 01110 01111 QLineEdit::mousePressEvent( e ); 01112 } 01113 01114 void KLineEdit::mouseReleaseEvent( QMouseEvent* e ) 01115 { 01116 if ( d->clickInClear ) { 01117 if ( d->clearButton == childAt( e->pos() ) ) { 01118 QString newText; 01119 if ( e->button() == Qt::MidButton ) { 01120 newText = QApplication::clipboard()->text( QClipboard::Selection ); 01121 setText( newText ); 01122 } else { 01123 setSelection(0, text().size()); 01124 del(); 01125 emit clearButtonClicked(); 01126 } 01127 emit textChanged( newText ); 01128 } 01129 01130 d->clickInClear = false; 01131 e->accept(); 01132 return; 01133 } 01134 01135 QLineEdit::mouseReleaseEvent( e ); 01136 01137 if (QApplication::clipboard()->supportsSelection() ) { 01138 if ( e->button() == Qt::LeftButton ) { 01139 // Fix copying of squeezed text if needed 01140 copySqueezedText( false ); 01141 } 01142 } 01143 } 01144 01145 void KLineEdit::tripleClickTimeout() 01146 { 01147 d->possibleTripleClick=false; 01148 } 01149 01150 QMenu* KLineEdit::createStandardContextMenu() 01151 { 01152 QMenu *popup = QLineEdit::createStandardContextMenu(); 01153 01154 if( !isReadOnly() ) 01155 { 01156 // FIXME: This code depends on Qt's action ordering. 01157 const QList<QAction *> actionList = popup->actions(); 01158 enum { UndoAct, RedoAct, Separator1, CutAct, CopyAct, PasteAct, DeleteAct, ClearAct, 01159 Separator2, SelectAllAct, NCountActs }; 01160 QAction *separatorAction = 0L; 01161 // separator we want is right after Delete right now. 01162 const int idx = actionList.indexOf( actionList[DeleteAct] ) + 1; 01163 if ( idx < actionList.count() ) 01164 separatorAction = actionList.at( idx ); 01165 if ( separatorAction ) 01166 { 01167 KAction *clearAllAction = KStandardAction::clear( this, SLOT( clear() ), this) ; 01168 if ( text().isEmpty() ) 01169 clearAllAction->setEnabled( false ); 01170 popup->insertAction( separatorAction, clearAllAction ); 01171 } 01172 } 01173 01174 KIconTheme::assignIconsToContextMenu( KIconTheme::TextEditor, popup->actions () ); 01175 01176 // If a completion object is present and the input 01177 // widget is not read-only, show the Text Completion 01178 // menu item. 01179 if ( compObj() && !isReadOnly() && KAuthorized::authorize("lineedit_text_completion") ) 01180 { 01181 QMenu *subMenu = popup->addMenu( KIcon("text-completion"), i18nc("@title:menu", "Text Completion") ); 01182 connect( subMenu, SIGNAL( triggered ( QAction* ) ), 01183 this, SLOT( completionMenuActivated( QAction* ) ) ); 01184 01185 popup->addSeparator(); 01186 01187 QActionGroup* ag = new QActionGroup( this ); 01188 d->noCompletionAction = ag->addAction( i18nc("@item:inmenu Text Completion", "None")); 01189 d->shellCompletionAction = ag->addAction( i18nc("@item:inmenu Text Completion", "Manual") ); 01190 d->autoCompletionAction = ag->addAction( i18nc("@item:inmenu Text Completion", "Automatic") ); 01191 d->popupCompletionAction = ag->addAction( i18nc("@item:inmenu Text Completion", "Dropdown List") ); 01192 d->shortAutoCompletionAction = ag->addAction( i18nc("@item:inmenu Text Completion", "Short Automatic") ); 01193 d->popupAutoCompletionAction = ag->addAction( i18nc("@item:inmenu Text Completion", "Dropdown List && Automatic")); 01194 subMenu->addActions( ag->actions() ); 01195 01196 //subMenu->setAccel( KStandardShortcut::completion(), ShellCompletion ); 01197 01198 d->shellCompletionAction->setCheckable( true ); 01199 d->noCompletionAction->setCheckable( true ); 01200 d->popupCompletionAction->setCheckable( true ); 01201 d->autoCompletionAction->setCheckable( true ); 01202 d->shortAutoCompletionAction->setCheckable( true ); 01203 d->popupAutoCompletionAction->setCheckable( true ); 01204 01205 d->shellCompletionAction->setEnabled( !d->disableCompletionMap[ KGlobalSettings::CompletionShell ] ); 01206 d->noCompletionAction->setEnabled( !d->disableCompletionMap[ KGlobalSettings::CompletionNone ] ); 01207 d->popupCompletionAction->setEnabled( !d->disableCompletionMap[ KGlobalSettings::CompletionPopup ] ); 01208 d->autoCompletionAction->setEnabled( !d->disableCompletionMap[ KGlobalSettings::CompletionAuto ] ); 01209 d->shortAutoCompletionAction->setEnabled( !d->disableCompletionMap[ KGlobalSettings::CompletionMan ] ); 01210 d->popupAutoCompletionAction->setEnabled( !d->disableCompletionMap[ KGlobalSettings::CompletionPopupAuto ] ); 01211 01212 const KGlobalSettings::Completion mode = completionMode(); 01213 d->noCompletionAction->setChecked( mode == KGlobalSettings::CompletionNone ); 01214 d->shellCompletionAction->setChecked( mode == KGlobalSettings::CompletionShell ); 01215 d->popupCompletionAction->setChecked( mode == KGlobalSettings::CompletionPopup ); 01216 d->autoCompletionAction->setChecked( mode == KGlobalSettings::CompletionAuto ); 01217 d->shortAutoCompletionAction->setChecked( mode == KGlobalSettings::CompletionMan ); 01218 d->popupAutoCompletionAction->setChecked( mode == KGlobalSettings::CompletionPopupAuto ); 01219 01220 const KGlobalSettings::Completion defaultMode = KGlobalSettings::completionMode(); 01221 if ( mode != defaultMode && !d->disableCompletionMap[ defaultMode ] ) 01222 { 01223 subMenu->addSeparator(); 01224 d->defaultAction = subMenu->addAction( i18nc("@item:inmenu Text Completion", "Default") ); 01225 } 01226 } 01227 01228 return popup; 01229 } 01230 01231 void KLineEdit::contextMenuEvent( QContextMenuEvent *e ) 01232 { 01233 if ( QLineEdit::contextMenuPolicy() != Qt::DefaultContextMenu ) 01234 return; 01235 QMenu *popup = createStandardContextMenu(); 01236 01237 // ### do we really need this? Yes, Please do not remove! This 01238 // allows applications to extend the popup menu without having to 01239 // inherit from this class! (DA) 01240 emit aboutToShowContextMenu( popup ); 01241 01242 popup->exec(e->globalPos()); 01243 delete popup; 01244 } 01245 01246 void KLineEdit::completionMenuActivated( QAction *act) 01247 { 01248 KGlobalSettings::Completion oldMode = completionMode(); 01249 01250 if( act == d->noCompletionAction ) 01251 { 01252 setCompletionMode( KGlobalSettings::CompletionNone ); 01253 } 01254 else if( act == d->shellCompletionAction) 01255 { 01256 setCompletionMode( KGlobalSettings::CompletionShell ); 01257 } 01258 else if( act == d->autoCompletionAction) 01259 { 01260 setCompletionMode( KGlobalSettings::CompletionAuto ); 01261 } 01262 else if( act == d->popupCompletionAction) 01263 { 01264 setCompletionMode( KGlobalSettings::CompletionPopup ); 01265 } 01266 else if( act == d->shortAutoCompletionAction) 01267 { 01268 setCompletionMode( KGlobalSettings::CompletionMan ); 01269 } 01270 else if( act == d->popupAutoCompletionAction) 01271 { 01272 setCompletionMode( KGlobalSettings::CompletionPopupAuto ); 01273 } 01274 else if( act == d->defaultAction ) 01275 { 01276 setCompletionMode( KGlobalSettings::completionMode() ); 01277 } 01278 else 01279 return; 01280 01281 if ( oldMode != completionMode() ) 01282 { 01283 if ( (oldMode == KGlobalSettings::CompletionPopup || 01284 oldMode == KGlobalSettings::CompletionPopupAuto ) && 01285 d->completionBox && d->completionBox->isVisible() ) 01286 d->completionBox->hide(); 01287 emit completionModeChanged( completionMode() ); 01288 } 01289 } 01290 01291 void KLineEdit::dropEvent(QDropEvent *e) 01292 { 01293 if( d->handleURLDrops ) 01294 { 01295 const KUrl::List urlList = KUrl::List::fromMimeData( e->mimeData() ); 01296 if ( !urlList.isEmpty() ) 01297 { 01298 // Let's replace the current text with the dropped URL(s), rather than appending. 01299 // Makes more sense in general (#188129), e.g. konq location bar and kurlrequester 01300 // can only hold one url anyway. OK this code supports multiple urls being dropped, 01301 // but that's not the common case [and it breaks if they contain spaces... this is why 01302 // kfiledialog uses double quotes around filenames in multiple-selection mode]... 01303 // 01304 // Anyway, if some apps prefer "append" then we should have a 01305 // setUrlDropsSupport( {NoUrlDrops, SingleUrlDrops, MultipleUrlDrops} ) 01306 // where Single replaces and Multiple appends. 01307 QString dropText; 01308 //QString dropText = text(); 01309 KUrl::List::ConstIterator it; 01310 for( it = urlList.begin() ; it != urlList.end() ; ++it ) 01311 { 01312 if(!dropText.isEmpty()) 01313 dropText+=' '; 01314 01315 dropText += (*it).prettyUrl(); 01316 } 01317 01318 setText(dropText); 01319 setCursorPosition(dropText.length()); 01320 01321 e->accept(); 01322 return; 01323 } 01324 } 01325 QLineEdit::dropEvent(e); 01326 } 01327 01328 bool KLineEdit::event( QEvent* ev ) 01329 { 01330 KCursor::autoHideEventFilter( this, ev ); 01331 if ( ev->type() == QEvent::ShortcutOverride ) 01332 { 01333 QKeyEvent *e = static_cast<QKeyEvent *>( ev ); 01334 if (d->overrideShortcut(e)) { 01335 ev->accept(); 01336 } 01337 } else if( ev->type() == QEvent::KeyPress ) { 01338 // Hmm -- all this could be done in keyPressEvent too... 01339 01340 QKeyEvent *e = static_cast<QKeyEvent *>( ev ); 01341 01342 if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) { 01343 const bool trap = d->completionBox && d->completionBox->isVisible(); 01344 01345 const bool stopEvent = trap || (d->grabReturnKeyEvents && 01346 (e->modifiers() == Qt::NoButton || 01347 e->modifiers() == Qt::KeypadModifier)); 01348 01349 // Qt will emit returnPressed() itself if we return false 01350 if (stopEvent) { 01351 emit QLineEdit::returnPressed(); 01352 e->accept(); 01353 } 01354 01355 emit returnPressed( displayText() ); 01356 01357 if (trap) { 01358 d->completionBox->hide(); 01359 deselect(); 01360 setCursorPosition(text().length()); 01361 } 01362 01363 // Eat the event if the user asked for it, or if a completionbox was visible 01364 if (stopEvent) { 01365 return true; 01366 } 01367 } 01368 } else if (ev->type() == QEvent::ApplicationPaletteChange 01369 || ev->type() == QEvent::PaletteChange) { 01370 // Assume the widget uses the application's palette 01371 QPalette p = QApplication::palette(); 01372 d->previousHighlightedTextColor=p.color(QPalette::Normal,QPalette::HighlightedText); 01373 d->previousHighlightColor=p.color(QPalette::Normal,QPalette::Highlight); 01374 setUserSelection(d->userSelection); 01375 } else if (ev->type() == QEvent::StyleChange) { 01376 // since we have our own style and it relies on this style to Get Things Right, 01377 // if a style is set specifically on the widget (which would replace our own style!) 01378 // hang on to this special style and re-instate our own style. 01379 //FIXME: Qt currently has a grave bug where already deleted QStyleSheetStyle objects 01380 // will get passed back in if we set a new style on it here. remove the qstrmcp test 01381 // when this is fixed in Qt (or a better approach is found) 01382 if (!qobject_cast<KLineEditStyle *>(style()) && 01383 qstrcmp(style()->metaObject()->className(), "QStyleSheetStyle") != 0 && 01384 QLatin1String(style()->metaObject()->className()) != d->lastStyleClass) { 01385 KLineEditStyle *kleStyle = d->style.data(); 01386 if (!kleStyle) { 01387 d->style = kleStyle = new KLineEditStyle(this); 01388 } 01389 01390 kleStyle->m_subStyle = style(); 01391 // this guards against "wrap around" where another style, e.g. QStyleSheetStyle, 01392 // is setting the style on QEvent::StyleChange 01393 d->lastStyleClass = QLatin1String(style()->metaObject()->className()); 01394 setStyle(kleStyle); 01395 d->lastStyleClass.clear(); 01396 } 01397 } 01398 01399 return QLineEdit::event( ev ); 01400 } 01401 01402 01403 void KLineEdit::setUrlDropsEnabled(bool enable) 01404 { 01405 d->handleURLDrops=enable; 01406 } 01407 01408 bool KLineEdit::urlDropsEnabled() const 01409 { 01410 return d->handleURLDrops; 01411 } 01412 01413 void KLineEdit::setTrapReturnKey( bool grab ) 01414 { 01415 d->grabReturnKeyEvents = grab; 01416 } 01417 01418 bool KLineEdit::trapReturnKey() const 01419 { 01420 return d->grabReturnKeyEvents; 01421 } 01422 01423 void KLineEdit::setUrl( const KUrl& url ) 01424 { 01425 setText( url.prettyUrl() ); 01426 } 01427 01428 void KLineEdit::setCompletionBox( KCompletionBox *box ) 01429 { 01430 if ( d->completionBox ) 01431 return; 01432 01433 d->completionBox = box; 01434 if ( handleSignals() ) 01435 { 01436 connect( d->completionBox, SIGNAL(currentTextChanged( const QString& )), 01437 SLOT(_k_slotCompletionBoxTextChanged( const QString& )) ); 01438 connect( d->completionBox, SIGNAL(userCancelled( const QString& )), 01439 SLOT(userCancelled( const QString& )) ); 01440 connect( d->completionBox, SIGNAL(activated(QString)), 01441 SIGNAL(completionBoxActivated(QString)) ); 01442 } 01443 } 01444 01445 void KLineEdit::userCancelled(const QString & cancelText) 01446 { 01447 if ( completionMode() != KGlobalSettings::CompletionPopupAuto ) 01448 { 01449 // TODO: this sets modified==false. But maybe it was true before... 01450 setText(cancelText); 01451 } 01452 else if (hasSelectedText() ) 01453 { 01454 if (d->userSelection) 01455 deselect(); 01456 else 01457 { 01458 d->autoSuggest=false; 01459 const int start = selectionStart() ; 01460 const QString s=text().remove(selectionStart(), selectedText().length()); 01461 setText(s); 01462 setCursorPosition(start); 01463 d->autoSuggest=true; 01464 } 01465 } 01466 } 01467 01468 bool KLineEditPrivate::overrideShortcut(const QKeyEvent* e) 01469 { 01470 KShortcut scKey; 01471 01472 const int key = e->key() | e->modifiers(); 01473 const KLineEdit::KeyBindingMap keys = q->getKeyBindings(); 01474 01475 if (keys[KLineEdit::TextCompletion].isEmpty()) 01476 scKey = KStandardShortcut::shortcut(KStandardShortcut::TextCompletion); 01477 else 01478 scKey = keys[KLineEdit::TextCompletion]; 01479 01480 if (scKey.contains( key )) 01481 return true; 01482 01483 if (keys[KLineEdit::NextCompletionMatch].isEmpty()) 01484 scKey = KStandardShortcut::shortcut(KStandardShortcut::NextCompletion); 01485 else 01486 scKey = keys[KLineEdit::NextCompletionMatch]; 01487 01488 if (scKey.contains( key )) 01489 return true; 01490 01491 if (keys[KLineEdit::PrevCompletionMatch].isEmpty()) 01492 scKey = KStandardShortcut::shortcut(KStandardShortcut::PrevCompletion); 01493 else 01494 scKey = keys[KLineEdit::PrevCompletionMatch]; 01495 01496 if (scKey.contains( key )) 01497 return true; 01498 01499 // Override all the text manupilation accelerators... 01500 if ( KStandardShortcut::copy().contains( key ) ) 01501 return true; 01502 else if ( KStandardShortcut::paste().contains( key ) ) 01503 return true; 01504 else if ( KStandardShortcut::cut().contains( key ) ) 01505 return true; 01506 else if ( KStandardShortcut::undo().contains( key ) ) 01507 return true; 01508 else if ( KStandardShortcut::redo().contains( key ) ) 01509 return true; 01510 else if (KStandardShortcut::deleteWordBack().contains( key )) 01511 return true; 01512 else if (KStandardShortcut::deleteWordForward().contains( key )) 01513 return true; 01514 else if (KStandardShortcut::forwardWord().contains( key )) 01515 return true; 01516 else if (KStandardShortcut::backwardWord().contains( key )) 01517 return true; 01518 else if (KStandardShortcut::beginningOfLine().contains( key )) 01519 return true; 01520 else if (KStandardShortcut::endOfLine().contains( key )) 01521 return true; 01522 01523 // Shortcut overrides for shortcuts that QLineEdit handles 01524 // but doesn't dare force as "stronger than kaction shortcuts"... 01525 else if (e->matches(QKeySequence::SelectAll)) { 01526 return true; 01527 } 01528 #ifdef Q_WS_X11 01529 else if (key == Qt::CTRL + Qt::Key_E || key == Qt::CTRL + Qt::Key_U) 01530 return true; 01531 #endif 01532 01533 if (completionBox && completionBox->isVisible ()) 01534 { 01535 const int key = e->key(); 01536 const Qt::KeyboardModifiers modifiers = e->modifiers(); 01537 if ((key == Qt::Key_Backtab || key == Qt::Key_Tab) && 01538 (modifiers == Qt::NoModifier || (modifiers & Qt::ShiftModifier))) 01539 { 01540 return true; 01541 } 01542 } 01543 01544 01545 return false; 01546 } 01547 01548 void KLineEdit::setCompletedItems( const QStringList& items, bool autoSuggest ) 01549 { 01550 QString txt; 01551 if ( d->completionBox && d->completionBox->isVisible() ) { 01552 // The popup is visible already - do the matching on the initial string, 01553 // not on the currently selected one. 01554 txt = completionBox()->cancelledText(); 01555 } else { 01556 txt = text(); 01557 } 01558 01559 if ( !items.isEmpty() && 01560 !(items.count() == 1 && txt == items.first()) ) 01561 { 01562 // create completion box if non-existent 01563 completionBox(); 01564 01565 if ( d->completionBox->isVisible() ) 01566 { 01567 QListWidgetItem* currentItem = d->completionBox->currentItem(); 01568 01569 QString currentSelection; 01570 if ( currentItem != 0 ) { 01571 currentSelection = currentItem->text(); 01572 } 01573 01574 d->completionBox->setItems( items ); 01575 01576 const QList<QListWidgetItem*> matchedItems = d->completionBox->findItems(currentSelection, Qt::MatchExactly); 01577 QListWidgetItem* matchedItem = matchedItems.isEmpty() ? 0 : matchedItems.first(); 01578 01579 if (matchedItem) { 01580 const bool blocked = d->completionBox->blockSignals( true ); 01581 d->completionBox->setCurrentItem( matchedItem ); 01582 d->completionBox->blockSignals( blocked ); 01583 } else { 01584 d->completionBox->setCurrentRow(-1); 01585 } 01586 } 01587 else // completion box not visible yet -> show it 01588 { 01589 if ( !txt.isEmpty() ) 01590 d->completionBox->setCancelledText( txt ); 01591 d->completionBox->setItems( items ); 01592 d->completionBox->popup(); 01593 } 01594 01595 if ( d->autoSuggest && autoSuggest ) 01596 { 01597 const int index = items.first().indexOf( txt ); 01598 const QString newText = items.first().mid( index ); 01599 setUserSelection(false); // can be removed? setCompletedText sets it anyway 01600 setCompletedText(newText,true); 01601 } 01602 } 01603 else 01604 { 01605 if ( d->completionBox && d->completionBox->isVisible() ) 01606 d->completionBox->hide(); 01607 } 01608 } 01609 01610 KCompletionBox * KLineEdit::completionBox( bool create ) 01611 { 01612 if ( create && !d->completionBox ) { 01613 setCompletionBox( new KCompletionBox( this ) ); 01614 d->completionBox->setObjectName("completion box"); 01615 d->completionBox->setFont(font()); 01616 } 01617 01618 return d->completionBox; 01619 } 01620 01621 void KLineEdit::setCompletionObject( KCompletion* comp, bool hsig ) 01622 { 01623 KCompletion *oldComp = compObj(); 01624 if ( oldComp && handleSignals() ) 01625 disconnect( oldComp, SIGNAL( matches( const QStringList& )), 01626 this, SLOT( setCompletedItems( const QStringList& ))); 01627 01628 if ( comp && hsig ) 01629 connect( comp, SIGNAL( matches( const QStringList& )), 01630 this, SLOT( setCompletedItems( const QStringList& ))); 01631 01632 KCompletionBase::setCompletionObject( comp, hsig ); 01633 } 01634 01635 // QWidget::create() turns off mouse-Tracking which would break auto-hiding 01636 void KLineEdit::create( WId id, bool initializeWindow, bool destroyOldWindow ) 01637 { 01638 QLineEdit::create( id, initializeWindow, destroyOldWindow ); 01639 KCursor::setAutoHideCursor( this, true, true ); 01640 } 01641 01642 void KLineEdit::setUserSelection(bool userSelection) 01643 { 01644 //if !d->userSelection && userSelection we are accepting a completion, 01645 //so trigger an update 01646 01647 if (!d->userSelection && userSelection) 01648 { 01649 d->_k_updateUserText(text()); 01650 } 01651 01652 QPalette p = palette(); 01653 01654 if (userSelection) 01655 { 01656 p.setColor(QPalette::Highlight, d->previousHighlightColor); 01657 p.setColor(QPalette::HighlightedText, d->previousHighlightedTextColor); 01658 } 01659 else 01660 { 01661 QColor color=p.color(QPalette::Disabled, QPalette::Text); 01662 p.setColor(QPalette::HighlightedText, color); 01663 color=p.color(QPalette::Active, QPalette::Base); 01664 p.setColor(QPalette::Highlight, color); 01665 } 01666 01667 d->userSelection=userSelection; 01668 setPalette(p); 01669 } 01670 01671 void KLineEdit::slotRestoreSelectionColors() 01672 { 01673 if (d->disableRestoreSelection) 01674 return; 01675 01676 setUserSelection(true); 01677 } 01678 01679 void KLineEdit::clear() 01680 { 01681 setText( QString() ); 01682 } 01683 01684 void KLineEdit::_k_slotCompletionBoxTextChanged( const QString& text ) 01685 { 01686 if (!text.isEmpty()) 01687 { 01688 setText( text ); 01689 setModified(true); 01690 emit textEdited(text); 01691 end( false ); // force cursor at end 01692 } 01693 } 01694 01695 QString KLineEdit::originalText() const 01696 { 01697 if ( d->enableSqueezedText && isReadOnly() ) 01698 return d->squeezedText; 01699 01700 return text(); 01701 } 01702 01703 QString KLineEdit::userText() const 01704 { 01705 return d->userText; 01706 } 01707 01708 bool KLineEdit::autoSuggest() const 01709 { 01710 return d->autoSuggest; 01711 } 01712 01713 void KLineEdit::paintEvent( QPaintEvent *ev ) 01714 { 01715 if (echoMode() == Password && d->threeStars) { 01716 // ### hack alert! 01717 // QLineEdit has currently no hooks to modify the displayed string. 01718 // When we call setText(), an update() is triggered and we get 01719 // into an infinite recursion. 01720 // Qt offers the setUpdatesEnabled() method, but when we re-enable 01721 // them, update() is triggered, and we get into the same recursion. 01722 // To work around this problem, we set/clear the internal Qt flag which 01723 // marks the updatesDisabled state manually. 01724 setAttribute(Qt::WA_UpdatesDisabled, true); 01725 blockSignals(true); 01726 const QString oldText = text(); 01727 const bool isModifiedState = isModified(); // save modified state because setText resets it 01728 setText(oldText + oldText + oldText); 01729 QLineEdit::paintEvent(ev); 01730 setText(oldText); 01731 setModified(isModifiedState); 01732 blockSignals(false); 01733 setAttribute(Qt::WA_UpdatesDisabled, false); 01734 } else { 01735 QLineEdit::paintEvent( ev ); 01736 } 01737 01738 if (d->enableClickMsg && d->drawClickMsg && !hasFocus() && text().isEmpty()) { 01739 QPainter p(this); 01740 QFont f = font(); 01741 f.setItalic(d->italicizePlaceholder); 01742 p.setFont(f); 01743 01744 QColor color(palette().color(foregroundRole())); 01745 color.setAlphaF(0.5); 01746 p.setPen(color); 01747 01748 QStyleOptionFrame opt; 01749 initStyleOption(&opt); 01750 QRect cr = style()->subElementRect(QStyle::SE_LineEditContents, &opt, this); 01751 01752 // this is copied/adapted from QLineEdit::paintEvent 01753 const int verticalMargin(1); 01754 const int horizontalMargin(2); 01755 01756 int left, top, right, bottom; 01757 getTextMargins( &left, &top, &right, &bottom ); 01758 cr.adjust( left, top, -right, -bottom ); 01759 01760 p.setClipRect(cr); 01761 01762 QFontMetrics fm = fontMetrics(); 01763 Qt::Alignment va = alignment() & Qt::AlignVertical_Mask; 01764 int vscroll; 01765 switch (va & Qt::AlignVertical_Mask) 01766 { 01767 case Qt::AlignBottom: 01768 vscroll = cr.y() + cr.height() - fm.height() - verticalMargin; 01769 break; 01770 01771 case Qt::AlignTop: 01772 vscroll = cr.y() + verticalMargin; 01773 break; 01774 01775 default: 01776 vscroll = cr.y() + (cr.height() - fm.height() + 1) / 2; 01777 break; 01778 01779 } 01780 01781 QRect lineRect(cr.x() + horizontalMargin, vscroll, cr.width() - 2*horizontalMargin, fm.height()); 01782 p.drawText(lineRect, Qt::AlignLeft|Qt::AlignVCenter, d->clickMessage); 01783 01784 } 01785 } 01786 01787 void KLineEdit::focusInEvent( QFocusEvent *ev ) 01788 { 01789 if ( d->enableClickMsg && d->drawClickMsg ) 01790 { 01791 d->drawClickMsg = false; 01792 update(); 01793 } 01794 QLineEdit::focusInEvent( ev ); 01795 } 01796 01797 void KLineEdit::focusOutEvent( QFocusEvent *ev ) 01798 { 01799 if ( d->enableClickMsg && text().isEmpty() ) 01800 { 01801 d->drawClickMsg = true; 01802 update(); 01803 } 01804 QLineEdit::focusOutEvent( ev ); 01805 } 01806 01807 void KLineEdit::setClickMessage( const QString &msg ) 01808 { 01809 d->enableClickMsg = !msg.isEmpty(); 01810 d->clickMessage = msg; 01811 d->drawClickMsg = text().isEmpty(); 01812 update(); 01813 } 01814 01815 #ifndef KDE_NO_DEPRECATED 01816 void KLineEdit::setContextMenuEnabled( bool showMenu ) 01817 { 01818 QLineEdit::setContextMenuPolicy( showMenu ? Qt::DefaultContextMenu : Qt::NoContextMenu ); 01819 } 01820 #endif 01821 01822 #ifndef KDE_NO_DEPRECATED 01823 bool KLineEdit::isContextMenuEnabled() const 01824 { 01825 return ( contextMenuPolicy() == Qt::DefaultContextMenu ); 01826 } 01827 #endif 01828 01829 void KLineEdit::setPasswordMode(bool b) 01830 { 01831 if(b) 01832 { 01833 KConfigGroup cg(KGlobal::config(), "Passwords"); 01834 const QString val = cg.readEntry("EchoMode", "OneStar"); 01835 if (val == "NoEcho") 01836 setEchoMode(NoEcho); 01837 else { 01838 d->threeStars = (val == "ThreeStars"); 01839 setEchoMode(Password); 01840 } 01841 } 01842 else 01843 { 01844 setEchoMode( Normal ); 01845 } 01846 } 01847 01848 bool KLineEdit::passwordMode() const 01849 { 01850 return echoMode() == NoEcho || echoMode() == Password; 01851 } 01852 01853 void KLineEdit::doCompletion(const QString& txt) 01854 { 01855 if (emitSignals()) { 01856 emit completion(txt); // emit when requested... 01857 } 01858 d->completionRunning = true; 01859 if (handleSignals()) { 01860 makeCompletion(txt); // handle when requested... 01861 } 01862 d->completionRunning = false; 01863 } 01864 01865 #include "klineedit.moc" 01866 #include "klineedit_p.moc" 01867
KDE 4.6 API Reference