Added actions to switch to Tab #n
[rekonq:nikhilms-mainline.git] / src / mainwindow.cpp
1 /* ============================================================
2 *
3 * This file is a part of the rekonq project
4 *
5 * Copyright (C) 2008-2010 by Andrea Diamantini <adjam7 at gmail dot com>
6 * Copyright (C) 2009 by Paweł Prażak <pawelprazak at gmail dot com>
7 * Copyright (C) 2009-2010 by Lionel Chauvin <megabigbug@yahoo.fr>
8 * Copyright (C) 2010 by Matthieu Gicquel <matgic78 at gmail dot com>
9 *
10 *
11 * This program is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU General Public License as
13 * published by the Free Software Foundation; either version 2 of
14 * the License or (at your option) version 3 or any later version
15 * accepted by the membership of KDE e.V. (or its successor approved
16 * by the membership of KDE e.V.), which shall act as a proxy
17 * defined in Section 14 of version 3 of the license.
18 *
19 * This program 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
22 * GNU General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
26 *
27 * ============================================================ */
28
29
30 // Self Includes
31 #include "mainwindow.h"
32 #include "mainwindow.moc"
33
34 // Auto Includes
35 #include "rekonq.h"
36
37 // Local Includes
38 #include "settingsdialog.h"
39 #include "historymanager.h"
40 #include "bookmarksmanager.h"
41 #include "webtab.h"
42 #include "mainview.h"
43 #include "findbar.h"
44 #include "historypanel.h"
45 #include "bookmarkspanel.h"
46 #include "webinspectorpanel.h"
47 #include "urlbar.h"
48 #include "tabbar.h"
49 #include "adblockmanager.h"
50 #include "analyzerpanel.h"
51
52 // Ui Includes
53 #include "ui_cleardata.h"
54
55 // KDE Includes
56 #include <KShortcut>
57 #include <KStandardAction>
58 #include <KAction>
59 #include <KToggleFullScreenAction>
60 #include <KActionCollection>
61 #include <KMessageBox>
62 #include <KFileDialog>
63 #include <KGlobalSettings>
64 #include <KPushButton>
65 #include <KTemporaryFile>
66 #include <KPassivePopup>
67 #include <KMenuBar>
68 #include <KJobUiDelegate>
69 #include <kdeprintdialog.h>
70 #include <KToggleAction>
71 #include <KStandardDirs>
72 #include <KActionCategory>
73 #include <KProcess>
74
75 // Qt Includes
76 #include <QtCore/QTimer>
77 #include <QtCore/QRect>
78 #include <QtCore/QSize>
79 #include <QtCore/QList>
80 #include <QtCore/QWeakPointer>
81
82 #include <QtGui/QVBoxLayout>
83 #include <QtGui/QFont>
84 #include <QtGui/QDesktopWidget>
85 #include <QtGui/QPrinter>
86 #include <QtGui/QPrintDialog>
87 #include <QtGui/QPrintPreviewDialog>
88 #include <QtGui/QFontMetrics>
89
90 #include <QtDBus/QDBusInterface>
91 #include <QtDBus/QDBusReply>
92
93 #include <QtWebKit/QWebHistory>
94
95
96 MainWindow::MainWindow()
97         : KMainWindow()
98         , m_view(new MainView(this))
99         , m_findBar(new FindBar(this))
100         , m_historyPanel(0)
101         , m_bookmarksPanel(0)
102         , m_webInspectorPanel(0)
103         , m_analyzerPanel(0)
104         , m_historyBackMenu(0)
105         , m_encodingMenu(new KMenu(this))
106         , m_mainBar(new KToolBar(QString("MainToolBar"), this, Qt::TopToolBarArea, true, true, true))
107         , m_bmBar(new KToolBar(QString("BookmarkToolBar"), this, Qt::TopToolBarArea, true, false, true))
108         , m_popup(new KPassivePopup(this))
109         , m_hidePopup(new QTimer(this))
110         , m_ac(new KActionCollection(this))
111 {
112     // enable window size "auto-save"
113     setAutoSaveSettings();
114
115     // creating a centralWidget containing panel, m_view and the hidden findbar
116     QWidget *centralWidget = new QWidget;
117     centralWidget->setContentsMargins(0, 0, 0, 0);
118
119     // setting layout
120     QVBoxLayout *layout = new QVBoxLayout;
121     layout->setContentsMargins(0, 0, 0, 0);
122     layout->addWidget(m_view);
123     layout->addWidget(m_findBar);
124     centralWidget->setLayout(layout);
125
126     // central widget
127     setCentralWidget(centralWidget);
128
129     // setting size policies
130     setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
131
132     // then, setup our actions
133     setupActions();
134
135     // setting Panels
136     setupPanels();
137
138     // setting up rekonq tools
139     setupTools();
140
141     // setting up rekonq toolbar(s)
142     setupToolbars();
143
144     // no more status bar..
145     setStatusBar(0);
146
147     // setting popup notification
148     m_popup->setAutoDelete(false);
149     connect(Application::instance(), SIGNAL(focusChanged(QWidget*, QWidget*)), m_popup, SLOT(hide()));
150     m_popup->setFrameShape(QFrame::NoFrame);
151     m_popup->setLineWidth(0);
152     connect(m_hidePopup, SIGNAL(timeout()), m_popup, SLOT(hide()));
153
154     QTimer::singleShot(0, this, SLOT(postLaunch()));
155 }
156
157
158 MainWindow::~MainWindow()
159 {
160     Application::bookmarkProvider()->removeToolBar(m_bmBar);
161     Application::instance()->removeMainWindow(this);
162     
163     delete m_view;
164     delete m_findBar;
165
166     delete m_historyPanel;
167     delete m_bookmarksPanel;
168     delete m_webInspectorPanel;
169
170     delete m_stopReloadAction;
171     delete m_historyBackMenu;
172     delete m_encodingMenu;
173
174     delete m_mainBar;
175     delete m_bmBar;
176
177     delete m_zoomSlider;
178
179     delete m_popup;
180     delete m_hidePopup;
181
182     delete m_ac;
183 }
184
185
186 void MainWindow::setupToolbars()
187 {
188     // ============ Main ToolBar  ================================
189     m_mainBar->addAction(actionByName(KStandardAction::name(KStandardAction::Back)));
190     m_mainBar->addAction(actionByName(KStandardAction::name(KStandardAction::Forward)));
191     m_mainBar->addSeparator();
192     m_mainBar->addAction(actionByName( QL1S("stop_reload") ));
193     m_mainBar->addAction(actionByName(KStandardAction::name(KStandardAction::Home)));
194
195     // location bar
196     KAction *urlBarAction = new KAction(this);
197     urlBarAction->setDefaultWidget(m_view->widgetBar());
198     m_mainBar->addAction(urlBarAction);
199
200     m_mainBar->addAction(actionByName( QL1S("bookmarksActionMenu") ));
201     m_mainBar->addAction(actionByName( QL1S("rekonq_tools") ));
202
203     m_mainBar->show();  // this just to fix reopening rekonq after fullscreen close
204
205     // =========== Bookmarks ToolBar ================================
206     m_bmBar->setAcceptDrops(true);
207     Application::bookmarkProvider()->setupBookmarkBar(m_bmBar);
208
209     if (ReKonfig::firstExecution())
210     {
211         m_mainBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
212
213         m_bmBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
214         m_bmBar->setIconDimensions(16);
215         m_bmBar->hide();
216
217         KToolBar::setToolBarsEditable(false);
218         KToolBar::setToolBarsLocked(true);
219
220         ReKonfig::setFirstExecution(false);
221     }
222 }
223
224
225 void MainWindow::postLaunch()
226 {
227     // KActionCollection read settings
228     m_ac->readSettings();
229
230     // notification system
231     connect(m_view, SIGNAL(showStatusBarMessage(const QString&, Rekonq::Notify)), this, SLOT(notifyMessage(const QString&, Rekonq::Notify)));
232     connect(m_view, SIGNAL(linkHovered(const QString&)), this, SLOT(notifyMessage(const QString&)));
233
234     // --------- connect signals and slots
235     connect(m_view, SIGNAL(currentTitle(const QString &)), this, SLOT(updateWindowTitle(const QString &)));
236     connect(m_view, SIGNAL(printRequested(QWebFrame *)), this, SLOT(printRequested(QWebFrame *)));
237
238     // (shift +) ctrl + tab switching
239     connect(this, SIGNAL(ctrlTabPressed()), m_view, SLOT(nextTab()));
240     connect(this, SIGNAL(shiftCtrlTabPressed()), m_view, SLOT(previousTab()));
241
242     // update toolbar actions signals
243     connect(m_view, SIGNAL(tabsChanged()), this, SLOT(updateActions()));
244     connect(m_view, SIGNAL(currentChanged(int)), this, SLOT(updateActions()));
245
246     // launch it manually. Just the first time...
247     updateActions();
248
249     // Find Bar signal
250     connect(m_findBar, SIGNAL(searchString(const QString &)), this, SLOT(find(const QString &)));
251
252     // setting up toolbars to NOT have context menu enabled
253     setContextMenuPolicy(Qt::DefaultContextMenu);
254
255     // accept d'n'd
256     setAcceptDrops(true);
257 }
258
259
260 QSize MainWindow::sizeHint() const
261 {
262     QRect desktopRect = QApplication::desktop()->screenGeometry();
263     QSize size = desktopRect.size() * 0.8;
264     return size;
265 }
266
267
268 void MainWindow::setupActions()
269 {
270     // this let shortcuts work..
271     actionCollection()->addAssociatedWidget(this);
272
273     KAction *a;
274
275     // new window action
276     a = new KAction(KIcon("window-new"), i18n("&New Window"), this);
277     a->setShortcut(KShortcut(Qt::CTRL | Qt::Key_N));
278     actionCollection()->addAction(QL1S("new_window"), a);
279     connect(a, SIGNAL(triggered(bool)), Application::instance(), SLOT(newWindow()));
280
281     // Standard Actions
282     KStandardAction::open(this, SLOT(fileOpen()), actionCollection());
283     KStandardAction::saveAs(this, SLOT(fileSaveAs()), actionCollection());
284     KStandardAction::print(this, SLOT(printRequested()), actionCollection());
285     KStandardAction::quit(this , SLOT(close()), actionCollection());
286
287     a = KStandardAction::find(m_findBar, SLOT(show()), actionCollection());
288     KShortcut findShortcut = KStandardShortcut::find();
289     findShortcut.setAlternate(Qt::Key_Slash);
290     a->setShortcut(findShortcut);
291
292     KStandardAction::findNext(this, SLOT(findNext()) , actionCollection());
293     KStandardAction::findPrev(this, SLOT(findPrevious()) , actionCollection());
294
295     a = KStandardAction::fullScreen(this, SLOT(viewFullScreen(bool)), this, actionCollection());
296     KShortcut fullScreenShortcut = KStandardShortcut::fullScreen();
297     fullScreenShortcut.setAlternate(Qt::Key_F11);
298     a->setShortcut(fullScreenShortcut);
299
300     a = actionCollection()->addAction(KStandardAction::Home);
301     connect(a, SIGNAL(triggered(Qt::MouseButtons, Qt::KeyboardModifiers)), this, SLOT(homePage(Qt::MouseButtons, Qt::KeyboardModifiers)));
302     KStandardAction::preferences(this, SLOT(preferences()), actionCollection());
303
304     a = KStandardAction::redisplay(m_view, SLOT(webReload()), actionCollection());
305     a->setText(i18n("Reload"));
306     KShortcut reloadShortcut = KStandardShortcut::reload();
307     reloadShortcut.setAlternate(Qt::CTRL + Qt::Key_R);
308     a->setShortcut(reloadShortcut);
309
310     a = new KAction(KIcon("process-stop"), i18n("&Stop"), this);
311     a->setShortcut(KShortcut(Qt::CTRL | Qt::Key_Period));
312     actionCollection()->addAction(QL1S("stop"), a);
313     connect(a, SIGNAL(triggered(bool)), m_view, SLOT(webStop()));
314
315     // stop reload Action
316     m_stopReloadAction = new KAction(this);
317     actionCollection()->addAction(QL1S("stop_reload") , m_stopReloadAction);
318     m_stopReloadAction->setShortcutConfigurable(false);
319     connect(m_view, SIGNAL(browserTabLoading(bool)), this, SLOT(browserLoading(bool)));
320     browserLoading(false); //first init for blank start page
321
322     a = new KAction(i18n("Open Location"), this);
323     a->setShortcut(Qt::CTRL + Qt::Key_L);
324     actionCollection()->addAction(QL1S("open_location"), a);
325     connect(a, SIGNAL(triggered(bool)) , this, SLOT(openLocation()));
326
327
328     // ============================= Zoom Actions ===================================
329     a = new KAction(KIcon("zoom-in"), i18n("&Zoom In"), this);
330     a->setShortcut(KShortcut(Qt::CTRL | Qt::Key_Plus));
331     actionCollection()->addAction(QL1S("zoom_in"), a);
332     connect(a, SIGNAL(triggered(bool)), this, SLOT(zoomIn()));
333
334     a = new KAction(KIcon("zoom-original"),  i18n("&Normal Zoom"), this);
335     a->setShortcut(KShortcut(Qt::CTRL | Qt::Key_0));
336     actionCollection()->addAction(QL1S("zoom_normal"), a);
337     connect(a, SIGNAL(triggered(bool)), this, SLOT(zoomNormal()));
338
339     a = new KAction(KIcon("zoom-out"),  i18n("&Zoom Out"), this);
340     a->setShortcut(KShortcut(Qt::CTRL | Qt::Key_Minus));
341     actionCollection()->addAction(QL1S("zoom_out"), a);
342     connect(a, SIGNAL(triggered(bool)), this, SLOT(zoomOut()));
343
344     // =============================== Tools Actions =================================
345     a = new KAction(i18n("Page S&ource"), this);
346     a->setIcon(KIcon("application-xhtml+xml"));
347     actionCollection()->addAction(QL1S("page_source"), a);
348     connect(a, SIGNAL(triggered(bool)), this, SLOT(viewPageSource()));
349
350     a = new KAction(KIcon("view-media-artist"), i18n("Private &Browsing"), this);
351     a->setCheckable(true);
352     actionCollection()->addAction(QL1S("private_browsing"), a);
353     connect(a, SIGNAL(triggered(bool)), this, SLOT(privateBrowsing(bool)));
354
355     a = new KAction(KIcon("edit-clear"), i18n("Clear Private Data..."), this);
356     actionCollection()->addAction(QL1S("clear_private_data"), a);
357     connect(a, SIGNAL(triggered(bool)), this, SLOT(clearPrivateData()));
358
359     // ========================= History related actions ==============================
360     a = actionCollection()->addAction(KStandardAction::Back);
361     connect(a, SIGNAL(triggered(Qt::MouseButtons, Qt::KeyboardModifiers)), this, SLOT(openPrevious(Qt::MouseButtons, Qt::KeyboardModifiers)));
362
363     m_historyBackMenu = new KMenu(this);
364     a->setMenu(m_historyBackMenu);
365     connect(m_historyBackMenu, SIGNAL(aboutToShow()), this, SLOT(aboutToShowBackMenu()));
366     connect(m_historyBackMenu, SIGNAL(triggered(QAction *)), this, SLOT(openActionUrl(QAction *)));
367
368     a = actionCollection()->addAction(KStandardAction::Forward);
369     connect(a, SIGNAL(triggered(Qt::MouseButtons, Qt::KeyboardModifiers)), this, SLOT(openNext(Qt::MouseButtons, Qt::KeyboardModifiers)));
370
371     // ============================== General Tab Actions ====================================
372     a = new KAction(KIcon("tab-new"), i18n("New &Tab"), this);
373     a->setShortcut(KShortcut(Qt::CTRL + Qt::Key_T));
374     actionCollection()->addAction(QL1S("new_tab"), a);
375     connect(a, SIGNAL(triggered(bool)), m_view, SLOT(newTab()));
376
377     a = new KAction(KIcon("view-refresh"), i18n("Reload All Tabs"), this);
378     actionCollection()->addAction(QL1S("reload_all_tabs"), a);
379     connect(a, SIGNAL(triggered(bool)), m_view, SLOT(reloadAllTabs()));
380
381     a = new KAction(i18n("Show Next Tab"), this);
382     a->setShortcuts(QApplication::isRightToLeft() ? KStandardShortcut::tabPrev() : KStandardShortcut::tabNext());
383     actionCollection()->addAction(QL1S("show_next_tab"), a);
384     connect(a, SIGNAL(triggered(bool)), m_view, SLOT(nextTab()));
385
386     a = new KAction(i18n("Show Previous Tab"), this);
387     a->setShortcuts(QApplication::isRightToLeft() ? KStandardShortcut::tabNext() : KStandardShortcut::tabPrev());
388     actionCollection()->addAction(QL1S("show_prev_tab"), a);
389     connect(a, SIGNAL(triggered(bool)), m_view, SLOT(previousTab()));
390     
391     a = new KAction(KIcon("tab-new"), i18n("Open Closed Tabs"), this);
392     a->setShortcut(KShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_T));
393     actionCollection()->addAction(QL1S("open_closed_tabs"), a);
394     connect(a, SIGNAL(triggered(bool)), m_view, SLOT(openClosedTabs()));
395
396     // Closed Tabs Menu
397     KActionMenu *closedTabsMenu = new KActionMenu(KIcon("tab-new"), i18n("Closed Tabs"), this);
398     closedTabsMenu->setDelayed(false);
399     actionCollection()->addAction(QL1S("closed_tab_menu"), closedTabsMenu);
400
401     // shortcuts for quickly switching to a tab
402     for( int i = 1; i <= 9; i++ ) {
403         a = new KAction(i18n("Switch to Tab %1", i), this);
404         a->setShortcut(KShortcut( QString("Alt+%1").arg(i) ));
405         a->setData( QVariant(i) );
406         actionCollection()->addAction(QL1S(("switch_tab_" + QString::number(i)).toAscii()), a);
407         connect(a, SIGNAL(triggered(bool)), m_view, SLOT(switchToTab()));
408     }
409
410
411     // ============================== Indexed Tab Actions ====================================
412     a = new KAction(KIcon("tab-close"), i18n("&Close Tab"), this);
413     actionCollection()->addAction(QL1S("close_tab"), a);
414     connect(a, SIGNAL(triggered(bool)), m_view->tabBar(), SLOT(closeTab()));
415
416     a = new KAction(KIcon("tab-duplicate"), i18n("Clone Tab"), this);
417     actionCollection()->addAction(QL1S("clone_tab"), a);
418     connect(a, SIGNAL(triggered(bool)), m_view->tabBar(), SLOT(cloneTab()));
419
420     a = new KAction(KIcon("tab-close-other"), i18n("Close &Other Tabs"), this);
421     actionCollection()->addAction(QL1S("close_other_tabs"), a);
422     connect(a, SIGNAL(triggered(bool)), m_view->tabBar(), SLOT(closeOtherTabs()));
423
424     a = new KAction(KIcon("view-refresh"), i18n("Reload Tab"), this);
425     actionCollection()->addAction(QL1S("reload_tab"), a);
426     connect(a, SIGNAL(triggered(bool)), m_view->tabBar(), SLOT(reloadTab()));
427
428     a = new KAction(KIcon("tab-detach"), i18n("Detach Tab"), this);
429     actionCollection()->addAction(QL1S("detach_tab"), a);
430     connect(a, SIGNAL(triggered(bool)), m_view->tabBar(), SLOT(detachTab()));
431
432
433     // ----------------------- Bookmarks ToolBar Action --------------------------------------
434     QAction *qa;
435
436     qa = m_mainBar->toggleViewAction();
437     qa->setText(i18n("Main Toolbar"));
438     qa->setIcon(KIcon("bookmark-toolbar"));
439     actionCollection()->addAction(QL1S("main_bar"), qa);
440
441     qa = m_bmBar->toggleViewAction();
442     qa->setText(i18n("Bookmarks Toolbar"));
443     qa->setIcon(KIcon("bookmark-toolbar"));
444     actionCollection()->addAction(QL1S("bm_bar"), qa);
445
446     // Bookmark Menu
447     KActionMenu *bmMenu = Application::bookmarkProvider()->bookmarkActionMenu(this);
448     bmMenu->setIcon(KIcon("bookmarks"));
449     bmMenu->setDelayed(false);
450     actionCollection()->addAction(QL1S("bookmarksActionMenu"), bmMenu);
451
452
453     // ---------------- Encodings -----------------------------------
454     a = new KAction(KIcon("character-set"), i18n("Set Encoding"), this);
455     actionCollection()->addAction(QL1S("encodings"), a);
456     a->setMenu(m_encodingMenu);
457     connect(m_encodingMenu, SIGNAL(aboutToShow()), this, SLOT(populateEncodingMenu()));
458     connect(m_encodingMenu, SIGNAL(triggered(QAction *)), this, SLOT(setEncoding(QAction *)));
459 }
460
461
462 void MainWindow::setupTools()
463 {
464     KActionMenu *toolsMenu = new KActionMenu(KIcon("configure"), i18n("&Tools"), this);
465     toolsMenu->setDelayed(false);
466
467     toolsMenu->addAction(actionByName(KStandardAction::name(KStandardAction::Open)));
468     toolsMenu->addAction(actionByName(KStandardAction::name(KStandardAction::SaveAs)));
469     toolsMenu->addAction(actionByName(KStandardAction::name(KStandardAction::Print)));
470     toolsMenu->addAction(actionByName(KStandardAction::name(KStandardAction::Find)));
471
472     // setup zoom widget
473     QWidget *zoomWidget = new QWidget(this);
474
475     QToolButton *zoomOut = new QToolButton(zoomWidget);
476     zoomOut->setDefaultAction(actionByName(QL1S("zoom_out")));
477     zoomOut->setAutoRaise(true);
478
479     m_zoomSlider = new QSlider(Qt::Horizontal, zoomWidget);
480     m_zoomSlider->setTracking(true);
481     m_zoomSlider->setRange(1, 19);      // divide by 10 to obtain a qreal for zoomFactor()
482     m_zoomSlider->setValue(10);
483     m_zoomSlider->setPageStep(3);
484     connect(m_zoomSlider, SIGNAL(valueChanged(int)), this, SLOT(setZoomFactor(int)));
485
486     QToolButton *zoomIn = new QToolButton(zoomWidget);
487     zoomIn->setDefaultAction(actionByName(QL1S("zoom_in")));
488     zoomIn->setAutoRaise(true);
489
490     QToolButton *zoomNormal = new QToolButton(zoomWidget);
491     zoomNormal->setDefaultAction(actionByName(QL1S("zoom_normal")));
492     zoomNormal->setAutoRaise(true);
493
494     QHBoxLayout* zoomWidgetLayout = new QHBoxLayout(zoomWidget);
495     zoomWidgetLayout->setSpacing(0);
496     zoomWidgetLayout->setMargin(0);
497     zoomWidgetLayout->addWidget(zoomOut);
498     zoomWidgetLayout->addWidget(m_zoomSlider);
499     zoomWidgetLayout->addWidget(zoomIn);
500     zoomWidgetLayout->addWidget(zoomNormal);
501
502     QWidgetAction *zoomAction = new QWidgetAction(this);
503     zoomAction->setDefaultWidget(zoomWidget);
504     toolsMenu->addAction(zoomAction);
505
506     toolsMenu->addAction(actionByName(QL1S("encodings")));
507
508     toolsMenu->addSeparator();
509
510     toolsMenu->addAction(actionByName(QL1S("private_browsing")));
511     toolsMenu->addAction(actionByName(QL1S("clear_private_data")));
512
513     toolsMenu->addSeparator();
514
515     KActionMenu *webMenu = new KActionMenu(KIcon("applications-development-web"), i18n("Development"), this);
516     webMenu->addAction(actionByName(QL1S("web_inspector")));
517     webMenu->addAction(actionByName(QL1S("page_source")));
518     webMenu->addAction(actionByName(QL1S("net_analyzer")));
519     toolsMenu->addAction(webMenu);
520
521     toolsMenu->addSeparator();
522
523     toolsMenu->addAction(actionByName(QL1S("bm_bar")));
524     toolsMenu->addAction(actionByName(QL1S("show_history_panel")));
525     toolsMenu->addAction(actionByName(QL1S("show_bookmarks_panel")));
526     toolsMenu->addAction(actionByName(KStandardAction::name(KStandardAction::FullScreen)));
527
528     toolsMenu->addSeparator();
529
530     helpMenu()->setIcon(KIcon("help-browser"));
531     toolsMenu->addAction(helpMenu()->menuAction());
532     toolsMenu->addAction(actionByName(KStandardAction::name(KStandardAction::Preferences)));
533
534     // adding rekonq_tools to rekonq actionCollection
535     actionCollection()->addAction(QL1S("rekonq_tools"), toolsMenu);
536 }
537
538
539 void MainWindow::setupPanels()
540 {
541     KAction* a;
542
543     // STEP 1
544     // Setup history panel
545     m_historyPanel = new HistoryPanel(i18n("History Panel"), this);
546     connect(m_historyPanel, SIGNAL(openUrl(const KUrl&, const Rekonq::OpenType &)), Application::instance(), SLOT(loadUrl(const KUrl&, const Rekonq::OpenType &)));
547     connect(m_historyPanel, SIGNAL(itemHovered(QString)), this, SLOT(notifyMessage(QString)));
548     connect(m_historyPanel, SIGNAL(destroyed()), Application::instance(), SLOT(saveConfiguration()));
549
550     addDockWidget(Qt::LeftDockWidgetArea, m_historyPanel);
551
552     // setup history panel action
553     a = (KAction *) m_historyPanel->toggleViewAction();
554     a->setShortcut(KShortcut(Qt::CTRL + Qt::Key_H));
555     a->setIcon(KIcon("view-history"));
556     actionCollection()->addAction(QL1S("show_history_panel"), a);
557
558     // STEP 2
559     // Setup bookmarks panel
560     m_bookmarksPanel = new BookmarksPanel(i18n("Bookmarks Panel"), this);
561     connect(m_bookmarksPanel, SIGNAL(openUrl(const KUrl&, const Rekonq::OpenType &)), Application::instance(), SLOT(loadUrl(const KUrl&, const Rekonq::OpenType &)));
562     connect(m_bookmarksPanel, SIGNAL(itemHovered(QString)), this, SLOT(notifyMessage(QString)));
563     connect(m_bookmarksPanel, SIGNAL(destroyed()), Application::instance(), SLOT(saveConfiguration()));
564
565     addDockWidget(Qt::LeftDockWidgetArea, m_bookmarksPanel);
566
567     // setup bookmarks panel action
568     a = (KAction *) m_bookmarksPanel->toggleViewAction();
569     a->setShortcut(KShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_B));
570     a->setIcon(KIcon("bookmarks-organize"));
571     actionCollection()->addAction(QL1S("show_bookmarks_panel"), a);
572
573     // STEP 3
574     // Setup webinspector panel
575     m_webInspectorPanel = new WebInspectorPanel(i18n("Web Inspector"), this);
576     connect(mainView(), SIGNAL(currentChanged(int)), m_webInspectorPanel, SLOT(changeCurrentPage()));
577
578     a = new KAction(KIcon("tools-report-bug"), i18n("Web &Inspector"), this);
579     a->setCheckable(true);
580     actionCollection()->addAction(QL1S("web_inspector"), a);
581     connect(a, SIGNAL(triggered(bool)), m_webInspectorPanel, SLOT(toggle(bool)));
582
583     addDockWidget(Qt::BottomDockWidgetArea, m_webInspectorPanel);
584     m_webInspectorPanel->hide();
585     
586     // STEP 4
587     // Setup Network analyzer panel
588     m_analyzerPanel = new NetworkAnalyzerPanel( i18n("Network Analyzer"), this);
589     connect(mainView(), SIGNAL(currentChanged(int)), m_analyzerPanel, SLOT(changeCurrentPage()));
590
591     a = new KAction(KIcon("document-edit-decrypt-verify"), i18n("Network Analyzer"), this);
592     a->setCheckable(true);
593     actionCollection()->addAction(QL1S("net_analyzer"), a);
594     connect(a, SIGNAL(triggered(bool)), this, SLOT(enableNetworkAnalysis(bool)));
595
596     addDockWidget(Qt::BottomDockWidgetArea, m_analyzerPanel);
597     m_analyzerPanel->hide();
598 }
599
600
601 void MainWindow::openLocation()
602 {
603     m_view->urlBar()->selectAll();
604     m_view->urlBar()->setFocus();
605 }
606
607
608 void MainWindow::fileSaveAs()
609 {
610     KUrl srcUrl = currentTab()->url();
611
612     QString name = srcUrl.fileName();
613     if (name.isNull())
614     {
615         name = srcUrl.host() + QString(".html");
616     }
617     const QString destUrl = KFileDialog::getSaveFileName(name, QString(), this);
618     if (destUrl.isEmpty()) return;
619     KIO::Job *job = KIO::file_copy(srcUrl, KUrl(destUrl), -1, KIO::Overwrite);
620     job->addMetaData("MaxCacheSize", "0");  // Don't store in http cache.
621     job->addMetaData("cache", "cache");     // Use entry from cache if available.
622     job->uiDelegate()->setAutoErrorHandlingEnabled(true);
623 }
624
625
626 void MainWindow::preferences()
627 {
628     // an instance the dialog could be already created and could be cached,
629     // in which case you want to display the cached dialog
630     if (SettingsDialog::showDialog("rekonfig"))
631         return;
632
633     // we didn't find an instance of this dialog, so lets create it
634     QPointer<SettingsDialog> s = new SettingsDialog(this);
635
636     // keep us informed when the user changes settings
637     connect(s, SIGNAL(settingsChanged(const QString&)), Application::instance(), SLOT(updateConfiguration()));
638
639     s->exec();
640     delete s;
641 }
642
643
644 void MainWindow::updateActions()
645 {
646     bool rekonqPage = currentTab()->page()->isOnRekonqPage();
647     
648     QAction *historyBackAction = actionByName(KStandardAction::name(KStandardAction::Back));
649     if( rekonqPage )
650         historyBackAction->setEnabled(true);
651     else
652         historyBackAction->setEnabled(currentTab()->view()->history()->canGoBack());
653
654     QAction *historyForwardAction = actionByName(KStandardAction::name(KStandardAction::Forward));
655     historyForwardAction->setEnabled(currentTab()->view()->history()->canGoForward());
656
657     QAction *openClosedTabsAction = actionByName( QL1S("open_closed_tabs") );
658     openClosedTabsAction->setEnabled(mainView()->recentlyClosedTabs().size() > 0);
659
660     // update closed tabs menu
661     KActionMenu *am = dynamic_cast<KActionMenu *>(actionByName( QL1S("closed_tab_menu") ));
662     if (!am)
663         return;
664
665     am->setEnabled(mainView()->recentlyClosedTabs().size() > 0);
666
667     if (am->menu())
668         am->menu()->clear();
669
670     foreach (HistoryItem item, mainView()->recentlyClosedTabs())
671     {
672         KAction *a = new KAction(Application::icon(item.url), item.title, this);
673         a->setData(item.url);
674         connect(a, SIGNAL(triggered()), m_view, SLOT(openClosedTab()));
675         am->addAction(a);
676     }
677 }
678
679
680 void MainWindow::updateWindowTitle(const QString &title)
681 {
682     QWebSettings *settings = QWebSettings::globalSettings();
683     if (title.isEmpty())
684     {
685         if (settings->testAttribute(QWebSettings::PrivateBrowsingEnabled))
686         {
687             setWindowTitle(i18nc("Window title when private browsing is activated", "rekonq (Private Browsing)"));
688         }
689         else
690         {
691             setWindowTitle("rekonq");
692         }
693     }
694     else
695     {
696         if (settings->testAttribute(QWebSettings::PrivateBrowsingEnabled))
697         {
698             setWindowTitle(i18nc("window title, %1 = title of the active website", "%1 – rekonq (Private Browsing)", title));
699         }
700         else
701         {
702             setWindowTitle(i18nc("window title, %1 = title of the active website", "%1 – rekonq", title));
703         }
704     }
705 }
706
707
708 void MainWindow::fileOpen()
709 {
710     QString filePath = KFileDialog::getOpenFileName(KUrl(),
711                        i18n("*.html *.htm *.svg *.png *.gif *.svgz|Web Resources (*.html *.htm *.svg *.png *.gif *.svgz)\n"
712                             "*.*|All files (*.*)"),
713                        this,
714                        i18n("Open Web Resource"));
715
716     if (filePath.isEmpty())
717         return;
718
719     Application::instance()->loadUrl(filePath);
720 }
721
722
723 void MainWindow::printRequested(QWebFrame *frame)
724 {
725     if (!currentTab())
726         return;
727
728     QWebFrame *printFrame = 0;
729     if (frame == 0)
730     {
731         printFrame = currentTab()->page()->mainFrame();
732     }
733     else
734     {
735         printFrame = frame;
736     }
737
738     QPrinter printer;
739     QPrintPreviewDialog previewdlg(&printer, this);
740
741     connect(&previewdlg, SIGNAL(paintRequested(QPrinter *)), printFrame, SLOT(print(QPrinter *)));
742
743     previewdlg.exec();
744 }
745
746
747 void MainWindow::privateBrowsing(bool enable)
748 {
749     QWebSettings *settings = QWebSettings::globalSettings();
750     if (enable && !settings->testAttribute(QWebSettings::PrivateBrowsingEnabled))
751     {
752         QString title = i18n("Are you sure you want to turn on private browsing?");
753         QString text = i18n("<b>%1</b>"
754                             "<p>When private browsing is turned on,"
755                             " web pages are not added to the history,"
756                             " new cookies are not stored, current cookies cannot be accessed,"
757                             " site icons will not be stored, the session will not be saved."
758                             " Until you close the window, you can still click the Back and Forward buttons"
759                             " to return to the web pages you have opened.</p>", title);
760
761         int button = KMessageBox::warningContinueCancel(this, text, title);
762         if (button == KMessageBox::Continue)
763         {
764             settings->setAttribute(QWebSettings::PrivateBrowsingEnabled, true);
765             m_view->urlBar()->setPrivateMode(true);
766         }
767         else
768         {
769             actionCollection()->action( QL1S("private_browsing") )->setChecked(false);
770         }
771     }
772     else
773     {
774         settings->setAttribute(QWebSettings::PrivateBrowsingEnabled, false);
775         m_view->urlBar()->setPrivateMode(false);
776
777         m_lastSearch.clear();
778         m_view->reloadAllTabs();
779     }
780 }
781
782
783 void MainWindow::find(const QString & search)
784 {
785     if (!currentTab())
786         return;
787     m_lastSearch = search;
788
789     findNext();
790 }
791
792
793 void MainWindow::matchCaseUpdate()
794 {
795     if (!currentTab())
796         return;
797
798     currentTab()->view()->findText(m_lastSearch, QWebPage::FindBackward);
799     findNext();
800 }
801
802
803 void MainWindow::findNext()
804 {
805     if (!currentTab())
806         return;
807
808     highlightAll();
809
810     if (m_findBar->isHidden())
811     {
812         QPoint previous_position = currentTab()->view()->page()->currentFrame()->scrollPosition();
813         currentTab()->view()->page()->focusNextPrevChild(true);
814         currentTab()->view()->page()->currentFrame()->setScrollPosition(previous_position);
815         return;
816     }
817
818     highlightAll();
819
820     QWebPage::FindFlags options = QWebPage::FindWrapsAroundDocument;
821     if (m_findBar->matchCase())
822         options |= QWebPage::FindCaseSensitively;
823
824     bool found = currentTab()->view()->findText(m_lastSearch, options);
825     m_findBar->notifyMatch(found);
826
827     if (!found)
828     {
829         QPoint previous_position = currentTab()->view()->page()->currentFrame()->scrollPosition();
830         currentTab()->view()->page()->focusNextPrevChild(true);
831         currentTab()->view()->page()->currentFrame()->setScrollPosition(previous_position);
832     }
833 }
834
835
836 void MainWindow::findPrevious()
837 {
838     if (!currentTab())
839         return;
840
841     QWebPage::FindFlags options = QWebPage::FindBackward | QWebPage::FindWrapsAroundDocument;
842     if (m_findBar->matchCase())
843         options |= QWebPage::FindCaseSensitively;
844
845     bool found = currentTab()->view()->findText(m_lastSearch, options);
846     m_findBar->notifyMatch(found);
847 }
848
849 void MainWindow::highlightAll()
850 {
851     if (!currentTab())
852         return;
853
854     QWebPage::FindFlags options = QWebPage::HighlightAllOccurrences;
855
856     currentTab()->view()->findText("", options); //Clear an existing highlight
857
858     if (m_findBar->highlightAllState() && !m_findBar->isHidden())
859     {
860         if (m_findBar->matchCase())
861             options |= QWebPage::FindCaseSensitively;
862
863         currentTab()->view()->findText(m_lastSearch, options);
864     }
865 }
866
867
868 void MainWindow::zoomIn()
869 {
870     m_zoomSlider->setValue(m_zoomSlider->value() + 1);
871 }
872
873
874 void MainWindow::zoomNormal()
875 {
876     m_zoomSlider->setValue(10);
877 }
878
879
880 void MainWindow::zoomOut()
881 {
882     m_zoomSlider->setValue(m_zoomSlider->value() - 1);
883 }
884
885
886 void MainWindow::setZoomFactor(int factor)
887 {
888     if (!currentTab())
889         return;
890     currentTab()->view()->setZoomFactor(QVariant(factor).toReal() / 10);
891 }
892
893
894 void MainWindow::setZoomSliderFactor(qreal factor)
895 {
896     m_zoomSlider->setValue(factor*10);
897 }
898
899
900 void MainWindow::viewFullScreen(bool makeFullScreen)
901 {
902     setWidgetsVisible(!makeFullScreen);
903     KToggleFullScreenAction::setFullScreen(this, makeFullScreen);
904 }
905
906
907 void MainWindow::setWidgetsVisible(bool makeVisible)
908 {
909     // state flags
910     static bool bookmarksToolBarFlag;
911     static bool historyPanelFlag;
912     static bool bookmarksPanelFlag;
913
914     if (!makeVisible)
915     {
916         // save current state, if in windowed mode
917         if (!isFullScreen())
918         {
919             bookmarksToolBarFlag = m_bmBar->isHidden();
920             historyPanelFlag = m_historyPanel->isHidden();
921             bookmarksPanelFlag = m_bookmarksPanel->isHidden();
922         }
923
924         m_bmBar->hide();
925         m_view->setTabBarHidden(true);
926         m_historyPanel->hide();
927         m_bookmarksPanel->hide();
928
929         // hide main toolbar
930         m_mainBar->hide();
931     }
932     else
933     {
934         // show main toolbar
935         m_mainBar->show();
936         m_view->setTabBarHidden(false);
937
938         // restore state of windowed mode
939         if (!bookmarksToolBarFlag)
940             m_bmBar->show();
941         if (!historyPanelFlag)
942             m_historyPanel->show();
943         if (!bookmarksPanelFlag)
944             m_bookmarksPanel->show();
945     }
946 }
947
948
949 void MainWindow::viewPageSource()
950 {
951     if (!currentTab())
952         return;
953
954     KUrl url(currentTab()->url());
955     bool isTempFile = false;
956     if (!url.isLocalFile())
957     {
958         KTemporaryFile sourceFile;
959
960         /// TODO: autochoose tempfile suffix
961         sourceFile.setSuffix(QString(".html"));
962         sourceFile.setAutoRemove(false);
963
964         if (sourceFile.open())
965         {
966             sourceFile.write(currentTab()->page()->mainFrame()->toHtml().toUtf8());
967
968             url = KUrl();
969             url.setPath(sourceFile.fileName());
970             isTempFile = true;
971         }
972     }
973     KRun::runUrl(url, QL1S("text/plain"), this, isTempFile);
974 }
975
976
977 void MainWindow::homePage(Qt::MouseButtons mouseButtons, Qt::KeyboardModifiers keyboardModifiers)
978 {
979     KUrl homeUrl = ReKonfig::useNewTabPage() 
980         ? KUrl( QL1S("about:home") )
981         : KUrl( ReKonfig::homePage() );
982         
983     if (mouseButtons == Qt::MidButton || keyboardModifiers == Qt::ControlModifier)
984         Application::instance()->loadUrl( homeUrl, Rekonq::SettingOpenTab);
985     else
986         currentTab()->view()->load( homeUrl );
987 }
988
989
990 WebTab *MainWindow::currentTab() const
991 {
992     return m_view->currentWebTab();
993 }
994
995
996 void MainWindow::browserLoading(bool v)
997 {
998     QAction *stop = actionCollection()->action( QL1S("stop") );
999     QAction *reload = actionCollection()->action( QL1S("view_redisplay") );
1000     if (v)
1001     {
1002         disconnect(m_stopReloadAction, SIGNAL(triggered(bool)), reload , SIGNAL(triggered(bool)));
1003         m_stopReloadAction->setIcon(KIcon("process-stop"));
1004         m_stopReloadAction->setToolTip(i18n("Stop loading the current page"));
1005         m_stopReloadAction->setText(i18n("Stop"));
1006         connect(m_stopReloadAction, SIGNAL(triggered(bool)), stop, SIGNAL(triggered(bool)));
1007     }
1008     else
1009     {
1010         disconnect(m_stopReloadAction, SIGNAL(triggered(bool)), stop , SIGNAL(triggered(bool)));
1011         m_stopReloadAction->setIcon(KIcon("view-refresh"));
1012         m_stopReloadAction->setToolTip(i18n("Reload the current page"));
1013         m_stopReloadAction->setText(i18n("Reload"));
1014         connect(m_stopReloadAction, SIGNAL(triggered(bool)), reload, SIGNAL(triggered(bool)));
1015
1016     }
1017 }
1018
1019
1020 void MainWindow::openPrevious(Qt::MouseButtons mouseButtons, Qt::KeyboardModifiers keyboardModifiers)
1021 {
1022     QWebHistory *history = currentTab()->view()->history();
1023     QWebHistoryItem *item = 0;
1024     
1025     if (currentTab()->page()->isOnRekonqPage())
1026     {
1027         item = new QWebHistoryItem(history->currentItem());
1028         currentTab()->view()->page()->setIsOnRekonqPage(false);
1029     }
1030     else
1031     {
1032         if (history->canGoBack())
1033         {
1034             item = new QWebHistoryItem(history->backItem());
1035         }
1036     }
1037
1038     if(!item)
1039         return;
1040     
1041     if (mouseButtons == Qt::MidButton || keyboardModifiers == Qt::ControlModifier)
1042     {
1043         Application::instance()->loadUrl(item->url(), Rekonq::SettingOpenTab);
1044     }
1045     else
1046     {
1047         history->goToItem(*item);
1048     }
1049
1050     updateActions();
1051 }
1052
1053
1054 void MainWindow::openNext(Qt::MouseButtons mouseButtons, Qt::KeyboardModifiers keyboardModifiers)
1055 {
1056     QWebHistory *history = currentTab()->view()->history();
1057     QWebHistoryItem *item = 0;
1058
1059     if (currentTab()->view()->page()->isOnRekonqPage())
1060     {
1061         item = new QWebHistoryItem(history->currentItem());
1062         currentTab()->view()->page()->setIsOnRekonqPage(false);
1063     }
1064     else
1065     {
1066         if (history->canGoForward())
1067         {
1068             item = new QWebHistoryItem(history->forwardItem());
1069         }
1070     }
1071     
1072     if(!item)
1073         return;
1074     
1075     if (mouseButtons == Qt::MidButton || keyboardModifiers == Qt::ControlModifier)
1076     {
1077         Application::instance()->loadUrl(item->url(), Rekonq::SettingOpenTab);
1078     }
1079     else
1080     {
1081         history->goToItem(*item);
1082     }
1083     
1084     updateActions();
1085 }
1086
1087
1088 void MainWindow::keyPressEvent(QKeyEvent *event)
1089 {
1090     // hide findbar
1091     if (event->key() == Qt::Key_Escape)
1092     {
1093         m_findBar->hide();
1094         currentTab()->setFocus();   // give focus to web pages
1095         return;
1096     }
1097
1098     // ctrl + tab action
1099     if ((event->modifiers() == Qt::ControlModifier) && (event->key() == Qt::Key_Tab))
1100     {
1101         emit ctrlTabPressed();
1102         return;
1103     }
1104
1105     // shift + ctrl + tab action
1106     if ((event->modifiers() == Qt::ControlModifier + Qt::ShiftModifier) && (event->key() == Qt::Key_Backtab))
1107     {
1108         emit shiftCtrlTabPressed();
1109         return;
1110     }
1111
1112     // close current tab action
1113     if ((event->modifiers() == Qt::ControlModifier) && event->key() == Qt::Key_W)
1114     {
1115         m_view->closeTab(m_view->currentIndex());
1116         return;
1117     }
1118
1119     KMainWindow::keyPressEvent(event);
1120 }
1121
1122
1123 void MainWindow::notifyMessage(const QString &msg, Rekonq::Notify status)
1124 {
1125     if (this != QApplication::activeWindow())
1126     {
1127         return;
1128     }
1129
1130     // deleting popus if empty msgs
1131     if (msg.isEmpty())
1132     {
1133         m_hidePopup->start(250);
1134         return;
1135     }
1136
1137     m_hidePopup->stop();
1138
1139
1140     switch (status)
1141     {
1142     case Rekonq::Info:
1143         break;
1144     case Rekonq::Success:
1145         break;
1146     case Rekonq::Error:
1147         break;
1148     case Rekonq::Download:
1149         break;
1150     default:
1151         break;
1152     }
1153
1154     int margin = 4;
1155
1156     // setting the popup
1157     QLabel *label = new QLabel(msg);
1158     m_popup->setView(label);
1159     QSize labelSize(label->fontMetrics().width(msg) + 2*margin, label->fontMetrics().height() + 2*margin);
1160     if (labelSize.width() > width()) labelSize.setWidth(width());
1161     m_popup->setFixedSize(labelSize);
1162     m_popup->layout()->setAlignment(Qt::AlignTop);
1163     m_popup->layout()->setMargin(margin);
1164
1165     // useful values
1166     WebTab *tab = m_view->currentWebTab();
1167
1168     // fix crash on window close
1169     if (!tab)
1170         return;
1171
1172     // fix crash on window close
1173     if (!tab->page())
1174         return;
1175
1176     bool scrollbarIsVisible = tab->page()->currentFrame()->scrollBarMaximum(Qt::Horizontal);
1177     int scrollbarSize = 0;
1178     if (scrollbarIsVisible)
1179     {
1180         //TODO: detect QStyle size
1181         scrollbarSize = 17;
1182     }
1183
1184     QPoint webViewOrigin = tab->view()->mapToGlobal(QPoint(0, 0));
1185     int bottomLeftY = webViewOrigin.y() + tab->page()->viewportSize().height() - labelSize.height() - scrollbarSize;
1186
1187     // setting popup in bottom-left position
1188     int x = geometry().x();
1189     int y = bottomLeftY;
1190
1191     QPoint mousePos = tab->mapToGlobal(tab->view()->mousePos());
1192     if (QRect(webViewOrigin.x() , bottomLeftY , labelSize.width() , labelSize.height()).contains(mousePos))
1193     {
1194         // setting popup above the mouse
1195         y = bottomLeftY - labelSize.height();
1196     }
1197
1198     m_popup->show(QPoint(x, y));
1199 }
1200
1201
1202 void MainWindow::clearPrivateData()
1203 {
1204     QPointer<KDialog> dialog = new KDialog(this);
1205     dialog->setCaption(i18n("Clear Private Data"));
1206     dialog->setButtons(KDialog::Ok | KDialog::Cancel);
1207
1208     dialog->button(KDialog::Ok)->setIcon(KIcon("edit-clear"));
1209     dialog->button(KDialog::Ok)->setText(i18n("Clear"));
1210
1211     Ui::ClearDataWidget clearWidget;
1212     QWidget widget;
1213     clearWidget.setupUi(&widget);
1214
1215     dialog->setMainWidget(&widget);
1216     dialog->exec();
1217
1218     if (dialog->result() == QDialog::Accepted)
1219     {
1220         if (clearWidget.clearHistory->isChecked())
1221         {
1222             Application::historyManager()->clear();
1223         }
1224
1225         if (clearWidget.clearDownloads->isChecked())
1226         {
1227             Application::historyManager()->clearDownloadsHistory();
1228         }
1229
1230         if (clearWidget.clearCookies->isChecked())
1231         {
1232             QDBusInterface kcookiejar("org.kde.kded", "/modules/kcookiejar", "org.kde.KCookieServer");
1233             QDBusReply<void> reply = kcookiejar.call("deleteAllCookies");
1234         }
1235
1236         if (clearWidget.clearCachedPages->isChecked())
1237         {
1238             KProcess::startDetached(KStandardDirs::findExe("kio_http_cache_cleaner"),
1239                                     QStringList(QL1S("--clear-all")));
1240         }
1241
1242         if (clearWidget.clearWebIcons->isChecked())
1243         {
1244             QWebSettings::clearIconDatabase();
1245         }
1246
1247         if (clearWidget.homePageThumbs->isChecked())
1248         {
1249             QString path = KStandardDirs::locateLocal("cache", QString("thumbs/rekonq"), true);
1250             path.remove("rekonq");
1251             QDir cacheDir(path);
1252             QStringList fileList = cacheDir.entryList();
1253             foreach(const QString &str, fileList)
1254             {
1255                 QFile file(path + str);
1256                 file.remove();
1257             }
1258         }
1259     }
1260
1261     dialog->deleteLater();
1262 }
1263
1264
1265 void MainWindow::aboutToShowBackMenu()
1266 {
1267     m_historyBackMenu->clear();
1268     if (!currentTab())
1269         return;
1270     QWebHistory *history = currentTab()->view()->history();
1271     int pivot = history->currentItemIndex();
1272     int offset = 0;
1273     QList<QWebHistoryItem> historyList = history->backItems(8); //no more than 8 elements!
1274     int listCount = historyList.count();
1275     if (pivot >= 8)
1276         offset = pivot - 8;
1277
1278     /*
1279      * Need a bug report upstream. 
1280      * Seems setHtml() do some garbage in history
1281      * Here history->currentItem() have backItem url and currentItem (error page) title
1282      */
1283     if (currentTab()->view()->page()->isOnRekonqPage())
1284     {
1285         QWebHistoryItem item = history->currentItem();
1286         KAction *action = new KAction(this);
1287         action->setData(listCount + offset++);
1288         KIcon icon = Application::icon(item.url());
1289         action->setIcon(icon);
1290         action->setText(item.title());
1291         m_historyBackMenu->addAction(action);
1292     }
1293          
1294     for (int i = listCount - 1; i >= 0; --i)
1295     {
1296         QWebHistoryItem item = historyList.at(i);
1297         KAction *action = new KAction(this);
1298         action->setData(i + offset);
1299         KIcon icon = Application::icon(item.url());
1300         action->setIcon(icon);
1301         action->setText(item.title());
1302         m_historyBackMenu->addAction(action);
1303     }
1304 }
1305
1306
1307 void MainWindow::openActionUrl(QAction *action)
1308 {
1309     int index = action->data().toInt();
1310
1311     QWebHistory *history = currentTab()->view()->history();
1312     if (!history->itemAt(index).isValid())
1313     {
1314         kDebug() << "Invalid Index!: " << index;
1315         return;
1316     }
1317
1318     history->goToItem(history->itemAt(index));
1319 }
1320
1321
1322 void MainWindow::setEncoding(QAction *qa)
1323 {
1324     QString currentCodec = qa->text().toLatin1();
1325     currentCodec = currentCodec.remove('&');
1326     kDebug() << "Setting codec: " << currentCodec;
1327     currentTab()->page()->settings()->setDefaultTextEncoding(currentCodec);
1328 }
1329
1330
1331 void MainWindow::populateEncodingMenu()
1332 {
1333     QStringList codecs;
1334     QList<int> mibs = QTextCodec::availableMibs();
1335     Q_FOREACH (const int &mib, mibs) 
1336     {
1337         QString codec = QLatin1String(QTextCodec::codecForMib(mib)->name());
1338         codecs.append(codec);
1339     }
1340     codecs.sort();
1341
1342     QString currentCodec = currentTab()->page()->settings()->defaultTextEncoding();
1343
1344     m_encodingMenu->clear();
1345     KMenu *isoMenu = new KMenu( QL1S("ISO"), m_encodingMenu);
1346     KMenu *winMenu = new KMenu( QL1S("windows"), m_encodingMenu);
1347     KMenu *isciiMenu = new KMenu( QL1S("Iscii"), m_encodingMenu);
1348     KMenu *uniMenu = new KMenu( QL1S("UNICODE"), m_encodingMenu);
1349     KMenu *otherMenu = new KMenu( QL1S("Other"), m_encodingMenu);
1350     
1351     QAction *a;
1352     Q_FOREACH(const QString &codec, codecs)
1353     {
1354         
1355         if( codec.startsWith( QL1S("ISO"), Qt::CaseInsensitive ) )
1356             a = isoMenu->addAction(codec);
1357         else if( codec.startsWith( QL1S("win") ) )
1358             a = winMenu->addAction(codec);
1359         else if( codec.startsWith( QL1S("Iscii") ) )
1360             a = isciiMenu->addAction(codec);
1361         else if( codec.startsWith( QL1S("UT") ) )
1362             a = uniMenu->addAction(codec);
1363         else 
1364             a = otherMenu->addAction(codec);
1365             
1366         a->setCheckable(true);
1367         if (currentCodec == codec)
1368             a->setChecked(true);
1369     }
1370     m_encodingMenu->addMenu( isoMenu );
1371     m_encodingMenu->addMenu( winMenu );
1372     m_encodingMenu->addMenu( isciiMenu );
1373     m_encodingMenu->addMenu( uniMenu );
1374     m_encodingMenu->addMenu( otherMenu );
1375 }
1376
1377
1378 void MainWindow::enableNetworkAnalysis(bool b)
1379 {
1380     currentTab()->page()->enableNetworkAnalyzer(b);
1381     m_analyzerPanel->toggle(b);
1382 }
1383
1384
1385 bool MainWindow::queryClose()
1386 {
1387     if (m_view->count() > 1)                                                                                                              
1388     {
1389         int answer = KMessageBox::questionYesNoCancel(                                                                                    
1390                         this,                                                                                                            
1391                         i18np("Are you sure you want to close the window?\n" "You have 1 tab open",
1392                          "Are you sure you want to close the window?\n" "You have %1 tabs open" , 
1393                         m_view->count()),
1394                         i18n("Are you sure you want to close the window?"),                                                              
1395                         KStandardGuiItem::quit(),                                                                                        
1396                         KGuiItem(i18n("C&lose Current Tab"), KIcon("tab-close")),                                                        
1397                         KStandardGuiItem::cancel(),                                                                                      
1398                         "confirmClosingMultipleTabs"                                                                                     
1399                                                         );                                                                                                                   
1400                                                                                                                     
1401         switch (answer)                                                                                                                   
1402         {                                                                                                                                 
1403             case KMessageBox::Yes:  
1404                 // Quit                                                                                                                         
1405                 return true;                                                                                                                  
1406             
1407             case KMessageBox::No:                                                                                                             
1408                 // Close only the current tab                                                                                                 
1409                 m_view->closeTab();
1410             
1411             default:                                                                                                                          
1412                 return false;                                                                                                                 
1413         }                                                                                                                                 
1414     }                                                                                                                                     
1415     return true;                                                                                                                          
1416 }