summaryrefslogtreecommitdiff
path: root/src/urlbar/urlresolver.cpp
blob: f7fb27f1b90d6835a1d0df2caebfb208ef7f3dde (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/* ============================================================
*
* This file is a part of the rekonq project
*
* Copyright (C) 2009-2012 by Andrea Diamantini <adjam7 at gmail dot com>
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License or (at your option) version 3 or any later version
* accepted by the membership of KDE e.V. (or its successor approved
* by the membership of KDE e.V.), which shall act as a proxy
* defined in Section 14 of version 3 of the license.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
* ============================================================ */


// Self Includes
#include "urlresolver.h"
#include "urlresolver.moc"

// Local Includes
#include "historymanager.h"
#include "bookmarkmanager.h"
#include "searchengine.h"

// KDE Includes
#include <KBookmark>
#include <KService>
#include <KProtocolInfo>

// Qt Includes
#include <QByteArray>


// NOTE
// default kurifilter plugin list (at least in my box):
// 1. "kshorturifilter"
// 2. "kurisearchfilter"
// 3. "localdomainurifilter"
// 4 ."kuriikwsfilter"
// 5. "fixhosturifilter"


// ------------------------------------------------------------------------

KService::Ptr UrlResolver::_searchEngine;

QRegExp UrlResolver::_browseRegexp;
QRegExp UrlResolver::_searchEnginesRegexp;


UrlResolver::UrlResolver(const QString &typedUrl)
    : QObject()
    , _typedString(typedUrl.trimmed())
    , _typedQuery()
{
    if (!_searchEngine)
        setSearchEngine(SearchEngine::defaultEngine());

    if (_browseRegexp.isEmpty())
    {
        QString protocol = QString("^(%1)").arg(KProtocolInfo::protocols().join("|"));

        QString localhost = QL1S("^localhost");

        QString local = QL1S("^/");

        QString ipv4 = QL1S("^0*([1-9]?\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.0*([1-9]?\\d|1\\d\\d|2[0-4]\\d|25[0-5])"\
                            "\\.0*([1-9]?\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.0*([1-9]?\\d|1\\d\\d|2[0-4]\\d|25[0-5])");

        QString ipv6 = QL1S("^([0-9a-fA-F]{4}|0)(\\:([0-9a-fA-F]{4}|0)){7}");

        QString address = QL1S("[\\d\\w-.]+\\.(a[cdefgilmnoqrstuwz]|b[abdefghijmnorstvwyz]|"\
                               "c[acdfghiklmnoruvxyz]|d[ejkmnoz]|e[ceghrstu]|f[ijkmnor]|g[abdefghilmnpqrstuwy]|"\
                               "h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|"\
                               "m[acdghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eouw]|"\
                               "s[abcdeghijklmnortuvyz]|t[cdfghjkmnoprtvwz]|u[augkmsyz]|v[aceginu]|w[fs]|"\
                               "y[etu]|z[amw]|aero|arpa|biz|com|coop|edu|info|int|gov|local|mil|museum|name|net|org|"\
                               "pro)");

        QString joiner = QL1S(")|(");
        _browseRegexp = QRegExp(QL1C('(') +
                                protocol + joiner +
                                localhost + joiner +
                                local + joiner +
                                address + joiner +
                                ipv6 + joiner +
                                ipv4 + QL1C(')')
                               );
    }

    if (_searchEnginesRegexp.isEmpty())
    {
        QString reg;
        QString engineUrl;
        Q_FOREACH(KService::Ptr s, SearchEngine::favorites())
        {
            engineUrl = QRegExp::escape(s->property("Query").toString()).replace(QL1S("\\\\\\{@\\}"), QL1S("[\\d\\w-.]+"));
            if (reg.isEmpty())
                reg = QL1C('(') + engineUrl + QL1C(')');
            else
                reg = reg + QL1S("|(") + engineUrl + QL1C(')');
        }
        _searchEnginesRegexp = QRegExp(reg);
    }
}


UrlSearchList UrlResolver::orderedSearchItems()
{
    if (_typedString.startsWith(QL1S("about:")))
    {
        QStringList aboutUrlList;
        aboutUrlList
        << QL1S("about:home")
        << QL1S("about:favorites")
        << QL1S("about:closedTabs")
        << QL1S("about:bookmarks")
        << QL1S("about:history")
        << QL1S("about:downloads")
        << QL1S("about:tabs")
        << QL1S("about:info");

        QStringList aboutUrlResults = aboutUrlList.filter(_typedString, Qt::CaseInsensitive);

        UrlSearchList list;
        
        if (aboutUrlResults.isEmpty())
        {
            UrlSearchItem info(UrlSearchItem::Browse, QL1S("about:info"),  QL1S("info"));
            list << info;

            return list;
        }

        Q_FOREACH(const QString & urlResult, aboutUrlResults)
        {
            QString name = urlResult;
            name.remove(0,6);
            UrlSearchItem item(UrlSearchItem::Browse, urlResult, name);
            list << item;
        }

        return list;
    }

    //compute lists
    computeHistory();
    computeQurlFromUserInput();
    computeWebSearches();
    computeBookmarks();

    return orderLists();
}


UrlSearchList UrlResolver::orderLists()
{
    // NOTE
    // The const int here decides the number of proper suggestions, taken from history & bookmarks
    // You have to add here the "browse & search" options, always available.
    const int availableEntries = 8;

    bool webSearchFirst = false;
    // Browse & Search results
    UrlSearchList browseSearch;
    QString lowerTypedString = _typedString.toLower();
    if (_browseRegexp.indexIn(lowerTypedString) != -1)
    {
        webSearchFirst = true;
        browseSearch << _webSearches;
    }
    else
    {
        browseSearch << _webSearches;
        browseSearch << _qurlFromUserInput;
    }


    // find relevant items (the one you are more probably searching...)
    UrlSearchList relevant;

    // history
    Q_FOREACH(const UrlSearchItem & item, _history)
    {
        QString hst = KUrl(item.url).host();
        if (item.url.startsWith(_typedString)
                || hst.startsWith(_typedString)
                || hst.remove("www.").startsWith(_typedString))
        {
            relevant << item;
            _history.removeOne(item);
            break;
        }
    }

    // bookmarks
    Q_FOREACH(const UrlSearchItem & item, _bookmarks)
    {
        QString hst = KUrl(item.url).host();
        if (item.url.startsWith(_typedString)
                || hst.startsWith(_typedString)
                || hst.remove("www.").startsWith(_typedString))
        {
            relevant << item;
            _bookmarks.removeOne(item);
            break;
        }
    }

    // decide history & bookmarks number
    int historyCount = _history.count();
    int bookmarksCount = _bookmarks.count();
    int relevantCount = relevant.count();

    const int historyEntries = (availableEntries - relevantCount) / 2;
    const int bookmarksEntries = availableEntries - relevantCount - historyEntries;

    if (historyCount >= historyEntries && bookmarksCount >= bookmarksEntries)
    {
        _history = _history.mid(0, historyEntries);
        _bookmarks = _bookmarks.mid(0, bookmarksEntries);
    }
    else if (historyCount < historyEntries && bookmarksCount >= bookmarksEntries)
    {
        if (historyCount + bookmarksCount > availableEntries)
        {
            _bookmarks = _bookmarks.mid(0, availableEntries - historyCount);
        }
    }
    else if (historyCount >= historyEntries && bookmarksCount < bookmarksEntries)
    {
        if (historyCount + bookmarksCount > availableEntries)
        {
            _history = _history.mid(0, availableEntries - bookmarksCount);
        }
    }

    // and finally, results
    UrlSearchList list;

    if (webSearchFirst)
        list << _qurlFromUserInput;
    list += relevant + browseSearch + _history + _bookmarks;
    return list;
}


//////////////////////////////////////////////////////////////////////////
// PRIVATE ENGINES


// QUrl from User Input (easily the best solution... )
void UrlResolver::computeQurlFromUserInput()
{
    QString url = _typedString;
    QUrl urlFromUserInput = QUrl::fromUserInput(url);
    if (urlFromUserInput.isValid())
    {
        // ensure http(s) hosts are lower cases
        if (urlFromUserInput.scheme().startsWith("http"))
        {
            QString hst = urlFromUserInput.host();
            urlFromUserInput.setHost(hst.toLower());
        }
        
        QString urlString = urlFromUserInput.toString();
        QString gTitle = i18nc("Browse a website", "Browse");
        UrlSearchItem gItem(UrlSearchItem::Browse, urlString, gTitle);
        _qurlFromUserInput << gItem;
    }
}


// webSearches
void UrlResolver::computeWebSearches()
{
    QString query = _typedString;
    KService::Ptr engine = SearchEngine::fromString(_typedString);
    if (engine)
    {
        query = query.remove(0, _typedString.indexOf(SearchEngine::delimiter()) + 1);
        setSearchEngine(engine);
    }

    if (_searchEngine)
    {
        UrlSearchItem item = UrlSearchItem(UrlSearchItem::Search, SearchEngine::buildQuery(_searchEngine, query), query);
        UrlSearchList list;
        list << item;
        _webSearches = list;
    }
}


// history
void UrlResolver::computeHistory()
{
    QList<HistoryItem> found = rApp->historyManager()->find(_typedString);
    qSort(found.begin(), found.end(), isHistoryItemRelevant);

    Q_FOREACH(const HistoryItem & i, found)
    {
        if (_searchEnginesRegexp.isEmpty() || _searchEnginesRegexp.indexIn(i.url) == -1) //filter all urls that are search engine results
        {
            UrlSearchItem gItem(UrlSearchItem::History, i.url, i.title);
            _history << gItem;
        }
    }
}


// bookmarks
void UrlResolver::computeBookmarks()
{
    QList<KBookmark> found = rApp->bookmarkManager()->find(_typedString);
    Q_FOREACH(const KBookmark & b, found)
    {
        UrlSearchItem gItem(UrlSearchItem::Bookmark, b.url().url(), b.fullText());
        _bookmarks << gItem;
    }
}


// opensearch suggestion
void UrlResolver::computeSuggestions()
{
    // NOTE
    // This attempt basically cuts out open search suggestions.
    UrlSearchList list;
    emit suggestionsReady(list, _typedString);
    return;

//     // if a string startsWith /, it is probably a local path
//     // so, no need for suggestions...
//     if (_typedString.startsWith('/') || !rApp->opensearchManager()->isSuggestionAvailable())
//     {
//         UrlSearchList list;
//         emit suggestionsReady(list, _typedString);
//         return;
//     }
//
//     QString query = _typedString;
//     KService::Ptr engine = SearchEngine::fromString(_typedString);
//     if (engine)
//     {
//         query = query.remove(0, _typedString.indexOf(SearchEngine::delimiter()) + 1);
//         setSearchEngine(engine);
//     }
//
//     connect(rApp->opensearchManager(),
//             SIGNAL(suggestionsReceived(QString,ResponseList)),
//             this,
//             SLOT(suggestionsReceived(QString,ResponseList)));
//
//     _typedQuery = query;
//     rApp->opensearchManager()->requestSuggestion(query);
}


bool UrlResolver::isHistoryItemRelevant(const HistoryItem &a, const HistoryItem &b)
{
    return a.relevance() > b.relevance();
}


void UrlResolver::suggestionsReceived(const QString &text, const ResponseList &suggestions)
{
    if (text != _typedQuery)
        return;

    UrlSearchList sugList;
    QString urlString;
    Q_FOREACH(const Response & i, suggestions)
    {
        if (text == i.title)
            continue;

        urlString = i.url;
        if (urlString.isEmpty())
        {
            urlString = SearchEngine::buildQuery(UrlResolver::searchEngine(), i.title);
        }

        UrlSearchItem gItem(UrlSearchItem::Suggestion, urlString, i.title, i.description, i.image, i.image_width, i.image_height);
        sugList << gItem;
    }
    emit suggestionsReady(sugList, _typedString);
    this->deleteLater();
}