1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the examples of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** BSD License Usage
18 ** Alternatively, you may use this file under the terms of the BSD license
19 ** as follows:
20 **
21 ** "Redistribution and use in source and binary forms, with or without
22 ** modification, are permitted provided that the following conditions are
23 ** met:
24 **   * Redistributions of source code must retain the above copyright
25 **     notice, this list of conditions and the following disclaimer.
26 **   * Redistributions in binary form must reproduce the above copyright
27 **     notice, this list of conditions and the following disclaimer in
28 **     the documentation and/or other materials provided with the
29 **     distribution.
30 **   * Neither the name of The Qt Company Ltd nor the names of its
31 **     contributors may be used to endorse or promote products derived
32 **     from this software without specific prior written permission.
33 **
34 **
35 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46 **
47 ** $QT_END_LICENSE$
48 **
49 ****************************************************************************/
50 
51 #include "googlesuggest.h"
52 
53 //! [1]
54 const QString gsuggestUrl(QStringLiteral("http://google.com/complete/search?output=toolbar&q=%1"));
55 //! [1]
56 
57 //! [2]
GSuggestCompletion(QLineEdit * parent)58 GSuggestCompletion::GSuggestCompletion(QLineEdit *parent): QObject(parent), editor(parent)
59 {
60     popup = new QTreeWidget;
61     popup->setWindowFlags(Qt::Popup);
62     popup->setFocusPolicy(Qt::NoFocus);
63     popup->setFocusProxy(parent);
64     popup->setMouseTracking(true);
65 
66     popup->setColumnCount(1);
67     popup->setUniformRowHeights(true);
68     popup->setRootIsDecorated(false);
69     popup->setEditTriggers(QTreeWidget::NoEditTriggers);
70     popup->setSelectionBehavior(QTreeWidget::SelectRows);
71     popup->setFrameStyle(QFrame::Box | QFrame::Plain);
72     popup->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
73     popup->header()->hide();
74 
75     popup->installEventFilter(this);
76 
77     connect(popup, &QTreeWidget::itemClicked,
78             this, &GSuggestCompletion::doneCompletion);
79 
80     timer.setSingleShot(true);
81     timer.setInterval(500);
82     connect(&timer, &QTimer::timeout,
83             this, &GSuggestCompletion::autoSuggest);
84     connect(editor, &QLineEdit::textEdited,
85             &timer, QOverload<>::of(&QTimer::start));
86 
87     connect(&networkManager, &QNetworkAccessManager::finished,
88             this, &GSuggestCompletion::handleNetworkData);
89 
90 }
91 //! [2]
92 
93 //! [3]
~GSuggestCompletion()94 GSuggestCompletion::~GSuggestCompletion()
95 {
96     delete popup;
97 }
98 //! [3]
99 
100 //! [4]
eventFilter(QObject * obj,QEvent * ev)101 bool GSuggestCompletion::eventFilter(QObject *obj, QEvent *ev)
102 {
103     if (obj != popup)
104         return false;
105 
106     if (ev->type() == QEvent::MouseButtonPress) {
107         popup->hide();
108         editor->setFocus();
109         return true;
110     }
111 
112     if (ev->type() == QEvent::KeyPress) {
113         bool consumed = false;
114         int key = static_cast<QKeyEvent*>(ev)->key();
115         switch (key) {
116         case Qt::Key_Enter:
117         case Qt::Key_Return:
118             doneCompletion();
119             consumed = true;
120             break;
121 
122         case Qt::Key_Escape:
123             editor->setFocus();
124             popup->hide();
125             consumed = true;
126             break;
127 
128         case Qt::Key_Up:
129         case Qt::Key_Down:
130         case Qt::Key_Home:
131         case Qt::Key_End:
132         case Qt::Key_PageUp:
133         case Qt::Key_PageDown:
134             break;
135 
136         default:
137             editor->setFocus();
138             editor->event(ev);
139             popup->hide();
140             break;
141         }
142 
143         return consumed;
144     }
145 
146     return false;
147 }
148 //! [4]
149 
150 //! [5]
showCompletion(const QVector<QString> & choices)151 void GSuggestCompletion::showCompletion(const QVector<QString> &choices)
152 {
153     if (choices.isEmpty())
154         return;
155 
156     const QPalette &pal = editor->palette();
157     QColor color = pal.color(QPalette::Disabled, QPalette::WindowText);
158 
159     popup->setUpdatesEnabled(false);
160     popup->clear();
161 
162     for (const auto &choice : choices) {
163         auto item  = new QTreeWidgetItem(popup);
164         item->setText(0, choice);
165         item->setForeground(0, color);
166     }
167 
168     popup->setCurrentItem(popup->topLevelItem(0));
169     popup->resizeColumnToContents(0);
170     popup->setUpdatesEnabled(true);
171 
172     popup->move(editor->mapToGlobal(QPoint(0, editor->height())));
173     popup->setFocus();
174     popup->show();
175 }
176 //! [5]
177 
178 //! [6]
doneCompletion()179 void GSuggestCompletion::doneCompletion()
180 {
181     timer.stop();
182     popup->hide();
183     editor->setFocus();
184     QTreeWidgetItem *item = popup->currentItem();
185     if (item) {
186         editor->setText(item->text(0));
187         QMetaObject::invokeMethod(editor, "returnPressed");
188     }
189 }
190 //! [6]
191 
192 //! [7]
autoSuggest()193 void GSuggestCompletion::autoSuggest()
194 {
195     QString str = editor->text();
196     QString url = gsuggestUrl.arg(str);
197     networkManager.get(QNetworkRequest(url));
198 }
199 //! [7]
200 
201 //! [8]
preventSuggest()202 void GSuggestCompletion::preventSuggest()
203 {
204     timer.stop();
205 }
206 //! [8]
207 
208 //! [9]
handleNetworkData(QNetworkReply * networkReply)209 void GSuggestCompletion::handleNetworkData(QNetworkReply *networkReply)
210 {
211     QUrl url = networkReply->url();
212     if (networkReply->error() == QNetworkReply::NoError) {
213         QVector<QString> choices;
214 
215         QByteArray response(networkReply->readAll());
216         QXmlStreamReader xml(response);
217         while (!xml.atEnd()) {
218             xml.readNext();
219             if (xml.tokenType() == QXmlStreamReader::StartElement)
220                 if (xml.name() == "suggestion") {
221                     QStringRef str = xml.attributes().value("data");
222                     choices << str.toString();
223                 }
224         }
225 
226         showCompletion(choices);
227     }
228 
229     networkReply->deleteLater();
230 }
231 //! [9]
232