1/* This file is part of the KDE libraries
2
3 This class was originally inspired by Torben Weis'
4 fileentry.cpp for KFM II.
5
6 Copyright (C) 1997 Sven Radej <sven.radej@iname.com>
7 Copyright (c) 1999 Patrick Ward <PAT_WARD@HP-USA-om5.om.hp.com>
8 Copyright (c) 1999 Preston Brown <pbrown@kde.org>
9
10 Completely re-designed:
11 Copyright (c) 2000,2001 Dawit Alemayehu <adawit@kde.org>
12
13 This library is free software; you can redistribute it and/or
14 modify it under the terms of the GNU Lesser General Public
15 License (LGPL) as published by the Free Software Foundation;
16 either version 2 of the License, or (at your option) any later
17 version.
18
19 This library is distributed in the hope that it will be useful,
20 but WITHOUT ANY WARRANTY; without even the implied warranty of
21 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 Lesser General Public License for more details.
23
24 You should have received a copy of the GNU Lesser General Public License
25 along with this library; see the file COPYING.LIB. If not, write to
26 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
27 Boston, MA 02110-1301, USA.
28*/
29
30#ifndef KLINEEDIT_H
31#define KLINEEDIT_H
32
33#include <QtGui/QLineEdit>
34
35#include <kcompletion.h>
36
37class QAction;
38class QMenu;
39class KCompletionBox;
40class KUrl;
41class KLineEditPrivate;
42
43/**
44 * An enhanced QLineEdit widget for inputting text.
45 *
46 * \b Detail \n
47 *
48 * This widget inherits from QLineEdit and implements the following
49 * additional functionalities: a completion object that provides both
50 * automatic and manual text completion as well as multiple match iteration
51 * features, configurable key-bindings to activate these features and a
52 * popup-menu item that can be used to allow the user to set text completion
53 * modes on the fly based on their preference.
54 *
55 * To support these new features KLineEdit also emits a few more
56 * additional signals. These are: completion( const QString& ),
57 * textRotation( KeyBindingType ), and returnPressed( const QString& ).
58 * The completion signal can be connected to a slot that will assist the
59 * user in filling out the remaining text. The text rotation signal is
60 * intended to be used to iterate through the list of all possible matches
61 * whenever there is more than one match for the entered text. The
62 * @p returnPressed( const QString& ) signals are the same as QLineEdit's
63 * except it provides the current text in the widget as its argument whenever
64 * appropriate.
65 *
66 * This widget by default creates a completion object when you invoke
67 * the completionObject( bool ) member function for the first time or
68 * use setCompletionObject( KCompletion*, bool ) to assign your own
69 * completion object. Additionally, to make this widget more functional,
70 * KLineEdit will by default handle the text rotation and completion
71 * events internally when a completion object is created through either one
72 * of the methods mentioned above. If you do not need this functionality,
73 * simply use KCompletionBase::setHandleSignals( bool ) or set the
74 * boolean parameter in the above functions to false.
75 *
76 * The default key-bindings for completion and rotation is determined
77 * from the global settings in KStandardShortcut. These values, however,
78 * can be overridden locally by invoking KCompletionBase::setKeyBinding().
79 * The values can easily be reverted back to the default setting, by simply
80 * calling useGlobalSettings(). An alternate method would be to default
81 * individual key-bindings by using setKeyBinding() with the default
82 * second argument.
83 *
84 * If @p EchoMode for this widget is set to something other than @p QLineEdit::Normal,
85 * the completion mode will always be defaulted to KGlobalSettings::CompletionNone.
86 * This is done purposefully to guard against protected entries such as passwords being
87 * cached in KCompletion's list. Hence, if the @p EchoMode is not QLineEdit::Normal, the
88 * completion mode is automatically disabled.
89 *
90 * A read-only KLineEdit will have the same background color as a
91 * disabled KLineEdit, but its foreground color will be the one used
92 * for the read-write mode. This differs from QLineEdit's implementation
93 * and is done to give visual distinction between the three different modes:
94 * disabled, read-only, and read-write.
95 *
96 * KLineEdit has also a password mode which depends of globals KDE settings. Use
97 * KLineEdit::setPasswordMode instead of QLineEdit::echoMode property to have a password field.
98 *
99 * \b Usage \n
100 *
101 * To enable the basic completion feature:
102 *
103 * \code
104 * KLineEdit *edit = new KLineEdit( this );
105 * KCompletion *comp = edit->completionObject();
106 * // Connect to the return pressed signal - optional
107 * connect(edit,SIGNAL(returnPressed(const QString&)),comp,SLOT(addItem(const QString&)));
108 * \endcode
109 *
110 * To use a customized completion objects or your
111 * own completion object:
112 *
113 * \code
114 * KLineEdit *edit = new KLineEdit( this );
115 * KUrlCompletion *comp = new KUrlCompletion();
116 * edit->setCompletionObject( comp );
117 * // Connect to the return pressed signal - optional
118 * connect(edit,SIGNAL(returnPressed(const QString&)),comp,SLOT(addItem(const QString&)));
119 * \endcode
120 *
121 * Note if you specify your own completion object you have to either delete
122 * it when you don't need it anymore, or you can tell KLineEdit to delete it
123 * for you:
124 * \code
125 * edit->setAutoDeleteCompletionObject( true );
126 * \endcode
127 *
128 * <b>Miscellaneous function calls :</b>\n
129 *
130 * \code
131 * // Tell the widget to not handle completion and iteration automatically.
132 * edit->setHandleSignals( false );
133 *
134 * // Set your own key-bindings for a text completion mode.
135 * edit->setKeyBinding( KCompletionBase::TextCompletion, Qt::End );
136 *
137 * // Hide the context (popup) menu
138 * edit->setContextMenuPolicy( Qt::NoContextMenu );
139 *
140 * // Default the key-bindings back to the default system settings.
141 * edit->useGlobalKeyBindings();
142 * \endcode
143 *
144 * \image html klineedit.png "KDE Line Edit Widgets with clear-button and clickMessage"
145 *
146 * @author Dawit Alemayehu <adawit@kde.org>
147 */
148
149class KDEUI_EXPORT KLineEdit : public QLineEdit, public KCompletionBase //krazy:exclude=qclasses
150{
151 friend class KComboBox;
152 friend class KLineEditStyle;
153
154 Q_OBJECT
155#ifndef KDE_NO_DEPRECATED
156 Q_PROPERTY( bool contextMenuEnabled READ isContextMenuEnabled WRITE setContextMenuEnabled )
157#endif
158 Q_PROPERTY( bool urlDropsEnabled READ urlDropsEnabled WRITE setUrlDropsEnabled )
159 Q_PROPERTY( bool trapEnterKeyEvent READ trapReturnKey WRITE setTrapReturnKey )
160 Q_PROPERTY( bool squeezedTextEnabled READ isSqueezedTextEnabled WRITE setSqueezedTextEnabled )
161 Q_PROPERTY( QString clickMessage READ clickMessage WRITE setClickMessage )
162 Q_PROPERTY( bool showClearButton READ isClearButtonShown WRITE setClearButtonShown )
163 Q_PROPERTY( bool passwordMode READ passwordMode WRITE setPasswordMode )
164
165public:
166
167 /**
168 * Constructs a KLineEdit object with a default text, a parent,
169 * and a name.
170 *
171 * @param string Text to be shown in the edit widget.
172 * @param parent The parent widget of the line edit.
173 */
174 explicit KLineEdit( const QString &string, QWidget *parent = 0 );
175
176 /**
177 * Constructs a line edit
178 * @param parent The parent widget of the line edit.
179 */
180 explicit KLineEdit( QWidget *parent = 0 );
181
182 /**
183 * Destructor.
184 */
185 virtual ~KLineEdit ();
186
187 /**
188 * Sets @p url into the lineedit. It uses KUrl::prettyUrl() so
189 * that the url is properly decoded for displaying.
190 */
191 void setUrl( const KUrl& url );
192
193 /**
194 * Re-implemented from KCompletionBase for internal reasons.
195 *
196 * This function is re-implemented in order to make sure that
197 * the EchoMode is acceptable before we set the completion mode.
198 *
199 * See KCompletionBase::setCompletionMode
200 */
201 virtual void setCompletionMode( KGlobalSettings::Completion mode );
202
203 /**
204 * Disables completion modes by makeing them non-checkable.
205 *
206 * The context menu allows to change the completion mode.
207 * This method allows to disable some modes.
208 */
209 void setCompletionModeDisabled( KGlobalSettings::Completion mode, bool disable = true );
210
211 /**
212 * Enables/disables the popup (context) menu.
213 *
214 * This method only works if this widget is editable, i.e. read-write and
215 * allows you to enable/disable the context menu. It does nothing if invoked
216 * for a none-editable combo-box.
217 *
218 * By default, the context menu is created if this widget is editable.
219 * Call this function with the argument set to false to disable the popup
220 * menu.
221 *
222 * @param showMenu If @p true, show the context menu.
223 * @deprecated use setContextMenuPolicy
224 */
225#ifndef KDE_NO_DEPRECATED
226 virtual KDE_DEPRECATED void setContextMenuEnabled( bool showMenu );
227#endif
228
229 /**
230 * Returns @p true when the context menu is enabled.
231 * @deprecated use contextMenuPolicy
232 */
233#ifndef KDE_NO_DEPRECATED
234 KDE_DEPRECATED bool isContextMenuEnabled() const;
235#endif
236
237 /**
238 * Enables/Disables handling of URL drops. If enabled and the user
239 * drops an URL, the decoded URL will be inserted. Otherwise the default
240 * behavior of QLineEdit is used, which inserts the encoded URL.
241 *
242 * @param enable If @p true, insert decoded URLs
243 */
244 void setUrlDropsEnabled( bool enable );
245
246 /**
247 * Returns @p true when decoded URL drops are enabled
248 */
249 bool urlDropsEnabled() const;
250
251 /**
252 * By default, KLineEdit recognizes @p Key_Return and @p Key_Enter and emits
253 * the returnPressed() signals, but it also lets the event pass,
254 * for example causing a dialog's default-button to be called.
255 *
256 * Call this method with @p trap = @p true to make @p KLineEdit stop these
257 * events. The signals will still be emitted of course.
258 *
259 * @see trapReturnKey()
260 */
261 void setTrapReturnKey( bool trap );
262
263 /**
264 * @returns @p true if keyevents of @p Key_Return or
265 * @p Key_Enter will be stopped or if they will be propagated.
266 *
267 * @see setTrapReturnKey ()
268 */
269 bool trapReturnKey() const;
270
271 /**
272 * @returns the completion-box, that is used in completion mode
273 * KGlobalSettings::CompletionPopup.
274 * This method will create a completion-box if none is there, yet.
275 *
276 * @param create Set this to false if you don't want the box to be created
277 * i.e. to test if it is available.
278 */
279 KCompletionBox * completionBox( bool create = true ); // KDE5 TODO: make virtual, so konq can reimplement i
280
281 /**
282 * Reimplemented for internal reasons, the API is not affected.
283 */
284 virtual void setCompletionObject( KCompletion *, bool hsig = true );
285
286 /**
287 * Reimplemented for internal reasons, the API is not affected.
288 */
289 virtual void copy() const;
290
291 /**
292 * Enable text squeezing whenever the supplied text is too long.
293 * Only works for "read-only" mode.
294 *
295 * Note that once text squeezing is enabled, QLineEdit::text()
296 * and QLineEdit::displayText() return the squeezed text. If
297 * you want the original text, use @ref originalText.
298 *
299 * @see QLineEdit
300 */
301 void setSqueezedTextEnabled( bool enable );
302
303 /**
304 * Returns true if text squeezing is enabled.
305 * This is only valid when the widget is in read-only mode.
306 */
307 bool isSqueezedTextEnabled() const;
308
309 /**
310 * Returns the original text if text squeezing is enabled.
311 * If the widget is not in "read-only" mode, this function
312 * returns the same thing as QLineEdit::text().
313 *
314 * @see QLineEdit
315 */
316 QString originalText() const;
317
318 /**
319 * Returns the text as given by the user (i.e. not autocompleted)
320 * if the widget has autocompletion disabled, this function
321 * returns the same as QLineEdit::text().
322 * @since 4.2.2
323 */
324 QString userText() const;
325
326 /**
327 * Set the completion-box to be used in completion mode
328 * KGlobalSettings::CompletionPopup.
329 * This will do nothing if a completion-box already exists.
330 *
331 * @param box The KCompletionBox to set
332 */
333 void setCompletionBox( KCompletionBox *box );
334
335 /**
336 * This makes the line edit display a grayed-out hinting text as long as
337 * the user didn't enter any text. It is often used as indication about
338 * the purpose of the line edit.
339 */
340 void setClickMessage( const QString &msg );
341
342 /**
343 * @return the message set with setClickMessage
344 */
345 QString clickMessage() const;
346
347 /**
348 * This makes the line edit display an icon on one side of the line edit
349 * which, when clicked, clears the contents of the line edit.
350 * This is useful for such things as location or search bars.
351 **/
352 void setClearButtonShown(bool show);
353
354 /**
355 * @return whether or not the clear button is shown
356 **/
357 bool isClearButtonShown() const;
358
359 /**
360 * @return the size used by the clear button
361 * @since KDE 4.1
362 **/
363 QSize clearButtonUsedSize() const;
364
365 /**
366 * Do completion now. This is called automatically when typing a key for instance.
367 * Emits completion() and/or calls makeCompletion(), depending on
368 * emitSignals and handleSignals.
369 *
370 * @since 4.2.1
371 */
372 void doCompletion(const QString& txt);
373
374Q_SIGNALS:
375
376 /**
377 * Emitted whenever the completion box is activated.
378 */
379 void completionBoxActivated (const QString &);
380
381 /**
382 * Emitted when the user presses the return key.
383 *
384 * The argument is the current text. Note that this
385 * signal is @em not emitted if the widget's @p EchoMode is set to
386 * QLineEdit::EchoMode.
387 */
388 void returnPressed( const QString& );
389
390 /**
391 * Emitted when the completion key is pressed.
392 *
393 * Please note that this signal is @em not emitted if the
394 * completion mode is set to @p CompletionNone or @p EchoMode is
395 * @em normal.
396 */
397 void completion( const QString& );
398
399 /**
400 * Emitted when the shortcut for substring completion is pressed.
401 */
402 void substringCompletion( const QString& );
403
404 /**
405 * Emitted when the text is changed NOT by the suggested autocompletion:
406 * either when the user is physically typing keys, or when the text is changed programmatically,
407 * for example, by calling setText().
408 * But not when automatic completion changes the text temporarily.
409 *
410 * @since 4.2.2
411 * @deprecated since 4.5. You probably want to connect to textEdited() instead,
412 * which is emitted whenever the text is actually changed by the user
413 * (by typing or accepting autocompletion), without side effects from
414 * suggested autocompletion either. userTextChanged isn't needed anymore.
415 */
416#ifndef KDE_NO_DEPRECATED
417 QT_MOC_COMPAT void userTextChanged( const QString & );
418#endif
419
420 /**
421 * Emitted when the text rotation key-bindings are pressed.
422 *
423 * The argument indicates which key-binding was pressed.
424 * In KLineEdit's case this can be either one of two values:
425 * PrevCompletionMatch or NextCompletionMatch. See
426 * KCompletionBase::setKeyBinding for details.
427 *
428 * Note that this signal is @em not emitted if the completion
429 * mode is set to @p KGlobalSettings::CompletionNone or @p echoMode() is @em not normal.
430 */
431 void textRotation( KCompletionBase::KeyBindingType );
432
433 /**
434 * Emitted when the user changed the completion mode by using the
435 * popupmenu.
436 */
437 void completionModeChanged( KGlobalSettings::Completion );
438
439 /**
440 * Emitted before the context menu is displayed.
441 *
442 * The signal allows you to add your own entries into the
443 * the context menu that is created on demand.
444 *
445 * NOTE: Do not store the pointer to the QMenu
446 * provided through since it is created and deleted
447 * on demand.
448 *
449 * @param p the context menu about to be displayed
450 */
451 void aboutToShowContextMenu(QMenu* menu);
452
453 /**
454 * Emitted when the user clicked on the clear button
455 */
456 void clearButtonClicked();
457
458public Q_SLOTS:
459
460 /**
461 * Sets the lineedit to read-only. Similar to QLineEdit::setReadOnly
462 * but also takes care of the background color, and the clear button.
463 */
464 virtual void setReadOnly(bool);
465
466 /**
467 * Iterates through all possible matches of the completed text or
468 * the history list.
469 *
470 * This function simply iterates over all possible matches in case
471 * multiple matches are found as a result of a text completion request.
472 * It will have no effect if only a single match is found.
473 *
474 * @param type The key-binding invoked.
475 */
476 void rotateText( KCompletionBase::KeyBindingType type );
477
478 /**
479 * See KCompletionBase::setCompletedText.
480 */
481 virtual void setCompletedText( const QString& );
482
483 /**
484 * Same as the above function except it allows you to temporarily
485 * turn off text completion in CompletionPopupAuto mode.
486 *
487 *
488 * @param items list of completion matches to be shown in the completion box.
489 * @param autoSuggest true if you want automatic text completion (suggestion) enabled.
490 */
491 void setCompletedItems( const QStringList& items, bool autoSuggest = true );
492
493 /**
494 * Reimplemented to workaround a buggy QLineEdit::clear()
495 * (changing the clipboard to the text we just had in the lineedit)
496 */
497 virtual void clear(); // ### KDE 5: check if still required
498
499 /**
500 * Squeezes @p text into the line edit.
501 * This can only be used with read-only line-edits.
502 */
503 void setSqueezedText( const QString &text);
504
505 /**
506 * Re-implemented to enable text squeezing. API is not affected.
507 */
508 virtual void setText ( const QString& );
509
510 /**
511 * @brief set the line edit in password mode.
512 * this change the EchoMode according to KDE preferences.
513 * @param b true to set in password mode
514 */
515 void setPasswordMode( bool b = true );
516
517 /**
518 * @return returns true if the lineedit is set to password mode echoing
519 */
520 bool passwordMode( ) const;
521
522
523protected Q_SLOTS:
524
525 /**
526 * Completes the remaining text with a matching one from
527 * a given list.
528 */
529 virtual void makeCompletion( const QString& );
530
531 /**
532 * Resets the current displayed text.
533 * Call this function to revert a text completion if the user
534 * cancels the request. Mostly applies to popup completions.
535 */
536 void userCancelled(const QString & cancelText);
537
538protected:
539
540 /**
541 * Re-implemented for internal reasons. API not affected.
542 */
543 virtual bool event( QEvent * );
544
545 /**
546 * Re-implemented for internal reasons. API not affected.
547 *
548 * See QLineEdit::resizeEvent().
549 */
550 virtual void resizeEvent( QResizeEvent * );
551
552 /**
553 * Re-implemented for internal reasons. API not affected.
554 *
555 * See QLineEdit::keyPressEvent().
556 */
557 virtual void keyPressEvent( QKeyEvent * );
558
559 /**
560 * Re-implemented for internal reasons. API not affected.
561 *
562 * See QLineEdit::mousePressEvent().
563 */
564 virtual void mousePressEvent( QMouseEvent * );
565
566 /**
567 * Re-implemented for internal reasons. API not affected.
568 *
569 * See QLineEdit::mouseReleaseEvent().
570 */
571 virtual void mouseReleaseEvent( QMouseEvent * );
572
573 /**
574 * Re-implemented for internal reasons. API not affected.
575 *
576 * See QWidget::mouseDoubleClickEvent().
577 */
578 virtual void mouseDoubleClickEvent( QMouseEvent * );
579
580 /**
581 * Re-implemented for internal reasons. API not affected.
582 *
583 * See QLineEdit::contextMenuEvent().
584 */
585 virtual void contextMenuEvent( QContextMenuEvent * );
586
587 /**
588 * Re-implemented for internal reasons. API not affected.
589 *
590 * See QLineEdit::createStandardContextMenu().
591 */
592 QMenu* createStandardContextMenu();
593
594 /**
595 * Re-implemented to handle URI drops.
596 *
597 * See QLineEdit::dropEvent().
598 */
599 virtual void dropEvent( QDropEvent * );
600
601 /**
602 * This function simply sets the lineedit text and
603 * highlights the text appropriately if the boolean
604 * value is set to true.
605 *
606 * @param text
607 * @param marked
608 */
609 virtual void setCompletedText( const QString& /*text*/, bool /*marked*/ );
610
611
612 /**
613 * Sets the widget in userSelection mode or in automatic completion
614 * selection mode. This changes the colors of selections.
615 */
616 void setUserSelection( bool userSelection );
617
618 /**
619 * Reimplemented for internal reasons, the API is not affected.
620 */
621 virtual void create( WId = 0, bool initializeWindow = true,
622 bool destroyOldWindow = true );
623
624 /**
625 * Whether in current state text should be auto-suggested
626 */
627 bool autoSuggest() const;
628
629 virtual void paintEvent( QPaintEvent *ev );
630
631 virtual void focusInEvent( QFocusEvent *ev );
632
633 virtual void focusOutEvent( QFocusEvent *ev );
634
635private Q_SLOTS:
636 void completionMenuActivated( QAction *act );
637 void tripleClickTimeout(); // resets possibleTripleClick
638 void slotRestoreSelectionColors();
639 void _k_slotCompletionBoxTextChanged( const QString& text );
640
641 /**
642 * updates the icon of the clear button on text change
643 **/
644 void updateClearButtonIcon(const QString&);
645
646private:
647
648
649 /**
650 * Initializes variables. Called from the constructors.
651 */
652 void init();
653
654 bool copySqueezedText( bool clipboard ) const;
655
656 /**
657 * Properly sets the squeezed text whenever the widget is
658 * created or resized.
659 */
660 void setSqueezedText ();
661
662 /**
663 * updates the geometry of the clear button on resize events
664 **/
665 void updateClearButton();
666
667private:
668 friend class KLineEditPrivate;
669 KLineEditPrivate *const d;
670
671 Q_PRIVATE_SLOT( d, void _k_slotSettingsChanged( int category ) )
672 Q_PRIVATE_SLOT( d, void _k_textChanged(const QString&) )
673};
674
675#endif
676