summaryrefslogtreecommitdiff
path: root/src/tabwindow/tabwindow.cpp
blob: 59aa1275d8edf6965be329fe2ccbb06dcdd696d0 (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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
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
542
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
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
620
621
622
623
624
625
626
627
628
629
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
/* ============================================================
*
* 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 "tabwindow.h"
#include "tabwindow.moc"

// Auto Includes
#include "rekonq.h"

// Local Includes
#include "application.h"
#include "webpage.h"
#include "webwindow.h"
#include "tabbar.h"

#include "tabhistory.h"

#include "bookmarkmanager.h"
#include "iconmanager.h"

// KDE Includes
#include <KAction>
#include <KApplication>
#include <KConfig>
#include <KConfigGroup>
#include <KLocalizedString>
#include <KStandardDirs>
#include <KUrl>
#include <KToggleFullScreenAction>

#include <KBookmark>
#include <KBookmarkGroup>

#include <KWindowInfo>
#include <KWindowSystem>

// Qt Includes
#include <QDesktopWidget>
#include <QLabel>
#include <QMovie>
#include <QTabBar>
#include <QToolButton>

#include <QWebHistory>
#include <QWebSettings>


TabWindow::TabWindow(bool withTab, bool PrivateBrowsingMode, QWidget *parent)
    : RekonqWindow(parent)
    , _addTabButton(new QToolButton(this))
    , _openedTabsCounter(0)
    , _isPrivateBrowsing(PrivateBrowsingMode)
    , _ac(new KActionCollection(this))
{
    init();

    // NOTE: we usually create TabWindow with AT LEAST one tab, but
    // in one important case...
    if (withTab)
    {
        WebWindow *tab = prepareNewTab();
        addTab(tab, i18n("new tab"));
        setCurrentWidget(tab);
    }
}


TabWindow::TabWindow(WebPage *pg, QWidget *parent)
    : RekonqWindow(parent)
    , _addTabButton(new QToolButton(this))
    , _openedTabsCounter(0)
    , _isPrivateBrowsing(false)
    , _ac(new KActionCollection(this))
{
    init();

    WebWindow *tab = prepareNewTab(pg);
    addTab(tab, i18n("new tab"));
    setCurrentWidget(tab);
}


void TabWindow::init()
{
    setContentsMargins(0, 0, 0, 0);

    setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);

    // set mouse tracking for tab previews
    setMouseTracking(true);

    // setting tabbar
    TabBar *tabBar = new TabBar(this);
    setTabBar(tabBar);

    // sets document mode; this removes the frame around the tabs
    setDocumentMode(true);

    // connecting tabbar signals
    connect(tabBar, SIGNAL(tabCloseRequested(int)), this,   SLOT(closeTab(int)));
    connect(tabBar, SIGNAL(mouseMiddleClick(int)),  this,   SLOT(closeTab(int)));

    connect(tabBar, SIGNAL(newTabRequest()),        this,   SLOT(newTab()));

    connect(tabBar, SIGNAL(cloneTab(int)),          this,   SLOT(cloneTab(int)));
    connect(tabBar, SIGNAL(closeTab(int)),          this,   SLOT(closeTab(int)));
    connect(tabBar, SIGNAL(closeOtherTabs(int)),    this,   SLOT(closeOtherTabs(int)));
    connect(tabBar, SIGNAL(reloadTab(int)),         this,   SLOT(reloadTab(int)));
    connect(tabBar, SIGNAL(detachTab(int)),         this,   SLOT(detachTab(int)));

    connect(tabBar, SIGNAL(tabLayoutChanged()),     this,   SLOT(updateNewTabButtonPosition()));

    // ============================== Tab Window Actions ====================================
    _ac->addAssociatedWidget(this);

    KAction* a;

    a = new KAction(KIcon("tab-new"), i18n("New &Tab"), this);
    a->setShortcut(KShortcut(Qt::CTRL + Qt::Key_T));
    actionCollection()->addAction(QL1S("new_tab"), a);
    connect(a, SIGNAL(triggered(bool)), this, SLOT(newTab()));

    a = new KAction(KIcon("tab-new"), i18n("Open Last Closed Tab"), this);
    a->setShortcut(KShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_T));
    actionCollection()->addAction(QL1S("open_last_closed_tab"), a);
    connect(a, SIGNAL(triggered(bool)), this, SLOT(restoreLastClosedTab()));

    a = new KAction(KIcon("tab-close"), i18n("&Close Tab"), this);
    a->setShortcuts(KStandardShortcut::close());
    actionCollection()->addAction(QL1S("close_tab"), a);
    connect(a, SIGNAL(triggered(bool)), this, SLOT(closeTab()));

    a = KStandardAction::fullScreen(this, SLOT(setFullScreen(bool)), this, actionCollection());
    KShortcut fullScreenShortcut = KStandardShortcut::fullScreen();
    fullScreenShortcut.setAlternate(Qt::Key_F11);
    a->setShortcut(fullScreenShortcut);

    a = new KAction(KIcon("bookmarks"), i18n("Bookmark all tabs"), this);
    actionCollection()->addAction(QL1S("bookmark_all_tabs"), a);
    connect(a, SIGNAL(triggered(bool)), this, SLOT(bookmarkAllTabs()));

    // ----------------------------------------------------------------------------------------------
    // Add Tab Button
    _addTabButton->setDefaultAction(actionByName(QL1S("new_tab")));
    _addTabButton->setAutoRaise(true);
    _addTabButton->raise();
    _addTabButton->setToolButtonStyle(Qt::ToolButtonIconOnly);

    connect(this, SIGNAL(currentChanged(int)), this, SLOT(currentChanged(int)));
}


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


KActionCollection *TabWindow::actionCollection() const
{
    return _ac;
}


QAction *TabWindow::actionByName(const QString &name)
{
    return actionCollection()->action(name);
}


TabBar *TabWindow::tabBar() const
{
    TabBar *tabBar = qobject_cast<TabBar *>(QTabWidget::tabBar());
    return tabBar;
}


WebWindow *TabWindow::currentWebWindow() const
{
    return webWindow(currentIndex());
}


WebWindow *TabWindow::webWindow(int index) const
{
    WebWindow *tab = qobject_cast<WebWindow *>(this->widget(index));
    if (tab)
    {
        return tab;
    }

    kDebug() << "WebWindow with index " << index << "not found. Returning NULL." ;
    return 0;
}


WebWindow *TabWindow::prepareNewTab(WebPage *page)
{
    WebWindow *tab = new WebWindow(this, page);

    if (_isPrivateBrowsing)
        tab->setPrivateBrowsing(true);

    connect(tab, SIGNAL(titleChanged(QString)), this, SLOT(tabTitleChanged(QString)));

    connect(tab, SIGNAL(loadStarted()), this, SLOT(tabLoadStarted()));
    connect(tab, SIGNAL(loadFinished(bool)), this, SLOT(tabLoadFinished(bool)));

    connect(tab, SIGNAL(pageCreated(WebPage *)), this, SLOT(pageCreated(WebPage *)));

    connect(tab, SIGNAL(setFullScreen(bool)), this, SLOT(setFullScreen(bool)));

    return tab;
}


void TabWindow::loadUrl(const KUrl &url, Rekonq::OpenType type, TabHistory *history)
{
    WebWindow *tab = 0;
    switch (type)
    {
    case Rekonq::NewTab:
    case Rekonq::NewBackGroundTab:
        tab = prepareNewTab();
        _openedTabsCounter++;
        insertTab(currentIndex() + _openedTabsCounter, tab, i18n("new tab"));
        break;

    case Rekonq::NewFocusedTab:
        tab = prepareNewTab();
        _openedTabsCounter++;
        insertTab(currentIndex() + _openedTabsCounter, tab, i18n("new tab"));
        setCurrentWidget(tab);
        break;

    case Rekonq::NewWindow:
    case Rekonq::NewPrivateWindow:
        rApp->loadUrl(url, type);
        return;

    case Rekonq::CurrentTab:
    default:
        tab = currentWebWindow();
        break;
    };

    tab->load(url);

    if (history)
    {
        history->applyHistory(tab->page()->history());
    }
}


void TabWindow::newTab(WebPage *page)
{
    WebWindow *tab = prepareNewTab(page);
    addTab(tab, i18n("new tab"));
    setCurrentWidget(tab);

    // no need to load an url if we already have a page...
    if (page)
        return;

    switch (ReKonfig::newTabsBehaviour())
    {
    case 0: // new tab page
        tab->load(KUrl("about:home"));
        break;
    case 2: // homepage
        tab->load(KUrl(ReKonfig::homePage()));
        break;
    case 1: // blank page
    default:
        tab->load(KUrl("about:blank"));
        break;
    }

}


void TabWindow::pageCreated(WebPage *page)
{
    WebWindow *tab = prepareNewTab(page);

    // Now, the dirty jobs...
    _openedTabsCounter++;
    insertTab(currentIndex() + _openedTabsCounter, tab, i18n("new tab"));

    setCurrentWidget(tab);
}


void TabWindow::currentChanged(int newIndex)
{
    _openedTabsCounter = 0;

    tabBar()->setTabHighlighted(newIndex, false);

    // update window title & icon
    WebWindow* tab = webWindow(newIndex);
    if (!tab)
        return;

    QString t = tab->title();

    (t.isEmpty() || t == QL1S("rekonq"))
    ? setWindowTitle(QL1S("rekonq"))
    : setWindowTitle(t + QL1S(" - rekonq"));

    tab->checkFocus();
}


void TabWindow::updateNewTabButtonPosition()
{
    if (isFullScreen())
        return;

    setUpdatesEnabled(false);

    int tabWidgetWidth = frameSize().width();
    int tabBarWidth = tabBar()->sizeHint().width();

    if (tabBarWidth + _addTabButton->width() > tabWidgetWidth)
    {
        setCornerWidget(_addTabButton);
    }
    else
    {
        setCornerWidget(0);
        _addTabButton->move(tabBarWidth, 0);
    }

    _addTabButton->show();
    setUpdatesEnabled(true);
}


void TabWindow::tabTitleChanged(const QString &title)
{
    WebWindow *tab = qobject_cast<WebWindow *>(sender());
    if (!tab)
        return;

    QString tabTitle = title.isEmpty() ? tab->title() : title;
    tabTitle.replace('&', "&&");

    int index = indexOf(tab);
    if (-1 != index && !tabBar()->tabData(index).toBool())
    {
        setTabText(index, tabTitle);
    }

    if (currentIndex() != index)
    {
        tabBar()->setTabHighlighted(index, true);
    }
    else
    {
        setWindowTitle(tabTitle + QL1S(" - rekonq"));
    }
}


void TabWindow::tabLoadStarted()
{
    WebWindow *tab = qobject_cast<WebWindow *>(sender());
    if (!tab)
        return;

    int index = indexOf(tab);
    if (index != -1)
    {
        QLabel *label = qobject_cast<QLabel* >(tabBar()->tabButton(index, QTabBar::LeftSide));
        if (!label)
        {
            label = new QLabel(this);
        }

        if (!label->movie())
        {
            static QString loadingGitPath = KStandardDirs::locate("appdata" , "pics/loading.mng");

            QMovie *movie = new QMovie(loadingGitPath, QByteArray(), label);
            movie->setSpeed(50);
            label->setMovie(movie);
            movie->start();
        }

        tabBar()->setTabButton(index, QTabBar::LeftSide, 0);
        tabBar()->setTabButton(index, QTabBar::LeftSide, label);

        if (!tabBar()->tabData(index).toBool())
            tabBar()->setTabText(index, i18n("Loading..."));
        else
        {
            tabBar()->tabButton(index, QTabBar::RightSide)->hide(); // NOTE: not really good this, but..."Repetita iuvant"!!!
        }
    }
}


void TabWindow::tabLoadFinished(bool ok)
{
    Q_UNUSED(ok);

    WebWindow *tab = qobject_cast<WebWindow *>(sender());
    if (!tab)
        return;

    int index = indexOf(tab);

    if (-1 == index)
        return;

    QLabel *label = qobject_cast<QLabel* >(tabBar()->tabButton(index, QTabBar::LeftSide));
    if (!label)
    {
        label = new QLabel(this);
        tabBar()->setTabButton(index, QTabBar::LeftSide, 0);
        tabBar()->setTabButton(index, QTabBar::LeftSide, label);
    }

    QMovie *movie = label->movie();
    if (movie)
    {
        movie->stop();
        delete movie;
    }

    label->setMovie(0);

    KIcon ic = IconManager::self()->iconForUrl(tab->url());
    label->setPixmap(ic.pixmap(16, 16));

    if (!tabBar()->tabData(index).toBool())
    {
        setTabText(index, tab->title());
    }
    else
    {
        setTabText(index, QString());
    }

    if (index == currentIndex())
        tab->checkFocus();
}


void TabWindow::cloneTab(int index)
{
    if (index < 0)
        index = currentIndex();
    if (index < 0 || index >= count())
        return;

    QUrl u = webWindow(index)->url();
    QWebHistory* history = webWindow(index)->page()->history();
    TabHistory clonedHistory(history);

    loadUrl(u, Rekonq::NewTab, &clonedHistory);
}


void TabWindow::closeTab(int index, bool del)
{
    if (index < 0)
        index = currentIndex();
    if (index < 0 || index >= count())
        return;

    WebWindow *tabToClose = webWindow(index);
    if (!tabToClose)
        return;

    // what to do if there is just one tab...
    if (count() == 1)
    {
        kDebug() << "CANNOT CLOSE WINDOW FROM HERE...";
        currentWebWindow()->load(KUrl("about:home"));
        return;
    }

    if (!tabToClose->url().isEmpty()
            && tabToClose->url().scheme() != QL1S("about")
            && !tabToClose->page()->settings()->testAttribute(QWebSettings::PrivateBrowsingEnabled)
       )
    {
        const int recentlyClosedTabsLimit = 8;
        TabHistory history(tabToClose->page()->history());
        history.title = tabToClose->title();
        history.url = tabToClose->url().url();
        history.position = index;

        m_recentlyClosedTabs.removeAll(history);
        if (m_recentlyClosedTabs.count() == recentlyClosedTabsLimit)
            m_recentlyClosedTabs.removeLast();
        m_recentlyClosedTabs.prepend(history);
    }

    removeTab(index);

    if (del)
    {
        tabToClose->deleteLater();
    }
}


void TabWindow::closeOtherTabs(int index)
{
    if (index < 0)
        index = currentIndex();
    if (index < 0 || index >= count())
        return;

    for (int i = count() - 1; i > index; --i)
    {
        closeTab(i);
    }

    for (int i = index - 1; i >= 0; --i)
    {
        closeTab(i);
    }
}


void TabWindow::detachTab(int index, TabWindow *toWindow)
{
    if (index < 0)
        index = currentIndex();
    if (index < 0 || index >= count())
        return;

    WebWindow *tab = webWindow(index);
    KUrl u = tab->url();
    if (u.scheme() == QL1S("about"))
    {
        closeTab(index);
        loadUrl(u, Rekonq::NewWindow);
        return;
    }
    // else

    closeTab(index, false);

    TabWindow *w = 0;
    w = (toWindow == 0)
        ? new TabWindow(false)
        : toWindow;

    w->addTab(tab, tab->title());
    w->setCurrentWidget(tab);

    // disconnect signals from old tabwindow
    // WARNING: Code copied from prepareNewTab method.
    // Any new changes there should be applied here...
    disconnect(tab, SIGNAL(titleChanged(QString)), this, SLOT(tabTitleChanged(QString)));
    disconnect(tab, SIGNAL(loadStarted()), this, SLOT(tabLoadStarted()));
    disconnect(tab, SIGNAL(loadFinished(bool)), this, SLOT(tabLoadFinished(bool)));
    disconnect(tab, SIGNAL(pageCreated(WebPage *)), this, SLOT(pageCreated(WebPage *)));

    // reconnect signals to new tabwindow
    // WARNING: Code copied from prepareNewTab method.
    // Any new changes there should be applied here...
    connect(tab, SIGNAL(titleChanged(QString)), w, SLOT(tabTitleChanged(QString)));
    connect(tab, SIGNAL(loadStarted()), w, SLOT(tabLoadStarted()));
    connect(tab, SIGNAL(loadFinished(bool)), w, SLOT(tabLoadFinished(bool)));
    connect(tab, SIGNAL(pageCreated(WebPage *)), w, SLOT(pageCreated(WebPage *)));

    w->show();
}


void TabWindow::reloadTab(int index)
{
    // When index is -1 index chooses the current tab
    if (index < 0)
        index = currentIndex();

    if (index < 0 || index >= count())
        return;

    WebWindow *reloadingTab = webWindow(index);
    QAction *action = reloadingTab->page()->action(QWebPage::Reload);
    action->trigger();
}


void TabWindow::reloadAllTabs()
{
    for (int i = 0; i < count(); ++i)
    {
        reloadTab(i);
    }
}


void TabWindow::bookmarkAllTabs()
{
    KBookmarkGroup rGroup = BookmarkManager::self()->rootGroup();
    KBookmarkGroup folderGroup = rGroup.createNewFolder(i18n("Bookmarked tabs: ") + QDate::currentDate().toString());
    for (int i = 0; i < count(); ++i)
    {
        WebWindow *tab = webWindow(i);
        KBookmark bk = folderGroup.addBookmark(tab->title(), tab->url());
    }
}


void TabWindow::restoreLastClosedTab()
{
    if (m_recentlyClosedTabs.isEmpty())
        return;

    TabHistory history = m_recentlyClosedTabs.takeAt(0);

    QUrl u = QUrl(history.url);

    int restorePosition = history.position;

    WebWindow *tab = prepareNewTab();

    if (restorePosition < count())
        insertTab(restorePosition, tab, i18n("restored tab"));
    else
        addTab(tab, i18n("restored tab"));

    setCurrentWidget(tab);

    tab->load(u);

    // just to get sure...
    m_recentlyClosedTabs.removeAll(history);
}


void TabWindow::setFullScreen(bool makeFullScreen)
{
    tabBar()->setVisible(!makeFullScreen);
    _addTabButton->setVisible(!makeFullScreen);

    KToggleFullScreenAction::setFullScreen(this, makeFullScreen);

    for (int i = 0; i < count(); i++)
        webWindow(i)->setWidgetsHidden(makeFullScreen);
}


bool TabWindow::isPrivateBrowsingWindowMode()
{
    return _isPrivateBrowsing;
}