last minute string fixes
[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     // ============================== Indexed Tab Actions ====================================
402     a = new KAction(KIcon("tab-close"), i18n("&Close Tab"), this);
403     actionCollection()->addAction(QL1S("close_tab"), a);
404     connect(a, SIGNAL(triggered(bool)), m_view->tabBar(), SLOT(closeTab()));
405
406     a = new KAction(KIcon("tab-duplicate"), i18n("Clone Tab"), this);
407     actionCollection()->addAction(QL1S("clone_tab"), a);
408     connect(a, SIGNAL(triggered(bool)), m_view->tabBar(), SLOT(cloneTab()));
409
410     a = new KAction(KIcon("tab-close-other"), i18n("Close &Other Tabs"), this);
411     actionCollection()->addAction(QL1S("close_other_tabs"), a);
412     connect(a, SIGNAL(triggered(bool)), m_view->tabBar(), SLOT(closeOtherTabs()));
413
414     a = new KAction(KIcon("view-refresh"), i18n("Reload Tab"), this);
415     actionCollection()->addAction(QL1S("reload_tab"), a);
416     connect(a, SIGNAL(triggered(bool)), m_view->tabBar(), SLOT(reloadTab()));
417
418     a = new KAction(KIcon("tab-detach"), i18n("Detach Tab"), this);
419     actionCollection()->addAction(QL1S("detach_tab"), a);
420     connect(a, SIGNAL(triggered(bool)), m_view->tabBar(), SLOT(detachTab()));
421
422
423     // ----------------------- Bookmarks ToolBar Action --------------------------------------
424     QAction *qa;
425
426     qa = m_mainBar->toggleViewAction();
427     qa->setText(i18n("Main Toolbar"));
428     qa->setIcon(KIcon("bookmark-toolbar"));
429     actionCollection()->addAction(QL1S("main_bar"), qa);
430
431     qa = m_bmBar->toggleViewAction();
432     qa->setText(i18n("Bookmarks Toolbar"));
433     qa->setIcon(KIcon("bookmark-toolbar"));
434     actionCollection()->addAction(QL1S("bm_bar"), qa);
435
436     // Bookmark Menu
437     KActionMenu *bmMenu = Application::bookmarkProvider()->bookmarkActionMenu(this);
438     bmMenu->setIcon(KIcon("bookmarks"));
439     bmMenu->setDelayed(false);
440     actionCollection()->addAction(QL1S("bookmarksActionMenu"), bmMenu);
441
442
443     // ---------------- Encodings -----------------------------------
444     a = new KAction(KIcon("character-set"), i18n("Set Encoding"), this);
445     actionCollection()->addAction(QL1S("encodings"), a);
446     a->setMenu(m_encodingMenu);
447     connect(m_encodingMenu, SIGNAL(aboutToShow()), this, SLOT(populateEncodingMenu()));
448     connect(m_encodingMenu, SIGNAL(triggered(QAction *)), this, SLOT(setEncoding(QAction *)));
449 }
450
451
452 void MainWindow::setupTools()
453 {
454     KActionMenu *toolsMenu = new KActionMenu(KIcon("configure"), i18n("&Tools"), this);
455     toolsMenu->setDelayed(false);
456
457     toolsMenu->addAction(actionByName(KStandardAction::name(KStandardAction::Open)));
458     toolsMenu->addAction(actionByName(KStandardAction::name(KStandardAction::SaveAs)));
459     toolsMenu->addAction(actionByName(KStandardAction::name(KStandardAction::Print)));
460     toolsMenu->addAction(actionByName(KStandardAction::name(KStandardAction::Find)));
461
462     // setup zoom widget
463     QWidget *zoomWidget = new QWidget(this);
464
465     QToolButton *zoomOut = new QToolButton(zoomWidget);
466     zoomOut->setDefaultAction(actionByName(QL1S("zoom_out")));
467     zoomOut->setAutoRaise(true);
468
469     m_zoomSlider = new QSlider(Qt::Horizontal, zoomWidget);
470     m_zoomSlider->setTracking(true);
471     m_zoomSlider->setRange(1, 19);      // divide by 10 to obtain a qreal for zoomFactor()
472     m_zoomSlider->setValue(10);
473     m_zoomSlider->setPageStep(3);
474     connect(m_zoomSlider, SIGNAL(valueChanged(int)), this, SLOT(setZoomFactor(int)));
475
476     QToolButton *zoomIn = new QToolButton(zoomWidget);
477     zoomIn->setDefaultAction(actionByName(QL1S("zoom_in")));
478     zoomIn->setAutoRaise(true);
479
480     QToolButton *zoomNormal = new QToolButton(zoomWidget);
481     zoomNormal->setDefaultAction(actionByName(QL1S("zoom_normal")));
482     zoomNormal->setAutoRaise(true);
483
484     QHBoxLayout* zoomWidgetLayout = new QHBoxLayout(zoomWidget);
485     zoomWidgetLayout->setSpacing(0);
486     zoomWidgetLayout->setMargin(0);
487     zoomWidgetLayout->addWidget(zoomOut);
488     zoomWidgetLayout->addWidget(m_zoomSlider);
489     zoomWidgetLayout->addWidget(zoomIn);
490     zoomWidgetLayout->addWidget(zoomNormal);
491
492     QWidgetAction *zoomAction = new QWidgetAction(this);
493     zoomAction->setDefaultWidget(zoomWidget);
494     toolsMenu->addAction(zoomAction);
495
496     toolsMenu->addAction(actionByName(QL1S("encodings")));
497
498     toolsMenu->addSeparator();
499
500     toolsMenu->addAction(actionByName(QL1S("private_browsing")));
501     toolsMenu->addAction(actionByName(QL1S("clear_private_data")));
502
503     toolsMenu->addSeparator();
504
505     KActionMenu *webMenu = new KActionMenu(KIcon("applications-development-web"), i18n("Development"), this);
506     webMenu->addAction(actionByName(QL1S("web_inspector")));
507     webMenu->addAction(actionByName(QL1S("page_source")));
508     webMenu->addAction(actionByName(QL1S("net_analyzer")));
509     toolsMenu->addAction(webMenu);
510
511     toolsMenu->addSeparator();
512
513     toolsMenu->addAction(actionByName(QL1S("bm_bar")));
514     toolsMenu->addAction(actionByName(QL1S("show_history_panel")));
515     toolsMenu->addAction(actionByName(QL1S("show_bookmarks_panel")));
516     toolsMenu->addAction(actionByName(KStandardAction::name(KStandardAction::FullScreen)));
517
518     toolsMenu->addSeparator();
519
520     helpMenu()->setIcon(KIcon("help-browser"));
521     toolsMenu->addAction(helpMenu()->menuAction());
522     toolsMenu->addAction(actionByName(KStandardAction::name(KStandardAction::Preferences)));
523
524     // adding rekonq_tools to rekonq actionCollection
525     actionCollection()->addAction(QL1S("rekonq_tools"), toolsMenu);
526 }
527
528
529 void MainWindow::setupPanels()
530 {
531     KAction* a;
532
533     // STEP 1
534     // Setup history panel
535     m_historyPanel = new HistoryPanel(i18n("History Panel"), this);
536     connect(m_historyPanel, SIGNAL(openUrl(const KUrl&, const Rekonq::OpenType &)), Application::instance(), SLOT(loadUrl(const KUrl&, const Rekonq::OpenType &)));
537     connect(m_historyPanel, SIGNAL(itemHovered(QString)), this, SLOT(notifyMessage(QString)));
538     connect(m_historyPanel, SIGNAL(destroyed()), Application::instance(), SLOT(saveConfiguration()));
539
540     addDockWidget(Qt::LeftDockWidgetArea, m_historyPanel);
541
542     // setup history panel action
543     a = (KAction *) m_historyPanel->toggleViewAction();
544     a->setShortcut(KShortcut(Qt::CTRL + Qt::Key_H));
545     a->setIcon(KIcon("view-history"));
546     actionCollection()->addAction(QL1S("show_history_panel"), a);
547
548     // STEP 2
549     // Setup bookmarks panel
550     m_bookmarksPanel = new BookmarksPanel(i18n("Bookmarks Panel"), this);
551     connect(m_bookmarksPanel, SIGNAL(openUrl(const KUrl&, const Rekonq::OpenType &)), Application::instance(), SLOT(loadUrl(const KUrl&, const Rekonq::OpenType &)));
552     connect(m_bookmarksPanel, SIGNAL(itemHovered(QString)), this, SLOT(notifyMessage(QString)));
553     connect(m_bookmarksPanel, SIGNAL(destroyed()), Application::instance(), SLOT(saveConfiguration()));
554
555     addDockWidget(Qt::LeftDockWidgetArea, m_bookmarksPanel);
556
557     // setup bookmarks panel action
558     a = (KAction *) m_bookmarksPanel->toggleViewAction();
559     a->setShortcut(KShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_B));
560     a->setIcon(KIcon("bookmarks-organize"));
561     actionCollection()->addAction(QL1S("show_bookmarks_panel"), a);
562
563     // STEP 3
564     // Setup webinspector panel
565     m_webInspectorPanel = new WebInspectorPanel(i18n("Web Inspector"), this);
566     connect(mainView(), SIGNAL(currentChanged(int)), m_webInspectorPanel, SLOT(changeCurrentPage()));
567
568     a = new KAction(KIcon("tools-report-bug"), i18n("Web &Inspector"), this);
569     a->setCheckable(true);
570     actionCollection()->addAction(QL1S("web_inspector"), a);
571     connect(a, SIGNAL(triggered(bool)), m_webInspectorPanel, SLOT(toggle(bool)));
572
573     addDockWidget(Qt::BottomDockWidgetArea, m_webInspectorPanel);
574     m_webInspectorPanel->hide();
575     
576     // STEP 4
577     // Setup Network analyzer panel
578     m_analyzerPanel = new NetworkAnalyzerPanel( i18n("Network Analyzer"), this);
579     connect(mainView(), SIGNAL(currentChanged(int)), m_analyzerPanel, SLOT(changeCurrentPage()));
580
581     a = new KAction(KIcon("document-edit-decrypt-verify"), i18n("Network Analyzer"), this);
582     a->setCheckable(true);
583     actionCollection()->addAction(QL1S("net_analyzer"), a);
584     connect(a, SIGNAL(triggered(bool)), this, SLOT(enableNetworkAnalysis(bool)));
585
586     addDockWidget(Qt::BottomDockWidgetArea, m_analyzerPanel);
587     m_analyzerPanel->hide();
588 }
589
590
591 void MainWindow::openLocation()
592 {
593     m_view->urlBar()->selectAll();
594     m_view->urlBar()->setFocus();
595 }
596
597
598 void MainWindow::fileSaveAs()
599 {
600     KUrl srcUrl = currentTab()->url();
601
602     QString name = srcUrl.fileName();
603     if (name.isNull())
604     {
605         name = srcUrl.host() + QString(".html");
606     }
607     const QString destUrl = KFileDialog::getSaveFileName(name, QString(), this);
608     if (destUrl.isEmpty()) return;
609     KIO::Job *job = KIO::file_copy(srcUrl, KUrl(destUrl), -1, KIO::Overwrite);
610     job->addMetaData("MaxCacheSize", "0");  // Don't store in http cache.
611     job->addMetaData("cache", "cache");     // Use entry from cache if available.
612     job->uiDelegate()->setAutoErrorHandlingEnabled(true);
613 }
614
615
616 void MainWindow::preferences()
617 {
618     // an instance the dialog could be already created and could be cached,
619     // in which case you want to display the cached dialog
620     if (SettingsDialog::showDialog("rekonfig"))
621         return;
622
623     // we didn't find an instance of this dialog, so lets create it
624     QPointer<SettingsDialog> s = new SettingsDialog(this);
625
626     // keep us informed when the user changes settings
627     connect(s, SIGNAL(settingsChanged(const QString&)), Application::instance(), SLOT(updateConfiguration()));
628
629     s->exec();
630     delete s;
631 }
632
633
634 void MainWindow::updateActions()
635 {
636     bool rekonqPage = currentTab()->page()->isOnRekonqPage();
637     
638     QAction *historyBackAction = actionByName(KStandardAction::name(KStandardAction::Back));
639     if( rekonqPage )
640         historyBackAction->setEnabled(true);
641     else
642         historyBackAction->setEnabled(currentTab()->view()->history()->canGoBack());
643
644     QAction *historyForwardAction = actionByName(KStandardAction::name(KStandardAction::Forward));
645     historyForwardAction->setEnabled(currentTab()->view()->history()->canGoForward());
646
647     QAction *openClosedTabsAction = actionByName( QL1S("open_closed_tabs") );
648     openClosedTabsAction->setEnabled(mainView()->recentlyClosedTabs().size() > 0);
649
650     // update closed tabs menu
651     KActionMenu *am = dynamic_cast<KActionMenu *>(actionByName( QL1S("closed_tab_menu") ));
652     if (!am)
653         return;
654
655     am->setEnabled(mainView()->recentlyClosedTabs().size() > 0);
656
657     if (am->menu())
658         am->menu()->clear();
659
660     foreach (HistoryItem item, mainView()->recentlyClosedTabs())
661     {
662         KAction *a = new KAction(Application::icon(item.url), item.title, this);
663         a->setData(item.url);
664         connect(a, SIGNAL(triggered()), m_view, SLOT(openClosedTab()));
665         am->addAction(a);
666     }
667 }
668
669
670 void MainWindow::updateWindowTitle(const QString &title)
671 {
672     QWebSettings *settings = QWebSettings::globalSettings();
673     if (title.isEmpty())
674     {
675         if (settings->testAttribute(QWebSettings::PrivateBrowsingEnabled))
676         {
677             setWindowTitle(i18nc("Window title when private browsing is activated", "rekonq (Private Browsing)"));
678         }
679         else
680         {
681             setWindowTitle("rekonq");
682         }
683     }
684     else
685     {
686         if (settings->testAttribute(QWebSettings::PrivateBrowsingEnabled))
687         {
688             setWindowTitle(i18nc("window title, %1 = title of the active website", "%1 – rekonq (Private Browsing)", title));
689         }
690         else
691         {
692             setWindowTitle(i18nc("window title, %1 = title of the active website", "%1 – rekonq", title));
693         }
694     }
695 }
696
697
698 void MainWindow::fileOpen()
699 {
700     QString filePath = KFileDialog::getOpenFileName(KUrl(),
701                        i18n("*.html *.htm *.svg *.png *.gif *.svgz|Web Resources (*.html *.htm *.svg *.png *.gif *.svgz)\n"
702                             "*.*|All files (*.*)"),
703                        this,
704                        i18n("Open Web Resource"));
705
706     if (filePath.isEmpty())
707         return;
708
709     Application::instance()->loadUrl(filePath);
710 }
711
712
713 void MainWindow::printRequested(QWebFrame *frame)
714 {
715     if (!currentTab())
716         return;
717
718     QWebFrame *printFrame = 0;
719     if (frame == 0)
720     {
721         printFrame = currentTab()->page()->mainFrame();
722     }
723     else
724     {
725         printFrame = frame;
726     }
727
728     QPrinter printer;
729     QPrintPreviewDialog previewdlg(&printer, this);
730
731     connect(&previewdlg, SIGNAL(paintRequested(QPrinter *)), printFrame, SLOT(print(QPrinter *)));
732
733     previewdlg.exec();
734 }
735
736
737 void MainWindow::privateBrowsing(bool enable)
738 {
739     QWebSettings *settings = QWebSettings::globalSettings();
740     if (enable && !settings->testAttribute(QWebSettings::PrivateBrowsingEnabled))
741     {
742         QString title = i18n("Are you sure you want to turn on private browsing?");
743         QString text = i18n("<b>%1</b>"
744                             "<p>When private browsing is turned on,"
745                             " web pages are not added to the history,"
746                             " new cookies are not stored, current cookies cannot be accessed,"
747                             " site icons will not be stored, the session will not be saved."
748                             " Until you close the window, you can still click the Back and Forward buttons"
749                             " to return to the web pages you have opened.</p>", title);
750
751         int button = KMessageBox::warningContinueCancel(this, text, title);
752         if (button == KMessageBox::Continue)
753         {
754             settings->setAttribute(QWebSettings::PrivateBrowsingEnabled, true);
755             m_view->urlBar()->setPrivateMode(true);
756         }
757         else
758         {
759             actionCollection()->action( QL1S("private_browsing") )->setChecked(false);
760         }
761     }
762     else
763     {
764         settings->setAttribute(QWebSettings::PrivateBrowsingEnabled, false);
765         m_view->urlBar()->setPrivateMode(false);
766
767         m_lastSearch.clear();
768         m_view->reloadAllTabs();
769     }
770 }
771
772
773 void MainWindow::find(const QString & search)
774 {
775     if (!currentTab())
776         return;
777     m_lastSearch = search;
778
779     findNext();
780 }
781
782
783 void MainWindow::matchCaseUpdate()
784 {
785     if (!currentTab())
786         return;
787
788     currentTab()->view()->findText(m_lastSearch, QWebPage::FindBackward);
789     findNext();
790 }
791
792
793 void MainWindow::findNext()
794 {
795     if (!currentTab())
796         return;
797
798     highlightAll();
799
800     if (m_findBar->isHidden())
801     {
802         QPoint previous_position = currentTab()->view()->page()->currentFrame()->scrollPosition();
803         currentTab()->view()->page()->focusNextPrevChild(true);
804         currentTab()->view()->page()->currentFrame()->setScrollPosition(previous_position);
805         return;
806     }
807
808     highlightAll();
809
810     QWebPage::FindFlags options = QWebPage::FindWrapsAroundDocument;
811     if (m_findBar->matchCase())
812         options |= QWebPage::FindCaseSensitively;
813
814     bool found = currentTab()->view()->findText(m_lastSearch, options);
815     m_findBar->notifyMatch(found);
816
817     if (!found)
818     {
819         QPoint previous_position = currentTab()->view()->page()->currentFrame()->scrollPosition();
820         currentTab()->view()->page()->focusNextPrevChild(true);
821         currentTab()->view()->page()->currentFrame()->setScrollPosition(previous_position);
822     }
823 }
824
825
826 void MainWindow::findPrevious()
827 {
828     if (!currentTab())
829         return;
830
831     QWebPage::FindFlags options = QWebPage::FindBackward | QWebPage::FindWrapsAroundDocument;
832     if (m_findBar->matchCase())
833         options |= QWebPage::FindCaseSensitively;
834
835     bool found = currentTab()->view()->findText(m_lastSearch, options);
836     m_findBar->notifyMatch(found);
837 }
838
839 void MainWindow::highlightAll()
840 {
841     if (!currentTab())
842         return;
843
844     QWebPage::FindFlags options = QWebPage::HighlightAllOccurrences;
845
846     currentTab()->view()->findText("", options); //Clear an existing highlight
847
848     if (m_findBar->highlightAllState() && !m_findBar->isHidden())
849     {
850         if (m_findBar->matchCase())
851             options |= QWebPage::FindCaseSensitively;
852
853         currentTab()->view()->findText(m_lastSearch, options);
854     }
855 }
856
857
858 void MainWindow::zoomIn()
859 {
860     m_zoomSlider->setValue(m_zoomSlider->value() + 1);
861 }
862
863
864 void MainWindow::zoomNormal()
865 {
866     m_zoomSlider->setValue(10);
867 }
868
869
870 void MainWindow::zoomOut()
871 {
872     m_zoomSlider->setValue(m_zoomSlider->value() - 1);
873 }
874
875
876 void MainWindow::setZoomFactor(int factor)
877 {
878     if (!currentTab())
879         return;
880     currentTab()->view()->setZoomFactor(QVariant(factor).toReal() / 10);
881 }
882
883
884 void MainWindow::setZoomSliderFactor(qreal factor)
885 {
886     m_zoomSlider->setValue(factor*10);
887 }
888
889
890 void MainWindow::viewFullScreen(bool makeFullScreen)
891 {
892     setWidgetsVisible(!makeFullScreen);
893     KToggleFullScreenAction::setFullScreen(this, makeFullScreen);
894 }
895
896
897 void MainWindow::setWidgetsVisible(bool makeVisible)
898 {
899     // state flags
900     static bool bookmarksToolBarFlag;
901     static bool historyPanelFlag;
902     static bool bookmarksPanelFlag;
903
904     if (!makeVisible)
905     {
906         // save current state, if in windowed mode
907         if (!isFullScreen())
908         {
909             bookmarksToolBarFlag = m_bmBar->isHidden();
910             historyPanelFlag = m_historyPanel->isHidden();
911             bookmarksPanelFlag = m_bookmarksPanel->isHidden();
912         }
913
914         m_bmBar->hide();
915         m_view->setTabBarHidden(true);
916         m_historyPanel->hide();
917         m_bookmarksPanel->hide();
918
919         // hide main toolbar
920         m_mainBar->hide();
921     }
922     else
923     {
924         // show main toolbar
925         m_mainBar->show();
926         m_view->setTabBarHidden(false);
927
928         // restore state of windowed mode
929         if (!bookmarksToolBarFlag)
930             m_bmBar->show();
931         if (!historyPanelFlag)
932             m_historyPanel->show();
933         if (!bookmarksPanelFlag)
934             m_bookmarksPanel->show();
935     }
936 }
937
938
939 void MainWindow::viewPageSource()
940 {
941     if (!currentTab())
942         return;
943
944     KUrl url(currentTab()->url());
945     bool isTempFile = false;
946     if (!url.isLocalFile())
947     {
948         KTemporaryFile sourceFile;
949
950         /// TODO: autochoose tempfile suffix
951         sourceFile.setSuffix(QString(".html"));
952         sourceFile.setAutoRemove(false);
953
954         if (sourceFile.open())
955         {
956             sourceFile.write(currentTab()->page()->mainFrame()->toHtml().toUtf8());
957
958             url = KUrl();
959             url.setPath(sourceFile.fileName());
960             isTempFile = true;
961         }
962     }
963     KRun::runUrl(url, QL1S("text/plain"), this, isTempFile);
964 }
965
966
967 void MainWindow::homePage(Qt::MouseButtons mouseButtons, Qt::KeyboardModifiers keyboardModifiers)
968 {
969     KUrl homeUrl = ReKonfig::useNewTabPage() 
970         ? KUrl( QL1S("about:home") )
971         : KUrl( ReKonfig::homePage() );
972         
973     if (mouseButtons == Qt::MidButton || keyboardModifiers == Qt::ControlModifier)
974         Application::instance()->loadUrl( homeUrl, Rekonq::SettingOpenTab);
975     else
976         currentTab()->view()->load( homeUrl );
977 }
978
979
980 WebTab *MainWindow::currentTab() const
981 {
982     return m_view->currentWebTab();
983 }
984
985
986 void MainWindow::browserLoading(bool v)
987 {
988     QAction *stop = actionCollection()->action( QL1S("stop") );
989     QAction *reload = actionCollection()->action( QL1S("view_redisplay") );
990     if (v)
991     {
992         disconnect(m_stopReloadAction, SIGNAL(triggered(bool)), reload , SIGNAL(triggered(bool)));
993         m_stopReloadAction->setIcon(KIcon("process-stop"));
994         m_stopReloadAction->setToolTip(i18n("Stop loading the current page"));
995         m_stopReloadAction->setText(i18n("Stop"));
996         connect(m_stopReloadAction, SIGNAL(triggered(bool)), stop, SIGNAL(triggered(bool)));
997     }
998     else
999     {
1000         disconnect(m_stopReloadAction, SIGNAL(triggered(bool)), stop , SIGNAL(triggered(bool)));
1001         m_stopReloadAction->setIcon(KIcon("view-refresh"));
1002         m_stopReloadAction->setToolTip(i18n("Reload the current page"));
1003         m_stopReloadAction->setText(i18n("Reload"));
1004         connect(m_stopReloadAction, SIGNAL(triggered(bool)), reload, SIGNAL(triggered(bool)));
1005
1006     }
1007 }
1008
1009
1010 void MainWindow::openPrevious(Qt::MouseButtons mouseButtons, Qt::KeyboardModifiers keyboardModifiers)
1011 {
1012     QWebHistory *history = currentTab()->view()->history();
1013     QWebHistoryItem *item = 0;
1014     
1015     if (currentTab()->page()->isOnRekonqPage())
1016     {
1017         item = new QWebHistoryItem(history->currentItem());
1018         currentTab()->view()->page()->setIsOnRekonqPage(false);
1019     }
1020     else
1021     {
1022         if (history->canGoBack())
1023         {
1024             item = new QWebHistoryItem(history->backItem());
1025         }
1026     }
1027
1028     if(!item)
1029         return;
1030     
1031     if (mouseButtons == Qt::MidButton || keyboardModifiers == Qt::ControlModifier)
1032     {
1033         Application::instance()->loadUrl(item->url(), Rekonq::SettingOpenTab);
1034     }
1035     else
1036     {
1037         history->goToItem(*item);
1038     }
1039
1040     updateActions();
1041 }
1042
1043
1044 void MainWindow::openNext(Qt::MouseButtons mouseButtons, Qt::KeyboardModifiers keyboardModifiers)
1045 {
1046     QWebHistory *history = currentTab()->view()->history();
1047     QWebHistoryItem *item = 0;
1048
1049     if (currentTab()->view()->page()->isOnRekonqPage())
1050     {
1051         item = new QWebHistoryItem(history->currentItem());
1052         currentTab()->view()->page()->setIsOnRekonqPage(false);
1053     }
1054     else
1055     {
1056         if (history->canGoForward())
1057         {
1058             item = new QWebHistoryItem(history->forwardItem());
1059         }
1060     }
1061     
1062     if(!item)
1063         return;
1064     
1065     if (mouseButtons == Qt::MidButton || keyboardModifiers == Qt::ControlModifier)
1066     {
1067         Application::instance()->loadUrl(item->url(), Rekonq::SettingOpenTab);
1068     }
1069     else
1070     {
1071         history->goToItem(*item);
1072     }
1073     
1074     updateActions();
1075 }
1076
1077
1078 void MainWindow::keyPressEvent(QKeyEvent *event)
1079 {
1080     // hide findbar
1081     if (event->key() == Qt::Key_Escape)
1082     {
1083         m_findBar->hide();
1084         currentTab()->setFocus();   // give focus to web pages
1085         return;
1086     }
1087
1088     // ctrl + tab action
1089     if ((event->modifiers() == Qt::ControlModifier) && (event->key() == Qt::Key_Tab))
1090     {
1091         emit ctrlTabPressed();
1092         return;
1093     }
1094
1095     // shift + ctrl + tab action
1096     if ((event->modifiers() == Qt::ControlModifier + Qt::ShiftModifier) && (event->key() == Qt::Key_Backtab))
1097     {
1098         emit shiftCtrlTabPressed();
1099         return;
1100     }
1101
1102     // close current tab action
1103     if ((event->modifiers() == Qt::ControlModifier) && event->key() == Qt::Key_W)
1104     {
1105         m_view->closeTab(m_view->currentIndex());
1106         return;
1107     }
1108
1109     KMainWindow::keyPressEvent(event);
1110 }
1111
1112
1113 void MainWindow::notifyMessage(const QString &msg, Rekonq::Notify status)
1114 {
1115     if (this != QApplication::activeWindow())
1116     {
1117         return;
1118     }
1119
1120     // deleting popus if empty msgs
1121     if (msg.isEmpty())
1122     {
1123         m_hidePopup->start(250);
1124         return;
1125     }
1126
1127     m_hidePopup->stop();
1128
1129
1130     switch (status)
1131     {
1132     case Rekonq::Info:
1133         break;
1134     case Rekonq::Success:
1135         break;
1136     case Rekonq::Error:
1137         break;
1138     case Rekonq::Download:
1139         break;
1140     default:
1141         break;
1142     }
1143
1144     int margin = 4;
1145
1146     // setting the popup
1147     QLabel *label = new QLabel(msg);
1148     m_popup->setView(label);
1149     QSize labelSize(label->fontMetrics().width(msg) + 2*margin, label->fontMetrics().height() + 2*margin);
1150     if (labelSize.width() > width()) labelSize.setWidth(width());
1151     m_popup->setFixedSize(labelSize);
1152     m_popup->layout()->setAlignment(Qt::AlignTop);
1153     m_popup->layout()->setMargin(margin);
1154
1155     // useful values
1156     WebTab *tab = m_view->currentWebTab();
1157
1158     // fix crash on window close
1159     if (!tab)
1160         return;
1161
1162     // fix crash on window close
1163     if (!tab->page())
1164         return;
1165
1166     bool scrollbarIsVisible = tab->page()->currentFrame()->scrollBarMaximum(Qt::Horizontal);
1167     int scrollbarSize = 0;
1168     if (scrollbarIsVisible)
1169     {
1170         //TODO: detect QStyle size
1171         scrollbarSize = 17;
1172     }
1173
1174     QPoint webViewOrigin = tab->view()->mapToGlobal(QPoint(0, 0));
1175     int bottomLeftY = webViewOrigin.y() + tab->page()->viewportSize().height() - labelSize.height() - scrollbarSize;
1176
1177     // setting popup in bottom-left position
1178     int x = geometry().x();
1179     int y = bottomLeftY;
1180
1181     QPoint mousePos = tab->mapToGlobal(tab->view()->mousePos());
1182     if (QRect(webViewOrigin.x() , bottomLeftY , labelSize.width() , labelSize.height()).contains(mousePos))
1183     {
1184         // setting popup above the mouse
1185         y = bottomLeftY - labelSize.height();
1186     }
1187
1188     m_popup->show(QPoint(x, y));
1189 }
1190
1191
1192 void MainWindow::clearPrivateData()
1193 {
1194     QPointer<KDialog> dialog = new KDialog(this);
1195     dialog->setCaption(i18n("Clear Private Data"));
1196     dialog->setButtons(KDialog::Ok | KDialog::Cancel);
1197
1198     dialog->button(KDialog::Ok)->setIcon(KIcon("edit-clear"));
1199     dialog->button(KDialog::Ok)->setText(i18n("Clear"));
1200
1201     Ui::ClearDataWidget clearWidget;
1202     QWidget widget;
1203     clearWidget.setupUi(&widget);
1204
1205     dialog->setMainWidget(&widget);
1206     dialog->exec();
1207
1208     if (dialog->result() == QDialog::Accepted)
1209     {
1210         if (clearWidget.clearHistory->isChecked())
1211         {
1212             Application::historyManager()->clear();
1213         }
1214
1215         if (clearWidget.clearDownloads->isChecked())
1216         {
1217             Application::historyManager()->clearDownloadsHistory();
1218         }
1219
1220         if (clearWidget.clearCookies->isChecked())
1221         {
1222             QDBusInterface kcookiejar("org.kde.kded", "/modules/kcookiejar", "org.kde.KCookieServer");
1223             QDBusReply<void> reply = kcookiejar.call("deleteAllCookies");
1224         }
1225
1226         if (clearWidget.clearCachedPages->isChecked())
1227         {
1228             KProcess::startDetached(KStandardDirs::findExe("kio_http_cache_cleaner"),
1229                                     QStringList(QL1S("--clear-all")));
1230         }
1231
1232         if (clearWidget.clearWebIcons->isChecked())
1233         {
1234             QWebSettings::clearIconDatabase();
1235         }
1236
1237         if (clearWidget.homePageThumbs->isChecked())
1238         {
1239             QString path = KStandardDirs::locateLocal("cache", QString("thumbs/rekonq"), true);
1240             path.remove("rekonq");
1241             QDir cacheDir(path);
1242             QStringList fileList = cacheDir.entryList();
1243             foreach(const QString &str, fileList)
1244             {
1245                 QFile file(path + str);
1246                 file.remove();
1247             }
1248         }
1249     }
1250
1251     dialog->deleteLater();
1252 }
1253
1254
1255 void MainWindow::aboutToShowBackMenu()
1256 {
1257     m_historyBackMenu->clear();
1258     if (!currentTab())
1259         return;
1260     QWebHistory *history = currentTab()->view()->history();
1261     int pivot = history->currentItemIndex();
1262     int offset = 0;
1263     QList<QWebHistoryItem> historyList = history->backItems(8); //no more than 8 elements!
1264     int listCount = historyList.count();
1265     if (pivot >= 8)
1266         offset = pivot - 8;
1267
1268     /*
1269      * Need a bug report upstream. 
1270      * Seems setHtml() do some garbage in history
1271      * Here history->currentItem() have backItem url and currentItem (error page) title
1272      */
1273     if (currentTab()->view()->page()->isOnRekonqPage())
1274     {
1275         QWebHistoryItem item = history->currentItem();
1276         KAction *action = new KAction(this);
1277         action->setData(listCount + offset++);
1278         KIcon icon = Application::icon(item.url());
1279         action->setIcon(icon);
1280         action->setText(item.title());
1281         m_historyBackMenu->addAction(action);
1282     }
1283          
1284     for (int i = listCount - 1; i >= 0; --i)
1285     {
1286         QWebHistoryItem item = historyList.at(i);
1287         KAction *action = new KAction(this);
1288         action->setData(i + offset);
1289         KIcon icon = Application::icon(item.url());
1290         action->setIcon(icon);
1291         action->setText(item.title());
1292         m_historyBackMenu->addAction(action);
1293     }
1294 }
1295
1296
1297 void MainWindow::openActionUrl(QAction *action)
1298 {
1299     int index = action->data().toInt();
1300
1301     QWebHistory *history = currentTab()->view()->history();
1302     if (!history->itemAt(index).isValid())
1303     {
1304         kDebug() << "Invalid Index!: " << index;
1305         return;
1306     }
1307
1308     history->goToItem(history->itemAt(index));
1309 }
1310
1311
1312 void MainWindow::setEncoding(QAction *qa)
1313 {
1314     QString currentCodec = qa->text().toLatin1();
1315     currentCodec = currentCodec.remove('&');
1316     kDebug() << "Setting codec: " << currentCodec;
1317     currentTab()->page()->settings()->setDefaultTextEncoding(currentCodec);
1318 }
1319
1320
1321 void MainWindow::populateEncodingMenu()
1322 {
1323     QStringList codecs;
1324     QList<int> mibs = QTextCodec::availableMibs();
1325     Q_FOREACH (const int &mib, mibs) 
1326     {
1327         QString codec = QLatin1String(QTextCodec::codecForMib(mib)->name());
1328         codecs.append(codec);
1329     }
1330     codecs.sort();
1331
1332     QString currentCodec = currentTab()->page()->settings()->defaultTextEncoding();
1333
1334     m_encodingMenu->clear();
1335     KMenu *isoMenu = new KMenu( QL1S("ISO"), m_encodingMenu);
1336     KMenu *winMenu = new KMenu( QL1S("windows"), m_encodingMenu);
1337     KMenu *isciiMenu = new KMenu( QL1S("Iscii"), m_encodingMenu);
1338     KMenu *uniMenu = new KMenu( QL1S("UNICODE"), m_encodingMenu);
1339     KMenu *otherMenu = new KMenu( QL1S("Other"), m_encodingMenu);
1340     
1341     QAction *a;
1342     Q_FOREACH(const QString &codec, codecs)
1343     {
1344         
1345         if( codec.startsWith( QL1S("ISO"), Qt::CaseInsensitive ) )
1346             a = isoMenu->addAction(codec);
1347         else if( codec.startsWith( QL1S("win") ) )
1348             a = winMenu->addAction(codec);
1349         else if( codec.startsWith( QL1S("Iscii") ) )
1350             a = isciiMenu->addAction(codec);
1351         else if( codec.startsWith( QL1S("UT") ) )
1352             a = uniMenu->addAction(codec);
1353         else 
1354             a = otherMenu->addAction(codec);
1355             
1356         a->setCheckable(true);
1357         if (currentCodec == codec)
1358             a->setChecked(true);
1359     }
1360     m_encodingMenu->addMenu( isoMenu );
1361     m_encodingMenu->addMenu( winMenu );
1362     m_encodingMenu->addMenu( isciiMenu );
1363     m_encodingMenu->addMenu( uniMenu );
1364     m_encodingMenu->addMenu( otherMenu );
1365 }
1366
1367
1368 void MainWindow::enableNetworkAnalysis(bool b)
1369 {
1370     currentTab()->page()->enableNetworkAnalyzer(b);
1371     m_analyzerPanel->toggle(b);
1372 }
1373
1374
1375 bool MainWindow::queryClose()
1376 {
1377     if (m_view->count() > 1)                                                                                                              
1378     {
1379         int answer = KMessageBox::questionYesNoCancel(                                                                                    
1380                         this,                                                                                                            
1381                         i18np("Are you sure you want to close the window?\n" "You have 1 tab open.",
1382                          "Are you sure you want to close the window?\n" "You have %1 tabs open.", 
1383                         m_view->count()),
1384                         i18n("Are you sure you want to close the window?"),                                                              
1385                         KStandardGuiItem::quit(),                                                                                        
1386                         KGuiItem(i18n("C&lose Current Tab"), KIcon("tab-close")),                                                        
1387                         KStandardGuiItem::cancel(),                                                                                      
1388                         "confirmClosingMultipleTabs"                                                                                     
1389                                                         );                                                                                                                   
1390                                                                                                                     
1391         switch (answer)                                                                                                                   
1392         {                                                                                                                                 
1393             case KMessageBox::Yes:  
1394                 // Quit                                                                                                                         
1395                 return true;                                                                                                                  
1396             
1397             case KMessageBox::No:                                                                                                             
1398                 // Close only the current tab                                                                                                 
1399                 m_view->closeTab();
1400             
1401             default:                                                                                                                          
1402                 return false;                                                                                                                 
1403         }                                                                                                                                 
1404     }                                                                                                                                     
1405     return true;                                                                                                                          
1406 }