application.cpp 27 KB
Newer Older
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
/* ============================================================
*
* This file is a part of the rekonq project
*
* Copyright (C) 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 "application.h"
#include "application.moc"

// Auto Includes
#include "rekonq.h"

Andrea Diamantini's avatar
Andrea Diamantini committed
34
35
36
// Ui Includes
#include "ui_webappcreation.h"

37
// Local Includes
Andrea Diamantini's avatar
Andrea Diamantini committed
38
#include "searchengine.h"
39

Andrea Diamantini's avatar
Andrea Diamantini committed
40
#include "tabbar.h"
41
#include "tabwindow.h"
42

43
#include "webwindow.h"
44
#include "webtab.h"
45
46
#include "webpage.h"

47
48
#include "urlresolver.h"

Andrea Diamantini's avatar
Andrea Diamantini committed
49
// Local Manager(s) Includes
50
#include "adblockmanager.h"
51
#include "downloadmanager.h"
Andrea Diamantini's avatar
Andrea Diamantini committed
52
#include "historymanager.h"
53
#include "iconmanager.h"
Andrea Diamantini's avatar
Andrea Diamantini committed
54
#include "sessionmanager.h"
Andrea Diamantini's avatar
Andrea Diamantini committed
55

56
57
58
59
// Ui Includes
#include "ui_cleardata.h"

// KDE Includes
60
61
#include <KCmdLineArgs>

62
63
64
65
#include <KDialog>
#include <KProcess>
#include <KPushButton>
#include <KStandardDirs>
66
67
68
69
70
#include <KWindowSystem>
#include <KWindowInfo>
#include <KStartupInfo>

#include <KMessageBox>
71
72
73
74

// Qt Includes
#include <QDBusInterface>
#include <QDBusReply>
75
#include <QDir>
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


Application::Application()
    : KUniqueApplication()
{
}


Application::~Application()
{
    // ok, we are closing well.
    // Don't recover on next load..
    ReKonfig::setRecoverOnCrash(0);
    saveConfiguration();

    kDebug() << "Bye bye (k)baby...";
}


int Application::newInstance()
{
    KCmdLineArgs* args = KCmdLineArgs::parsedArgs();

    // not that easy, indeed
    // We have to consider 3 variables here:
    // 1) Is first load?
    // 2) Are there arguments?
    // 3) Is rekonq recovering from crash?
    // so, we have 8 possible cases...
    static bool isFirstLoad = true;
    bool areThereArguments = (args->count() > 0);
107
108
109
    bool hasToBeRecoveredFromCrash = (ReKonfig::recoverOnCrash() > 0);
    // note that hasToBeRecoveredFromCrash is always true if it is not the first load
    // !isFirstLoad -> hasToBeRecoveredFromCrash
110
111
112

    kDebug() << "is first load? " << isFirstLoad;
    kDebug() << "are there arguments? " << areThereArguments;
113
    kDebug() << "is rekonq crashed? " << hasToBeRecoveredFromCrash;
114

115
116
117
    bool incognito = args->isSet("incognito");
    bool webapp = args->isSet("webapp");

118
119
    if (webapp)
    {
120
        kDebug() << "WEBAPP MODE...";
121
122
123
124
125
        if (args->count() == 0)
        {
            KMessageBox::error(0, i18n("Error"), i18n("Cannot launch webapp mode without an URL to load"));
            return 1;
        }
126

127
128
129
130
131
        if (args->count() > 1)
        {
            KMessageBox::error(0, i18n("Error"), i18n("Cannot load more than one URL in webapp mode"));
            return 1;
        }
132

133
134
135
136
137
138
139
        KUrl u = args->url(0);
        if (!u.isLocalFile() || !QFile::exists(u.toLocalFile()))
        {
            u = UrlResolver::urlFromTextTyped(args->arg(0));
        }
        kDebug() << "URL: " << u;

140
        WebTab *tab = newWebApp();
141
        connect(tab->page(), SIGNAL(pageCreated(WebPage*)), this, SLOT(pageCreated(WebPage*)));
142
        tab->view()->load(u);
143

144
145
146
147
        if (isFirstLoad)
        {
            // updating rekonq configuration
            updateConfiguration();
148

149
150
151
152
153
154
155
156
157
158
            setWindowIcon(KIcon("rekonq"));

            // just create History Manager...
            HistoryManager::self();
        }

        KStartupInfo::appStarted();
        isFirstLoad = false;
        return 0;
    }
159

160
    if (areThereArguments)
161
    {
162
163
        kDebug() << "DEFAULT MODE, WITH ARGUMENTS...";

164
165
166
        // prepare URLS to load
        KUrl::List urlList;
        for (int i = 0; i < args->count(); ++i)
167
        {
168
            const KUrl u = args->url(i);
169

170
            if (u.isLocalFile() && QFile::exists(u.toLocalFile())) // "rekonq somefile.html" case
171
            {
172
                urlList += u;
173
174
175
            }
            else
            {
176
177
                // "rekonq kde.org" || "rekonq kde:kdialog" cases
                urlList += UrlResolver::urlFromTextTyped(args->arg(i));
178
            }
179
        }
180

181
        if (isFirstLoad)
182
        {
183
184
185
186
187
188
189
190
191
            bool restoreOk = false;
            if (ReKonfig::startupBehaviour() == 2)
            {
                restoreOk = SessionManager::self()->restoreSessionFromScratch();
            }
            else
            {
                restoreOk = SessionManager::self()->restoreJustThePinnedTabs();
            }
192
193

            isFirstLoad = !restoreOk;
194
195
196
        }

        // first argument: 99% of the time we have just that...
197
        if (isFirstLoad || m_tabWindows.count() == 0)
198
199
200
        {
            // No windows in the current desktop? No windows at all?
            // Create a new one and load there sites...
201
202
203
204
            if (incognito)
                loadUrl(urlList.at(0), Rekonq::NewPrivateWindow);
            else
                loadUrl(urlList.at(0), Rekonq::NewWindow);
205
206
207
        }
        else
        {
208
            if (incognito)
209
            {
210
                loadUrl(urlList.at(0), Rekonq::NewPrivateWindow);
211
            }
212
213
214
215
            else if (!ReKonfig::openExternalLinksInNewWindow())
            {
                loadUrl(urlList.at(0), Rekonq::NewFocusedTab);
            }
216
            else
217
218
219
            {
                loadUrl(urlList.at(0), Rekonq::NewWindow);
            }
220
221
222
223
224
225
226
227
228
229
230

            if (!tabWindow()->isActiveWindow())
                KWindowSystem::demandAttention(tabWindow()->winId(), true);
        }

        // following arguments: what's best behavior here?
        // I'm pretty sure no one has real opinion about...
        if (!ReKonfig::openExternalLinksInNewWindow())
        {
            for (int i = 1; i < urlList.count(); ++i)
                loadUrl(urlList.at(i), Rekonq::NewFocusedTab);
231
232
233
        }
        else
        {
234
            for (int i = 1; i < urlList.count(); ++i)
235
236
237
238
                if (incognito)
                    loadUrl(urlList.at(i), Rekonq::NewPrivateWindow);
                else
                    loadUrl(urlList.at(i), Rekonq::NewWindow);
239
240
        }
    }
241
    else    // ok, NO arguments
242
    {
243
        kDebug() << "DEFAULT MODE, NO ARGUMENTS...";
244
245
        if (isFirstLoad)
        {
246
247
248
            // NOTE: just load new tabs/windows without arguments
            // if NOT is Session restored...
            if (!isSessionRestored())
249
            {
250
                switch (ReKonfig::startupBehaviour())
251
                {
252
                case 0: // open home page
253
254
255
256
257
                    if (incognito)
                    {
                        loadUrl(KUrl(ReKonfig::homePage()), Rekonq::NewPrivateWindow);
                        break;
                    }
258
259
260
                    if (SessionManager::self()->restoreJustThePinnedTabs())
                        loadUrl(KUrl(ReKonfig::homePage()) , Rekonq::NewTab);
                    else
261
                        loadUrl(KUrl(ReKonfig::homePage()) , Rekonq::NewWindow);
262
263
                    break;
                case 1: // open new tab page
264
265
266
267
268
                    if (incognito)
                    {
                        loadUrl(KUrl("about:home"), Rekonq::NewPrivateWindow);
                        break;
                    }
269
270
271
                    if (SessionManager::self()->restoreJustThePinnedTabs())
                        loadUrl(KUrl("about:home") , Rekonq::NewTab);
                    else
272
                        loadUrl(KUrl("about:home"), Rekonq::NewWindow);
273
274
                    break;
                case 2: // restore session
275
276
277
278
279
                    if (incognito)
                    {
                        loadUrl(KUrl("about:home"), Rekonq::NewPrivateWindow);
                        break;
                    }
280
                    if (SessionManager::self()->restoreSessionFromScratch())
281
282
283
                    {
                        break;
                    }
284
                default:
Andrea Diamantini's avatar
Andrea Diamantini committed
285
                    newTabWindow()->newTab();
286
                    break;
287
288
                }
            }
289
290
291
        }
        else
        {
292
            Rekonq::OpenType type = incognito ? Rekonq::NewPrivateWindow : Rekonq::NewWindow;
293

294
            switch (ReKonfig::newTabsBehaviour())
295
            {
296
            case 0: // new tab page
297
                loadUrl(KUrl("about:home") , type);
298
299
                break;
            case 2: // homepage
300
                loadUrl(KUrl(ReKonfig::homePage()) , type);
301
302
303
                break;
            case 1: // blank page
            default:
304
                loadUrl(KUrl("about:blank") , type);
305
                break;
306
307
            }
        }
308
    }
309

310
    // ok, now last stuffs...
Andrea Diamantini's avatar
Andrea Diamantini committed
311
312
    if (isFirstLoad)
    {
313
        if (hasToBeRecoveredFromCrash && !incognito)
Andrea Diamantini's avatar
Andrea Diamantini committed
314
        {
315
            QTimer::singleShot(1000, tabWindow()->currentWebWindow(), SLOT(showCrashMessageBar()));
Andrea Diamantini's avatar
Andrea Diamantini committed
316
317
318
319
320
321
        }
        else
        {
            SessionManager::self()->setSessionManagementEnabled(true);
        }

322
        if (ReKonfig::checkDefaultSearchEngine() && !hasToBeRecoveredFromCrash && SearchEngine::defaultEngine().isNull())
323
            QTimer::singleShot(2000, tabWindow()->currentWebWindow()->tabView(), SLOT(showSearchEngineBar()));
324
325
326
327
328
329

        // updating rekonq configuration
        updateConfiguration();

        setWindowIcon(KIcon("rekonq"));

Andrea Diamantini's avatar
Andrea Diamantini committed
330
331
        // just create History Manager...
        HistoryManager::self();
332
333
334

        ReKonfig::setRecoverOnCrash(ReKonfig::recoverOnCrash() + 1);
        saveConfiguration();
Andrea Diamantini's avatar
Andrea Diamantini committed
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

    KStartupInfo::appStarted();
    isFirstLoad = false;

    return 0;
}


Application *Application::instance()
{
    return (qobject_cast<Application *>(QCoreApplication::instance()));
}


void Application::saveConfiguration() const
{
    ReKonfig::self()->writeConfig();
}


TabWindow *Application::tabWindow()
{
    TabWindow *active = qobject_cast<TabWindow*>(QApplication::activeWindow());

    if (!active)
    {
        if (m_tabWindows.isEmpty())
            return 0;

        Q_FOREACH(const QWeakPointer<TabWindow> &pointer, m_tabWindows)
        {
            if (KWindowInfo(pointer.data()->effectiveWinId(), NET::WMDesktop, 0).isOnCurrentDesktop())
                return pointer.data();
        }
        return m_tabWindows.at(0).data();
    }
    return active;
}


void Application::loadUrl(const KUrl& url, const Rekonq::OpenType& type)
{
    if (url.isEmpty())
        return;

    if (!url.isValid())
    {
        KMessageBox::error(0, i18n("Malformed URL:\n%1", url.url(KUrl::RemoveTrailingSlash)));
        return;
    }

    Rekonq::OpenType newType = type;
    // Don't open useless tabs or windows for actions in about: pages
    if (url.url().contains("about:") && url.url().contains("/"))
        newType = Rekonq::CurrentTab;

    TabWindow *w = 0;
393
394
395
396
397
398
    if (newType == Rekonq::NewPrivateWindow)
    {
        w = newTabWindow(true, true);
        newType = Rekonq::CurrentTab;
    }
    else if (newType == Rekonq::NewWindow
399
             || ((newType == Rekonq::NewTab || newType == Rekonq::NewFocusedTab) && tabWindowList().count() == 0))
400
401
402
403
404
405
406
407
408
409
410
411
412
    {
        w = newTabWindow();
        newType = Rekonq::CurrentTab;
    }
    else
    {
        w = tabWindow();
    }

    w->loadUrl(url, newType);
}


413
TabWindow *Application::newTabWindow(bool withTab, bool PrivateBrowsingMode)
414
{
415
    TabWindow *w = new TabWindow(withTab, PrivateBrowsingMode);
416
417
418

    // set object name
    int n = m_tabWindows.count() + 1;
419
    w->setObjectName(QL1S("win") + QString::number(n));
420

421
422
423
424
425
426
427
428
429
430
    // This is used to track which window was activated most recently
    w->installEventFilter(this);

    m_tabWindows.prepend(w);
    w->show();

    return w;
}


431
432
433
434
435
436
437
438
439
440
441
442
443
WebTab *Application::newWebApp()
{
    WebTab *tab = new WebTab;

    tab->installEventFilter(this);
    m_webApps.prepend(tab);

    tab->show();

    return tab;
}


444
445
446
447
448
449
TabWindowList Application::tabWindowList()
{
    return m_tabWindows;
}


450
451
452
453
454
455
WebAppList Application::webAppList()
{
    return m_webApps;
}


456
457
458
459
460
461
462
463
464
bool Application::eventFilter(QObject* watched, QEvent* event)
{
    // Track which window was activated most recently to prefer it on window choosing
    // (e.g. when another application opens a link)
    if (event->type() == QEvent::WindowActivate)
    {
        TabWindow *window = qobject_cast<TabWindow*>(watched);
        if (window)
        {
465
466
467
            if (!m_tabWindows.isEmpty() 
                && m_tabWindows.at(0) 
                && m_tabWindows.at(0).data() != window)
468
469
470
471
472
473
474
475
            {
                int index = m_tabWindows.indexOf(QWeakPointer<TabWindow>(window));
                Q_ASSERT(index != -1);
                m_tabWindows.prepend(m_tabWindows.takeAt(index));
            }
        }
    }

476
477
478
479
480
    // As we are filtering the events occurred to the tabwindows, check also
    // when we close one of them, remove from tab window list and check if it was last...
    if (event->type() == QEvent::Close)
    {
        TabWindow *window = qobject_cast<TabWindow*>(watched);
481
482
        if (window)
            m_tabWindows.removeOne(window);
483

484
485
        WebTab *webApp = qobject_cast<WebTab*>(watched);
        m_webApps.removeOne(webApp);
486

487
        if (m_tabWindows.count() == 0 && m_webApps.count() == 0)
488
489
490
            quit();
    }

491
492
493
494
495
496
    return QObject::eventFilter(watched, event);
}


void Application::updateConfiguration()
{
Andrea Diamantini's avatar
Andrea Diamantini committed
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
    // ============== Tabs ==================
    bool b = ReKonfig::closeTabSelectPrevious();
    Q_FOREACH(const QWeakPointer<TabWindow> &w, m_tabWindows)
    {
        if (b)
            w.data()->tabBar()->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
        else
            w.data()->tabBar()->setSelectionBehaviorOnRemove(QTabBar::SelectRightTab);
    }


    QWebSettings *defaultSettings = QWebSettings::globalSettings();

    // =========== Fonts ==============
    defaultSettings->setFontFamily(QWebSettings::StandardFont, ReKonfig::standardFontFamily());
    defaultSettings->setFontFamily(QWebSettings::FixedFont, ReKonfig::fixedFontFamily());
    defaultSettings->setFontFamily(QWebSettings::SerifFont, ReKonfig::serifFontFamily());
    defaultSettings->setFontFamily(QWebSettings::SansSerifFont, ReKonfig::sansSerifFontFamily());
    defaultSettings->setFontFamily(QWebSettings::CursiveFont, ReKonfig::cursiveFontFamily());
    defaultSettings->setFontFamily(QWebSettings::FantasyFont, ReKonfig::fantasyFontFamily());

    // compute font size
    // (I have to admit I know nothing about these DPI questions..: copied from kwebkitpart, as someone suggested)
    // font size in pixels =  font size in inches × screen dpi
    if (tabWindow() && tabWindow()->currentWebWindow())
    {
        int logDpiY = tabWindow()->currentWebWindow()->logicalDpiY();
        float toPix = (logDpiY < 96.0)
                      ? 96.0 / 72.0
                      : logDpiY / 72.0 ;

        int defaultFontSize = ReKonfig::defaultFontSize();
        int minimumFontSize = ReKonfig::minFontSize();

        defaultSettings->setFontSize(QWebSettings::DefaultFontSize, qRound(defaultFontSize * toPix));
        defaultSettings->setFontSize(QWebSettings::MinimumFontSize, qRound(minimumFontSize * toPix));
    }

    // encodings
    QString enc = ReKonfig::defaultEncoding();
    defaultSettings->setDefaultTextEncoding(enc);

    // ================ WebKit ============================
    defaultSettings->setAttribute(QWebSettings::DnsPrefetchEnabled, ReKonfig::dnsPrefetch());
    defaultSettings->setAttribute(QWebSettings::PrintElementBackgrounds, ReKonfig::printElementBackgrounds());
542
    defaultSettings->setAttribute(QWebSettings::ZoomTextOnly, ReKonfig::zoomTextOnly());
Andrea Diamantini's avatar
Andrea Diamantini committed
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576

    defaultSettings->setAttribute(QWebSettings::JavascriptEnabled, ReKonfig::javascriptEnabled());
    defaultSettings->setAttribute(QWebSettings::JavascriptCanOpenWindows, ReKonfig::javascriptCanOpenWindows());
    defaultSettings->setAttribute(QWebSettings::JavascriptCanAccessClipboard, ReKonfig::javascriptCanAccessClipboard());

    defaultSettings->setAttribute(QWebSettings::JavaEnabled, ReKonfig::javaEnabled());

    if (ReKonfig::pluginsEnabled() == 2)
        defaultSettings->setAttribute(QWebSettings::PluginsEnabled, false);
    else
        defaultSettings->setAttribute(QWebSettings::PluginsEnabled, true);

    // Enabling WebKit "Page Cache" feature: http://webkit.org/blog/427/webkit-page-cache-i-the-basics/
    defaultSettings->setMaximumPagesInCache(3);

    // ===== HTML 5 features WebKit support ======
    defaultSettings->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, ReKonfig::offlineStorageDatabaseEnabled());
    defaultSettings->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled, ReKonfig::offlineWebApplicationCacheEnabled());
    defaultSettings->setAttribute(QWebSettings::LocalStorageEnabled, ReKonfig::localStorageEnabled());
    if (ReKonfig::localStorageEnabled())
    {
        QString path = KStandardDirs::locateLocal("cache", QString("WebkitLocalStorage/rekonq"), true);
        path.remove("rekonq");
        QWebSettings::setOfflineStoragePath(path);
        QWebSettings::setOfflineStorageDefaultQuota(50000);
    }

    // ================= WebGl ===================
    defaultSettings->setAttribute(QWebSettings::WebGLEnabled, ReKonfig::webGL());
    defaultSettings->setAttribute(QWebSettings::AcceleratedCompositingEnabled, ReKonfig::webGL());

    // Applies user defined CSS to all open webpages.
    defaultSettings->setUserStyleSheetUrl(ReKonfig::userCSS());

Andrea Diamantini's avatar
Andrea Diamantini committed
577
578
    // ====== load Settings on main classes
    HistoryManager::self()->loadSettings();
Andrea Diamantini's avatar
Andrea Diamantini committed
579
580
581
582
583
584
585

    defaultSettings = 0;

    if (!tabWindow())
        return;

    // FIXME What about this?
586
587
588
589
//     ReKonfig::useFavicon()
//     ? tabWindow()->changeWindowIcon(tabWindow()->mainView()->currentIndex())
//     : tabWindow()->setWindowIcon(KIcon("rekonq"))
//     ;
590
//
Andrea Diamantini's avatar
Andrea Diamantini committed
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
    // hovering unfocused tabs options
    switch (ReKonfig::hoveringTabOption())
    {
    case 0: // tab previews
    case 3: // nothing
        for (int i = 0; i < tabWindow()->tabBar()->count(); i++)
        {
            tabWindow()->tabBar()->setTabToolTip(i, QL1S(""));
        }
        break;

    case 1: // title previews
        for (int i = 0; i < tabWindow()->tabBar()->count(); i++)
        {
            tabWindow()->tabBar()->setTabToolTip(i, tabWindow()->tabText(i).remove('&'));
        }
        break;

    case 2: // url previews
        for (int i = 0; i < tabWindow()->tabBar()->count(); i++)
        {
            tabWindow()->tabBar()->setTabToolTip(i, tabWindow()->webWindow(i)->url().toMimeDataString());
        }
        break;

    default: // non extant case
        ASSERT_NOT_REACHED(unknown hoveringTabOption);
        break;
    }
620
621
622
623
624
625

}


void Application::queryQuit()
{
626
627
628
    if (m_webApps.count() > 0)
    {
        tabWindow()->close();
629
        return;
630
    }
631

632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
    if (tabWindowList().count() > 1)
    {
        int answer = KMessageBox::questionYesNoCancel(
                         tabWindow(),
                         i18n("Do you want to close the window or the whole application?"),
                         i18n("Application/Window closing..."),
                         KGuiItem(i18n("C&lose Current Window"),
                                  KIcon("window-close")),
                         KStandardGuiItem::quit(),
                         KStandardGuiItem::cancel(),
                         "confirmClosingMultipleWindows"
                     );

        switch (answer)
        {
        case KMessageBox::Yes:
            tabWindow()->close();
            return;

        case KMessageBox::No:
            break;

        default:
            return;
        }
    }

    // in case of just one window...
    quit();
}
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738


void Application::clearPrivateData()
{
    QPointer<KDialog> dialog = new KDialog(tabWindow());
    dialog->setCaption(i18nc("@title:window", "Clear Private Data"));
    dialog->setButtons(KDialog::Ok | KDialog::Cancel);

    dialog->button(KDialog::Ok)->setIcon(KIcon("edit-clear"));
    dialog->button(KDialog::Ok)->setText(i18n("Clear"));

    Ui::ClearDataWidget clearWidget;
    QWidget widget;
    clearWidget.setupUi(&widget);
    clearWidget.clearHistory->setChecked(ReKonfig::clearHistory());
    clearWidget.clearDownloads->setChecked(ReKonfig::clearDownloads());
    clearWidget.clearCookies->setChecked(ReKonfig::clearCookies());
    clearWidget.clearCachedPages->setChecked(ReKonfig::clearCachedPages());
    clearWidget.clearWebIcons->setChecked(ReKonfig::clearWebIcons());
    clearWidget.homePageThumbs->setChecked(ReKonfig::clearHomePageThumbs());

    dialog->setMainWidget(&widget);
    dialog->exec();

    if (dialog->result() == QDialog::Accepted)
    {
        //Save current state
        ReKonfig::setClearHistory(clearWidget.clearHistory->isChecked());
        ReKonfig::setClearDownloads(clearWidget.clearDownloads->isChecked());
        ReKonfig::setClearCookies(clearWidget.clearDownloads->isChecked());
        ReKonfig::setClearCachedPages(clearWidget.clearCachedPages->isChecked());
        ReKonfig::setClearWebIcons(clearWidget.clearWebIcons->isChecked());
        ReKonfig::setClearHomePageThumbs(clearWidget.homePageThumbs->isChecked());

        if (clearWidget.clearHistory->isChecked())
        {
            HistoryManager::self()->clear();
        }

        if (clearWidget.clearDownloads->isChecked())
        {
            DownloadManager::self()->clearDownloadsHistory();
        }

        if (clearWidget.clearCookies->isChecked())
        {
            QDBusInterface kcookiejar("org.kde.kded", "/modules/kcookiejar", "org.kde.KCookieServer");
            QDBusReply<void> reply = kcookiejar.call("deleteAllCookies");
        }

        if (clearWidget.clearCachedPages->isChecked())
        {
            KProcess::startDetached(KStandardDirs::findExe("kio_http_cache_cleaner"),
                                    QStringList(QL1S("--clear-all")));
        }

        if (clearWidget.clearWebIcons->isChecked())
        {
            IconManager::self()->clearIconCache();
        }

        if (clearWidget.homePageThumbs->isChecked())
        {
            QString path = KStandardDirs::locateLocal("cache", QString("thumbs/rekonq"), true);
            path.remove("rekonq");
            QDir cacheDir(path);
            QStringList fileList = cacheDir.entryList();
            Q_FOREACH(const QString & str, fileList)
            {
                QFile file(path + str);
                file.remove();
            }
        }
    }

    dialog->deleteLater();
}
Andrea Diamantini's avatar
Andrea Diamantini committed
739
740
741
742
743
744
745
746
747
748
749
750


void Application::createWebAppShortcut()
{
    KUrl u = tabWindow()->currentWebWindow()->url();
    QString h = u.host();

    QPointer<KDialog> dialog = new KDialog(tabWindow());
    dialog->setCaption(i18nc("@title:window", "Create Application Shortcut"));
    dialog->setButtons(KDialog::Ok | KDialog::Cancel);
    dialog->button(KDialog::Ok)->setText(i18n("Create"));
    dialog->setMinimumSize(400, 50);
751
    dialog->setWindowIcon(QIcon(IconManager::self()->iconForUrl(u).pixmap(16)));
Andrea Diamantini's avatar
Andrea Diamantini committed
752
753
754
755
756

    Ui::webAppCreation wAppWidget;
    QWidget widget;
    wAppWidget.setupUi(&widget);

757
758
    QString webAppTitle = tabWindow()->currentWebWindow()->title().remove('&');
    wAppWidget.nameLineEdit->setText(webAppTitle);
Andrea Diamantini's avatar
Andrea Diamantini committed
759
760
761
762
763
764
765
766
767
768
769
770
771
772
    wAppWidget.kcfg_createDesktopAppShortcut->setChecked(ReKonfig::createDesktopAppShortcut());
    wAppWidget.kcfg_createMenuAppShortcut->setChecked(ReKonfig::createMenuAppShortcut());

    dialog->setMainWidget(&widget);
    dialog->exec();

    if (dialog->result() == QDialog::Accepted)
    {
        ReKonfig::setCreateDesktopAppShortcut(wAppWidget.kcfg_createDesktopAppShortcut->isChecked());
        ReKonfig::setCreateMenuAppShortcut(wAppWidget.kcfg_createMenuAppShortcut->isChecked());

        IconManager::self()->saveDesktopIconForUrl(u);
        QString iconPath = KStandardDirs::locateLocal("cache" , "favicons/" , true) + h + QL1S("_WEBAPPICON.png");

773
774
775
776
777
778
        if (!wAppWidget.nameLineEdit->text().isEmpty())
            webAppTitle = wAppWidget.nameLineEdit->text();

        QString webAppDescription;
        if (!wAppWidget.descriptionLineEdit->text().isEmpty())
            webAppDescription = wAppWidget.descriptionLineEdit->text();
779

Andrea Diamantini's avatar
Andrea Diamantini committed
780
781
        QString shortcutString = QL1S("#!/usr/bin/env xdg-open\n")
                                 + QL1S("[Desktop Entry]\n")
782
                                 + QL1S("Name=") + webAppTitle
Andrea Diamantini's avatar
Andrea Diamantini committed
783
                                 + QL1S("\n")
784
                                 + QL1S("GenericName=") + webAppDescription
Andrea Diamantini's avatar
Andrea Diamantini committed
785
786
                                 + QL1S("\n")
                                 + QL1S("Icon=") + iconPath + QL1S("\n")
787
                                 + QL1S("Exec=rekonq --webapp ") + u.url() + QL1S("\n")
Andrea Diamantini's avatar
Andrea Diamantini committed
788
789
790
791
792
793
794
                                 + QL1S("Type=Application\n")
                                 + QL1S("Categories=Application;Network\n")
                                 ;

        if (ReKonfig::createDesktopAppShortcut())
        {
            QString desktop = KGlobalSettings::desktopPath();
795
            QFile wAppFile(desktop + QL1C('/') + webAppTitle);
Andrea Diamantini's avatar
Andrea Diamantini committed
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813

            if (!wAppFile.open(QIODevice::WriteOnly | QIODevice::Text))
            {
                kDebug() << "Unable to open file: " << wAppFile.errorString();
                return;
            }

            QTextStream out(&wAppFile);
            out.setCodec("UTF-8");
            out << shortcutString;

            wAppFile.setPermissions(QFile::ReadUser | QFile::WriteUser | QFile::ExeUser | QFile::ReadGroup | QFile::ReadOther);
            wAppFile.close();
        }

        if (ReKonfig::createMenuAppShortcut())
        {
            QString appMenuDir = KStandardDirs::locateLocal("xdgdata-apps", QString());
814
            QFile wAppFile(appMenuDir + QL1C('/') + webAppTitle + QL1S(".desktop"));
Andrea Diamantini's avatar
Andrea Diamantini committed
815
816
817
818
819
820
821
822
823
824
825
826
827

            if (!wAppFile.open(QIODevice::WriteOnly | QIODevice::Text))
            {
                kDebug() << "Unable to open file: " << wAppFile.errorString();
                return;
            }

            QTextStream out(&wAppFile);
            out.setCodec("UTF-8");
            out << shortcutString;

            wAppFile.close();
        }
828

Andrea Diamantini's avatar
Andrea Diamantini committed
829
830
831
832
    }

    dialog->deleteLater();
}
833
834
835
836
837
838


void Application::bookmarksToolbarToggled(bool b)
{
    emit toggleBookmarksToolbar(b);
}
Andrea Diamantini's avatar
Andrea Diamantini committed
839
840


841
842
void Application::newPrivateBrowsingWindow()
{
843
    // NOTE: what about an "about:incognito" page?
844
    loadUrl(KUrl("about:home"), Rekonq::NewPrivateWindow);
845
}
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873


void Application::pageCreated(WebPage *pg)
{
    if (m_tabWindows.isEmpty())
    {
        // NOTE: This is "adjusted" from newTabWindow() code...
        TabWindow *w = new TabWindow(pg);

        // set object name
        int n = m_tabWindows.count() + 1;
        w->setObjectName(QL1S("win") + QString::number(n));

        // This is used to track which window was activated most recently
        w->installEventFilter(this);

        m_tabWindows.prepend(w);
        w->show();

        return;
    }

    TabWindow *tw = tabWindow();
    tw->newTab(pg);

    tw->activateWindow();
    tw->raise();
}