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