From 145abc15d57fb29701a12e8a14dcb9c1fd72e9be Mon Sep 17 00:00:00 2001 From: Michele Calgaro Date: Mon, 7 Dec 2020 22:58:44 +0900 Subject: Renaming of files in preparation for code style tools. Signed-off-by: Michele Calgaro --- konqueror/CMakeLists.txt | 14 +- konqueror/ChangeLog | 126 +- konqueror/KonqMainWindowIface.cc | 175 - konqueror/KonqMainWindowIface.cpp | 175 + konqueror/KonqViewIface.cc | 141 - konqueror/KonqViewIface.cpp | 141 + konqueror/KonquerorIface.cc | 294 -- konqueror/KonquerorIface.cpp | 294 ++ konqueror/Makefile.am | 38 +- konqueror/about/CMakeLists.txt | 2 +- konqueror/about/Makefile.am | 2 +- konqueror/about/konq_aboutpage.cc | 558 --- konqueror/about/konq_aboutpage.cpp | 558 +++ konqueror/client/CMakeLists.txt | 2 +- konqueror/client/Makefile.am | 4 +- konqueror/client/kfmclient.cc | 653 --- konqueror/client/kfmclient.cpp | 653 +++ konqueror/delayedinitializer.cc | 52 - konqueror/delayedinitializer.cpp | 52 + konqueror/iconview/CMakeLists.txt | 2 +- konqueror/iconview/Makefile.am | 2 +- konqueror/iconview/konq_iconview.cc | 1660 ------- konqueror/iconview/konq_iconview.cpp | 1660 +++++++ konqueror/konq_actions.cc | 504 -- konqueror/konq_actions.cpp | 504 ++ konqueror/konq_browseriface.cc | 22 - konqueror/konq_browseriface.cpp | 22 + konqueror/konq_combo.cc | 905 ---- konqueror/konq_combo.cpp | 905 ++++ konqueror/konq_extensionmanager.cc | 147 - konqueror/konq_extensionmanager.cpp | 147 + konqueror/konq_factory.cc | 264 -- konqueror/konq_factory.cpp | 264 ++ konqueror/konq_frame.cc | 680 --- konqueror/konq_frame.cpp | 680 +++ konqueror/konq_guiclients.cc | 363 -- konqueror/konq_guiclients.cpp | 363 ++ konqueror/konq_main.cc | 222 - konqueror/konq_main.cpp | 222 + konqueror/konq_mainwindow.cc | 5998 ------------------------ konqueror/konq_mainwindow.cpp | 5998 ++++++++++++++++++++++++ konqueror/konq_misc.cc | 281 -- konqueror/konq_misc.cpp | 281 ++ konqueror/konq_misc.h | 2 +- konqueror/konq_profiledlg.cc | 266 -- konqueror/konq_profiledlg.cpp | 266 ++ konqueror/konq_run.cc | 195 - konqueror/konq_run.cpp | 195 + konqueror/konq_tabs.cc | 609 --- konqueror/konq_tabs.cpp | 609 +++ konqueror/konq_view.cc | 1398 ------ konqueror/konq_view.cpp | 1398 ++++++ konqueror/konq_viewmgr.cc | 1842 -------- konqueror/konq_viewmgr.cpp | 1842 ++++++++ konqueror/konqueror.kcfg | 10 +- konqueror/listview/CMakeLists.txt | 8 +- konqueror/listview/Makefile.am | 10 +- konqueror/listview/konq_infolistviewitem.cc | 280 -- konqueror/listview/konq_infolistviewitem.cpp | 280 ++ konqueror/listview/konq_infolistviewwidget.cc | 384 -- konqueror/listview/konq_infolistviewwidget.cpp | 384 ++ konqueror/listview/konq_listview.cc | 731 --- konqueror/listview/konq_listview.cpp | 731 +++ konqueror/listview/konq_listviewitems.cc | 459 -- konqueror/listview/konq_listviewitems.cpp | 459 ++ konqueror/listview/konq_listviewwidget.cc | 1592 ------- konqueror/listview/konq_listviewwidget.cpp | 1592 +++++++ konqueror/listview/konq_textviewitem.cc | 258 - konqueror/listview/konq_textviewitem.cpp | 258 + konqueror/listview/konq_textviewwidget.cc | 224 - konqueror/listview/konq_textviewwidget.cpp | 224 + konqueror/listview/konq_treeviewitem.cc | 101 - konqueror/listview/konq_treeviewitem.cpp | 101 + konqueror/listview/konq_treeviewwidget.cc | 307 -- konqueror/listview/konq_treeviewwidget.cpp | 307 ++ konqueror/preloader/CMakeLists.txt | 2 +- konqueror/preloader/Makefile.am | 2 +- konqueror/preloader/configure.in.in | 2 +- konqueror/preloader/preloader.cc | 151 - konqueror/preloader/preloader.cpp | 151 + 80 files changed, 21830 insertions(+), 21830 deletions(-) delete mode 100644 konqueror/KonqMainWindowIface.cc create mode 100644 konqueror/KonqMainWindowIface.cpp delete mode 100644 konqueror/KonqViewIface.cc create mode 100644 konqueror/KonqViewIface.cpp delete mode 100644 konqueror/KonquerorIface.cc create mode 100644 konqueror/KonquerorIface.cpp delete mode 100644 konqueror/about/konq_aboutpage.cc create mode 100644 konqueror/about/konq_aboutpage.cpp delete mode 100644 konqueror/client/kfmclient.cc create mode 100644 konqueror/client/kfmclient.cpp delete mode 100644 konqueror/delayedinitializer.cc create mode 100644 konqueror/delayedinitializer.cpp delete mode 100644 konqueror/iconview/konq_iconview.cc create mode 100644 konqueror/iconview/konq_iconview.cpp delete mode 100644 konqueror/konq_actions.cc create mode 100644 konqueror/konq_actions.cpp delete mode 100644 konqueror/konq_browseriface.cc create mode 100644 konqueror/konq_browseriface.cpp delete mode 100644 konqueror/konq_combo.cc create mode 100644 konqueror/konq_combo.cpp delete mode 100644 konqueror/konq_extensionmanager.cc create mode 100644 konqueror/konq_extensionmanager.cpp delete mode 100644 konqueror/konq_factory.cc create mode 100644 konqueror/konq_factory.cpp delete mode 100644 konqueror/konq_frame.cc create mode 100644 konqueror/konq_frame.cpp delete mode 100644 konqueror/konq_guiclients.cc create mode 100644 konqueror/konq_guiclients.cpp delete mode 100644 konqueror/konq_main.cc create mode 100644 konqueror/konq_main.cpp delete mode 100644 konqueror/konq_mainwindow.cc create mode 100644 konqueror/konq_mainwindow.cpp delete mode 100644 konqueror/konq_misc.cc create mode 100644 konqueror/konq_misc.cpp delete mode 100644 konqueror/konq_profiledlg.cc create mode 100644 konqueror/konq_profiledlg.cpp delete mode 100644 konqueror/konq_run.cc create mode 100644 konqueror/konq_run.cpp delete mode 100644 konqueror/konq_tabs.cc create mode 100644 konqueror/konq_tabs.cpp delete mode 100644 konqueror/konq_view.cc create mode 100644 konqueror/konq_view.cpp delete mode 100644 konqueror/konq_viewmgr.cc create mode 100644 konqueror/konq_viewmgr.cpp delete mode 100644 konqueror/listview/konq_infolistviewitem.cc create mode 100644 konqueror/listview/konq_infolistviewitem.cpp delete mode 100644 konqueror/listview/konq_infolistviewwidget.cc create mode 100644 konqueror/listview/konq_infolistviewwidget.cpp delete mode 100644 konqueror/listview/konq_listview.cc create mode 100644 konqueror/listview/konq_listview.cpp delete mode 100644 konqueror/listview/konq_listviewitems.cc create mode 100644 konqueror/listview/konq_listviewitems.cpp delete mode 100644 konqueror/listview/konq_listviewwidget.cc create mode 100644 konqueror/listview/konq_listviewwidget.cpp delete mode 100644 konqueror/listview/konq_textviewitem.cc create mode 100644 konqueror/listview/konq_textviewitem.cpp delete mode 100644 konqueror/listview/konq_textviewwidget.cc create mode 100644 konqueror/listview/konq_textviewwidget.cpp delete mode 100644 konqueror/listview/konq_treeviewitem.cc create mode 100644 konqueror/listview/konq_treeviewitem.cpp delete mode 100644 konqueror/listview/konq_treeviewwidget.cc create mode 100644 konqueror/listview/konq_treeviewwidget.cpp delete mode 100644 konqueror/preloader/preloader.cc create mode 100644 konqueror/preloader/preloader.cpp (limited to 'konqueror') diff --git a/konqueror/CMakeLists.txt b/konqueror/CMakeLists.txt index bd6f9d974..aa6091502 100644 --- a/konqueror/CMakeLists.txt +++ b/konqueror/CMakeLists.txt @@ -141,13 +141,13 @@ tde_add_library( ${target} STATIC_PIC set( target konqueror ) set( ${target}_SRCS - konq_main.cc KonquerorIface.cc KonquerorIface.skel - KonqMainWindowIface.cc KonqMainWindowIface.skel - KonqViewIface.cc KonqViewIface.skel konq_guiclients.cc - konq_run.cc konq_view.cc konq_viewmgr.cc konq_misc.cc - konq_frame.cc konq_tabs.cc konq_actions.cc konq_profiledlg.cc - konq_factory.cc konq_combo.cc konq_browseriface.cc - delayedinitializer.cc konq_mainwindow.cc konq_extensionmanager.cc + konq_main.cpp KonquerorIface.cpp KonquerorIface.skel + KonqMainWindowIface.cpp KonqMainWindowIface.skel + KonqViewIface.cpp KonqViewIface.skel konq_guiclients.cpp + konq_run.cpp konq_view.cpp konq_viewmgr.cpp konq_misc.cpp + konq_frame.cpp konq_tabs.cpp konq_actions.cpp konq_profiledlg.cpp + konq_factory.cpp konq_combo.cpp konq_browseriface.cpp + delayedinitializer.cpp konq_mainwindow.cpp konq_extensionmanager.cpp ) tde_add_tdeinit_executable( ${target} AUTOMOC diff --git a/konqueror/ChangeLog b/konqueror/ChangeLog index bdd198606..a6b8bed4c 100644 --- a/konqueror/ChangeLog +++ b/konqueror/ChangeLog @@ -5,14 +5,14 @@ 2001-05-05 David Faure - * konq_mainwindow.cc: Set WDestructiveClose again when going + * konq_mainwindow.cpp: Set WDestructiveClose again when going to fullscreen mode (Qt bug), to prevent Alt+F4 from crashing. - * konq_misc.cc: Only abort full-screen mode for windows on the + * konq_misc.cpp: Only abort full-screen mode for windows on the current desktop. 2001-05-01 Simon Hausmann - * konq_mainwindow.cc : moved the connect and disconnect calls + * konq_mainwindow.cpp : moved the connect and disconnect calls to/from the highlighting signals of the actioncollections into two separate methods, for cleanup, and use the qt child deletion mechanism to delete the bookmark actioncollection @@ -26,11 +26,11 @@ starts flickering like mad, when the window width is getting small than the length of the url in the combobox. - * konq_mainwindow.cc (initActions): use KonqGoURLAction + * konq_mainwindow.cpp (initActions): use KonqGoURLAction 2001-04-27 Simon Hausmann - * konq_mainwindow.cc (goURL): new slot, sending a fake key + * konq_mainwindow.cpp (goURL): new slot, sending a fake key event to the lineedit, acting like the user pressing return (initActions): allocate a "Go" action and connect it to the new goURL slot @@ -39,22 +39,22 @@ 2001-04-07 Simon Hausmann - * konq_mainwindow.cc (slotReload): call m_currentView->lockHistory(), + * konq_mainwindow.cpp (slotReload): call m_currentView->lockHistory(), to fix #23818 - * konq_view.cc/h (reload): removed obsolete method + * konq_view.cpp/h (reload): removed obsolete method 2001-03-31 David Faure - * konq_mainwindow.cc(slotRunFinished): Stop wheel animation when a + * konq_mainwindow.cpp(slotRunFinished): Stop wheel animation when a konqrun fails and we have no view. 2001-03-25 Simon Hausmann - * iconview/konq_iconview.cc (KonqKfmIconView): specify a status text for + * iconview/konq_iconview.cpp (KonqKfmIconView): specify a status text for some actions. Likewise for some actions in KonqDirPart. Also call setHighlightingEnabled in the KonqDirPart constructor - * konq_mainwindow.cc (slotShowMenuBar): call saveMainWindowSettings and + * konq_mainwindow.cpp (slotShowMenuBar): call saveMainWindowSettings and TDEGlobal::config()->sync() after toggling the visiblity of the menubar, just like it is done for toolbars. (slotPartActivated): connect and disconnect to/from the actionStatusText @@ -62,25 +62,25 @@ 2001-03-02 Simon Hausmann - * konq_view.cc, konq_browseriface.cc/h: Utilize and implement the newly + * konq_view.cpp, konq_browseriface.cpp/h: Utilize and implement the newly added KParts::BrowserInterface 2001-02-06 Simon Hausmann - * konq_mainwindow.cc (openBookmarkURL): Patch by + * konq_mainwindow.cpp (openBookmarkURL): Patch by Marco Krohn to call openFilteredURL instead of openURL. Allows environment variables in bookmarks and other sugar. 2001-01-28 Stephan Kulow - * konq_mainwindow.cc (initActions): Plug the actions into a TDEAccel to + * konq_mainwindow.cpp (initActions): Plug the actions into a TDEAccel to fix short cuts in full screen mode 2001-01-16 Simon Hausmann - * konq_actions.cc (fillHistoryPopup), - libkonq/kbookmarkmenu.cc (fillBookmarkMenu): When a Website has + * konq_actions.cpp (fillHistoryPopup), + libkonq/kbookmarkmenu.cpp (fillBookmarkMenu): When a Website has "&" in the Title, make sure to transform it into "&&" before inserting it into a QPopupMenu (for history or for bookmarks) , to avoid QPopupMenu interpreting it as accelerator. @@ -88,30 +88,30 @@ 2001-01-15 David Faure - * konq_aboutpage.cc, konq_mainwindow.cc: Support for "about:konqueror". + * konq_aboutpage.cpp, konq_mainwindow.cpp: Support for "about:konqueror". Credits to Simon for the part, and Torsten for the icons. 2001-01-14 David Faure - * konq_viewmgr.cc (loadItem): Use openView instead of view->openURL, + * konq_viewmgr.cpp (loadItem): Use openView instead of view->openURL, so that "view-follows-view" is also applied on startup. Fixes #17679. - * konq_mainwindow.cc etc.: Lock to current location doesn't make the + * konq_mainwindow.cpp etc.: Lock to current location doesn't make the view passive anymore. This allows to e.g. change the view mode. - * konq_frame.cc: Added Lock / Unlock to view statusbar's popupmenu. + * konq_frame.cpp: Added Lock / Unlock to view statusbar's popupmenu. 2001-01-13 David Faure - * konq_dirpart.cc etc.: Always paste to current directory, even + * konq_dirpart.cpp etc.: Always paste to current directory, even when an item is selected. 2001-01-12 David Faure - * konq_viewmgr.cc (loadViewProfile): Set active part before loading + * konq_viewmgr.cpp (loadViewProfile): Set active part before loading URL, so that the URL appears in the location bar. - * konq_mainwindow.cc, konq_dirpart.cc: Store find part into history, + * konq_mainwindow.cpp, konq_dirpart.cpp: Store find part into history, in order to restore it when pressing back. 2001-01-11 David Faure @@ -132,7 +132,7 @@ 2001-01-08 Simon Hausmann - * KonquerorIface.cc (openBrowserWindow), + * KonquerorIface.cpp (openBrowserWindow), (createNewWindow), (createNewWindow), (createBrowserWindowFromProfile), @@ -150,14 +150,14 @@ 2000-12-28 Simon Hausmann - * konq_viewmgr.cc (loadViewProfile): When loading an empty profile + * konq_viewmgr.cpp (loadViewProfile): When loading an empty profile (in particular the webbrowsing one) , activate the clear_location action. This gives the focus to the location bar -> the user can type in an url right away when loading the webbrowsing profile 2000-12-27 Simon Hausmann - * konq_mainwindow.cc (enableAllActions): for iterating over all actions + * konq_mainwindow.cpp (enableAllActions): for iterating over all actions don't use the action( int index ) method of TDEActionCollection but instead retrieve a QValueList and iterate over that, as the =+(int) operator of QDictIterator isn't really fast @@ -166,16 +166,16 @@ 2000-12-12 David Faure - * konq_viewmgr.cc: Fixed saving of profiles containing views + * konq_viewmgr.cpp: Fixed saving of profiles containing views "locked to their current location". The attribute was missing from the profile. - * konq_mainwindow.cc: Save and restore the preferred service in for + * konq_mainwindow.cpp: Save and restore the preferred service in for each toolbar 'viewmode' button. 2000-12-10 David Faure - * konq_mainwindow.cc, konq_view.*, browserextension.*: Fixed + * konq_mainwindow.cpp, konq_view.*, browserextension.*: Fixed the initial state of the common actions (cut,copy,paste etc.). Had to move all the handling of the action states to browserextension. @@ -203,7 +203,7 @@ 2000-12-08 David Faure - * konq_mainwindow.cc (openURL): Support for about:blank + * konq_mainwindow.cpp (openURL): Support for about:blank Fix for severe problems with the activation of the standard actions. The state of the action is now stored in each KonqView. @@ -220,77 +220,77 @@ 2000-12-06 Matthias Elter - * konq_mainwindow.cc: Turned the Configure submenu into a single dialog. + * konq_mainwindow.cpp: Turned the Configure submenu into a single dialog. 2000-12-02 David Faure - * konq_mainwindow.cc (slotToolFind): "Find Files" now embeds the kfind + * konq_mainwindow.cpp (slotToolFind): "Find Files" now embeds the kfind part, and the result of the search is connected to the current directory part. "Close" or opening any other URL closes the 'find' part. Thanks to Eric Coquelle for the kfind classes, and to jpmartin for pushing us to do this :) - * konq_viewmgr.cc: Support for suicidal passive views, more arguments + * konq_viewmgr.cpp: Support for suicidal passive views, more arguments to splitView and splitWindow. - * konq_guiclients.cc: Duplicated code removed, uses splitWindow now. + * konq_guiclients.cpp: Duplicated code removed, uses splitWindow now. 2000-11-30 David Faure - * konq_mainwindow.cc: Use current profile in "New Window" to fix #16283. + * konq_mainwindow.cpp: Use current profile in "New Window" to fix #16283. 2000-11-28 David Faure - * konq_actions.cc: Accel (Alt+O in English) to give focus to location bar, + * konq_actions.cpp: Accel (Alt+O in English) to give focus to location bar, shown by the label. - * konq_profiledlg.cc: Ported to TDEListView to fix problems with selection. + * konq_profiledlg.cpp: Ported to TDEListView to fix problems with selection. 2000-11-26 David Faure - * konq_misc.cc, kfmclient.cc, KonquerorIface.cc: Speed up for URLs opened + * konq_misc.cpp, kfmclient.cpp, KonquerorIface.cpp: Speed up for URLs opened from another process using KRun (e.g. kdesktop's Minicli), by passing the mimetype through to konqueror. 2000-11-25 David Faure - * konq_misc.cc: Fixed location bar not showing the URL asap. + * konq_misc.cpp: Fixed location bar not showing the URL asap. - * konq_mainwindow.cc : Icons for the configure submenu. + * konq_mainwindow.cpp : Icons for the configure submenu. - * konq_actions.cc : KonqHistoryAction turned into TDEToolBarPopupAction. + * konq_actions.cpp : KonqHistoryAction turned into TDEToolBarPopupAction. Drag the "Location" label to start a drag with the current URL. 2000-11-25 Simon Hausmann - * konq_view.cc (connectPart): Install new url event filter for plain + * konq_view.cpp (connectPart): Install new url event filter for plain krops and for browserviews with the enableURLDropHandling property enabled (eventFilter): New eventfilter which listens for url drop events Sat Nov 25 17:38:27 2000 Carsten Pfeiffer - * konq_mainwindow.cc: Completion handling overhauled. We have + * konq_mainwindow.cpp: Completion handling overhauled. We have one KonqHistoryManager, which holds a TDECompletion object and syncs the history with the completion. - * konq_view.cc: + * konq_view.cpp: set m_bAborted before calling slotCompleted in slotCanceled() feed the history manager - * konq_actions.cc: use KonqHistoryCombo that doesn't mess with the + * konq_actions.cpp: use KonqHistoryCombo that doesn't mess with the competion-object, we do our own synchronization now. * libkonq/ added konq_history* 2000-11-22 David Faure - * konq_listview.cc: Added "Default" Icon Size, which corresponds to + * konq_listview.cpp: Added "Default" Icon Size, which corresponds to TDEIcon::Small (but when switching to icon view, it becomes whatever's configured for the "Desktop" group). 2000-11-21 David Faure - * konq_listview.cc: Case Insensitive Sort option, on by default. + * konq_listview.cpp: Case Insensitive Sort option, on by default. * Views: Major rework of the "delayed mimetypes determination" feature, to make it available to the list view. This makes the list view @@ -303,30 +303,30 @@ Sat Nov 25 17:38:27 2000 Carsten Pfeiffer 2000-11-17 David Faure - * konq_profiledlg.cc: Made checkbox states persistent (saved to config) + * konq_profiledlg.cpp: Made checkbox states persistent (saved to config) - * konq_run.cc: Check that when we call KRun from KonqRun, it's not going + * konq_run.cpp: Check that when we call KRun from KonqRun, it's not going to launch another konqueror. - * konq_guiclients.cc: Build toggle-view actions in the actioncollection + * konq_guiclients.cpp: Build toggle-view actions in the actioncollection of the mainwindow, so that it's possible to assign them a shortcut. 2000-11-16 David Faure - * konq_viewmgr.cc: Patch by Keunwoo Lee to + * konq_viewmgr.cpp: Patch by Keunwoo Lee to implement dynamic accels for the profile submenu. 2000-11-15 David Faure - * konq_drag.cc: Export URLs as text/plain as well. + * konq_drag.cpp: Export URLs as text/plain as well. - * konq_mainwindow.cc: Implemented auto-saving of toolbars (TDEMainWindow), + * konq_mainwindow.cpp: Implemented auto-saving of toolbars (TDEMainWindow), removed "Save Settings". Fixed "clicking on directory in dirtree uses wrong view mode for dirs". - * konq_iconview.cc: Added +/- buttons for changing the icon size. + * konq_iconview.cpp: Added +/- buttons for changing the icon size. 2000-11-06 David Faure - * konq_operations.cc: statURL, calls a slot when it stat'ed + * konq_operations.cpp: statURL, calls a slot when it stat'ed the url and created a tdefileitem for it. Used in doDrop when the destination's tdefileitem is unknown. Fixes #14739. Also, KPropsDlg now does a similar thing when called with a KURL. @@ -336,30 +336,30 @@ Sat Nov 25 17:38:27 2000 Carsten Pfeiffer * konqueror.rc: Moved the "open with" actions to the Location menu, and added a separator to the action list. - * konq_view.cc (connectPart): moved call to setSaveViewPropertiesLocally + * konq_view.cpp (connectPart): moved call to setSaveViewPropertiesLocally (used to be in various places in KonqMW) so that the flag is also correct when switching views. - * konq_dirpart.cc and directory views: apply background color and pixmap + * konq_dirpart.cpp and directory views: apply background color and pixmap to the viewport(), and updated konq_iconview to do the same. This fixes many inconsistencies, and makes resizing a window much faster & smoother. Note that it has to be the viewport and not the widget, otherwise in the listview, the box between the scrollbars appears colored/pixmap-ed. - * konq_mainwindow.cc: action renamed View Properties Saved In Directory + * konq_mainwindow.cpp: action renamed View Properties Saved In Directory 2000-11-04 David Faure - * konq_viewmgr.cc: now takes care of enableAllActions. + * konq_viewmgr.cpp: now takes care of enableAllActions. Show led and active statusbar even in the tree+icon configuration (the rule is now "more than one view", not "more than one activeable view"). This should remove some confusion. - * konq_frame.cc: "Remove View" in RMB on statusbar. + * konq_frame.cpp: "Remove View" in RMB on statusbar. Don't try to activate passive views when clicking statusbar. Different background color on statusbar for active view. - * konq_mainwindow.cc: Fixes for "Remove Active View" enabling, + * konq_mainwindow.cpp: Fixes for "Remove Active View" enabling, to avoid ending up with a lonely embedded konsole, and some cleanup of code for enabling other view-related actions. Introducing updateViewActions for common code between enableAllActions @@ -393,10 +393,10 @@ Sat Nov 25 17:38:27 2000 Carsten Pfeiffer 2000-10-22 David Faure - * dirtree/konq_dirtree.cc: Fixed support for devices in the directory + * dirtree/konq_dirtree.cpp: Fixed support for devices in the directory tree. It currently requires MountPoint in the device desktop file. - * listview/konq_textviewwidget.cc: Only the Name column is now + * listview/konq_textviewwidget.cpp: Only the Name column is now selected, and used as a drop area - like in other listviews. This requires the fix in TDEListView to work properly. @@ -406,7 +406,7 @@ Sat Nov 25 17:38:27 2000 Carsten Pfeiffer 2000-10-20 David Faure - * konq_misc.cc: Use webbrowsing profile for *.html *.htm as well. + * konq_misc.cpp: Use webbrowsing profile for *.html *.htm as well. 2000-10-20 Simon Hausmann diff --git a/konqueror/KonqMainWindowIface.cc b/konqueror/KonqMainWindowIface.cc deleted file mode 100644 index a18301a2f..000000000 --- a/konqueror/KonqMainWindowIface.cc +++ /dev/null @@ -1,175 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2000 Simon Hausmann - Copyright (C) 2000 David Faure - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "KonqMainWindowIface.h" -#include "KonqViewIface.h" -#include "konq_view.h" - - -#include -#include -#include -#include -#include -#include -#include - -KonqMainWindowIface::KonqMainWindowIface( KonqMainWindow * mainWindow ) - : - // ARGL I hate this "virtual public DCOPObject" stuff! - DCOPObject( mainWindow->name() ), - TDEMainWindowInterface( mainWindow ), m_pMainWindow( mainWindow ) -{ - m_dcopActionProxy = new KDCOPActionProxy( mainWindow->actionCollection(), this ); -} - -KonqMainWindowIface::~KonqMainWindowIface() -{ - delete m_dcopActionProxy; -} - -void KonqMainWindowIface::openURL( TQString url ) -{ - m_pMainWindow->openFilteredURL( url ); -} - -void KonqMainWindowIface::newTab( TQString url ) -{ - m_pMainWindow->openFilteredURL( url, true ); -} - -void KonqMainWindowIface::openURL( TQString url, bool tempFile ) -{ - m_pMainWindow->openFilteredURL( url, false, tempFile ); -} - -void KonqMainWindowIface::newTab( TQString url, bool tempFile ) -{ - m_pMainWindow->openFilteredURL( url, true, tempFile ); -} - -void KonqMainWindowIface::newTabASN( TQString url, const TQCString& startup_id, bool tempFile ) -{ - TDEStartupInfo::setNewStartupId( m_pMainWindow, startup_id ); - m_pMainWindow->openFilteredURL( url, true, tempFile ); -} - - -void KonqMainWindowIface::splitViewHorizontally() -{ - m_pMainWindow->slotSplitViewHorizontal(); -} - -void KonqMainWindowIface::splitViewVertically() -{ - m_pMainWindow->slotSplitViewVertical(); -} - -void KonqMainWindowIface::reload() -{ - m_pMainWindow->slotReload(); -} - -DCOPRef KonqMainWindowIface::currentView() -{ - KonqView *view = m_pMainWindow->currentView(); - if ( !view ) - return DCOPRef(); - - return DCOPRef( kapp->dcopClient()->appId(), view->dcopObject()->objId() ); -} - -DCOPRef KonqMainWindowIface::currentPart() -{ - DCOPRef res; - - KonqView *view = m_pMainWindow->currentView(); - if ( !view ) - return res; - - return view->dcopObject()->part(); -} - -DCOPRef KonqMainWindowIface::view(int viewNumber) -{ - KonqMainWindow::MapViews viewMap = m_pMainWindow->viewMap(); - KonqMainWindow::MapViews::const_iterator it = viewMap.begin(); - for ( int i = 0; it != viewMap.end() && i < viewNumber; ++i ) - ++it; - if ( it == viewMap.end() ) - return DCOPRef(); - return DCOPRef( kapp->dcopClient()->appId(), (*it)->dcopObject()->objId() ); -} - -DCOPRef KonqMainWindowIface::part(int viewNumber) -{ - KonqMainWindow::MapViews viewMap = m_pMainWindow->viewMap(); - KonqMainWindow::MapViews::const_iterator it = viewMap.begin(); - for ( int i = 0; it != viewMap.end() && i < viewNumber; ++i ) - ++it; - if ( it == viewMap.end() ) - return DCOPRef(); - return (*it)->dcopObject()->part(); -} - -DCOPRef KonqMainWindowIface::action( const TQCString &name ) -{ - return DCOPRef( kapp->dcopClient()->appId(), m_dcopActionProxy->actionObjectId( name ) ); -} - -QCStringList KonqMainWindowIface::actions() -{ - QCStringList res; - TQValueList lst = m_dcopActionProxy->actions(); - TQValueList::ConstIterator it = lst.begin(); - TQValueList::ConstIterator end = lst.end(); - for (; it != end; ++it ) - res.append( (*it)->name() ); - - return res; -} - -TQMap KonqMainWindowIface::actionMap() -{ - return m_dcopActionProxy->actionMap(); -} - -QCStringList KonqMainWindowIface::functionsDynamic() -{ - return DCOPObject::functionsDynamic() + KDCOPPropertyProxy::functions( TQT_TQOBJECT(m_pMainWindow) ); -} - -bool KonqMainWindowIface::processDynamic( const TQCString &fun, const TQByteArray &data, TQCString &replyType, TQByteArray &replyData ) -{ - if ( KDCOPPropertyProxy::isPropertyRequest( fun, TQT_TQOBJECT(m_pMainWindow) ) ) - return KDCOPPropertyProxy::processPropertyRequest( fun, data, replyType, replyData, TQT_TQOBJECT(m_pMainWindow) ); - - return DCOPObject::processDynamic( fun, data, replyType, replyData ); -} - -bool KonqMainWindowIface::windowCanBeUsedForTab() -{ - KWin::WindowInfo winfo = KWin::windowInfo( m_pMainWindow->winId(), NET::WMDesktop ); - if( !winfo.isOnCurrentDesktop() ) - return false; // this window shows on different desktop - if( KonqMainWindow::isPreloaded() ) - return false; // we want a tab in an already shown window - return true; -} diff --git a/konqueror/KonqMainWindowIface.cpp b/konqueror/KonqMainWindowIface.cpp new file mode 100644 index 000000000..a18301a2f --- /dev/null +++ b/konqueror/KonqMainWindowIface.cpp @@ -0,0 +1,175 @@ +/* This file is part of the KDE project + Copyright (C) 2000 Simon Hausmann + Copyright (C) 2000 David Faure + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "KonqMainWindowIface.h" +#include "KonqViewIface.h" +#include "konq_view.h" + + +#include +#include +#include +#include +#include +#include +#include + +KonqMainWindowIface::KonqMainWindowIface( KonqMainWindow * mainWindow ) + : + // ARGL I hate this "virtual public DCOPObject" stuff! + DCOPObject( mainWindow->name() ), + TDEMainWindowInterface( mainWindow ), m_pMainWindow( mainWindow ) +{ + m_dcopActionProxy = new KDCOPActionProxy( mainWindow->actionCollection(), this ); +} + +KonqMainWindowIface::~KonqMainWindowIface() +{ + delete m_dcopActionProxy; +} + +void KonqMainWindowIface::openURL( TQString url ) +{ + m_pMainWindow->openFilteredURL( url ); +} + +void KonqMainWindowIface::newTab( TQString url ) +{ + m_pMainWindow->openFilteredURL( url, true ); +} + +void KonqMainWindowIface::openURL( TQString url, bool tempFile ) +{ + m_pMainWindow->openFilteredURL( url, false, tempFile ); +} + +void KonqMainWindowIface::newTab( TQString url, bool tempFile ) +{ + m_pMainWindow->openFilteredURL( url, true, tempFile ); +} + +void KonqMainWindowIface::newTabASN( TQString url, const TQCString& startup_id, bool tempFile ) +{ + TDEStartupInfo::setNewStartupId( m_pMainWindow, startup_id ); + m_pMainWindow->openFilteredURL( url, true, tempFile ); +} + + +void KonqMainWindowIface::splitViewHorizontally() +{ + m_pMainWindow->slotSplitViewHorizontal(); +} + +void KonqMainWindowIface::splitViewVertically() +{ + m_pMainWindow->slotSplitViewVertical(); +} + +void KonqMainWindowIface::reload() +{ + m_pMainWindow->slotReload(); +} + +DCOPRef KonqMainWindowIface::currentView() +{ + KonqView *view = m_pMainWindow->currentView(); + if ( !view ) + return DCOPRef(); + + return DCOPRef( kapp->dcopClient()->appId(), view->dcopObject()->objId() ); +} + +DCOPRef KonqMainWindowIface::currentPart() +{ + DCOPRef res; + + KonqView *view = m_pMainWindow->currentView(); + if ( !view ) + return res; + + return view->dcopObject()->part(); +} + +DCOPRef KonqMainWindowIface::view(int viewNumber) +{ + KonqMainWindow::MapViews viewMap = m_pMainWindow->viewMap(); + KonqMainWindow::MapViews::const_iterator it = viewMap.begin(); + for ( int i = 0; it != viewMap.end() && i < viewNumber; ++i ) + ++it; + if ( it == viewMap.end() ) + return DCOPRef(); + return DCOPRef( kapp->dcopClient()->appId(), (*it)->dcopObject()->objId() ); +} + +DCOPRef KonqMainWindowIface::part(int viewNumber) +{ + KonqMainWindow::MapViews viewMap = m_pMainWindow->viewMap(); + KonqMainWindow::MapViews::const_iterator it = viewMap.begin(); + for ( int i = 0; it != viewMap.end() && i < viewNumber; ++i ) + ++it; + if ( it == viewMap.end() ) + return DCOPRef(); + return (*it)->dcopObject()->part(); +} + +DCOPRef KonqMainWindowIface::action( const TQCString &name ) +{ + return DCOPRef( kapp->dcopClient()->appId(), m_dcopActionProxy->actionObjectId( name ) ); +} + +QCStringList KonqMainWindowIface::actions() +{ + QCStringList res; + TQValueList lst = m_dcopActionProxy->actions(); + TQValueList::ConstIterator it = lst.begin(); + TQValueList::ConstIterator end = lst.end(); + for (; it != end; ++it ) + res.append( (*it)->name() ); + + return res; +} + +TQMap KonqMainWindowIface::actionMap() +{ + return m_dcopActionProxy->actionMap(); +} + +QCStringList KonqMainWindowIface::functionsDynamic() +{ + return DCOPObject::functionsDynamic() + KDCOPPropertyProxy::functions( TQT_TQOBJECT(m_pMainWindow) ); +} + +bool KonqMainWindowIface::processDynamic( const TQCString &fun, const TQByteArray &data, TQCString &replyType, TQByteArray &replyData ) +{ + if ( KDCOPPropertyProxy::isPropertyRequest( fun, TQT_TQOBJECT(m_pMainWindow) ) ) + return KDCOPPropertyProxy::processPropertyRequest( fun, data, replyType, replyData, TQT_TQOBJECT(m_pMainWindow) ); + + return DCOPObject::processDynamic( fun, data, replyType, replyData ); +} + +bool KonqMainWindowIface::windowCanBeUsedForTab() +{ + KWin::WindowInfo winfo = KWin::windowInfo( m_pMainWindow->winId(), NET::WMDesktop ); + if( !winfo.isOnCurrentDesktop() ) + return false; // this window shows on different desktop + if( KonqMainWindow::isPreloaded() ) + return false; // we want a tab in an already shown window + return true; +} diff --git a/konqueror/KonqViewIface.cc b/konqueror/KonqViewIface.cc deleted file mode 100644 index 77bfbb61c..000000000 --- a/konqueror/KonqViewIface.cc +++ /dev/null @@ -1,141 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2000 Simon Hausmann - Copyright (C) 2000 David Faure - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "KonqViewIface.h" -#include "konq_view.h" - -#include -#include -#include - -KonqViewIface::KonqViewIface( KonqView * view, const TQCString& name ) - : DCOPObject( name ), m_pView ( view ) -{ -} - -KonqViewIface::~KonqViewIface() -{ -} - -void KonqViewIface::openURL( TQString url, const TQString & locationBarURL, const TQString & nameFilter ) -{ - KURL u(url); - m_pView->openURL( u, locationBarURL, nameFilter ); -} - -bool KonqViewIface::changeViewMode( const TQString &serviceType, - const TQString &serviceName ) -{ - return m_pView->changeViewMode( serviceType, serviceName ); -} - -void KonqViewIface::lockHistory() - -{ - m_pView->lockHistory(); -} - -void KonqViewIface::stop() -{ - m_pView->stop(); -} - -TQString KonqViewIface::url() -{ - return m_pView->url().url(); -} - -TQString KonqViewIface::locationBarURL() -{ - return m_pView->locationBarURL(); -} - -TQString KonqViewIface::serviceType() -{ - return m_pView->serviceType(); -} - -TQStringList KonqViewIface::serviceTypes() -{ - return m_pView->serviceTypes(); -} - -DCOPRef KonqViewIface::part() -{ - DCOPRef res; - - KParts::ReadOnlyPart *part = m_pView->part(); - - if ( !part ) - return res; - - TQVariant dcopProperty = part->property( "dcopObjectId" ); - - if ( dcopProperty.type() != TQVariant::CString ) - return res; - - res.setRef( kapp->dcopClient()->appId(), dcopProperty.toCString() ); - return res; -} - -void KonqViewIface::enablePopupMenu( bool b ) -{ - m_pView->enablePopupMenu( b ); -} - -uint KonqViewIface::historyLength()const -{ - return m_pView->historyLength(); -} - -bool KonqViewIface::allowHTML() const -{ - return m_pView->allowHTML(); -} - -void KonqViewIface::goForward() -{ - m_pView->go(-1); -} - -void KonqViewIface::goBack() -{ - m_pView->go(+1); -} - -bool KonqViewIface::isPopupMenuEnabled() const -{ - return m_pView->isPopupMenuEnabled(); -} - -bool KonqViewIface::canGoBack()const -{ - return m_pView->canGoBack(); -} - -bool KonqViewIface::canGoForward()const -{ - return m_pView->canGoForward(); -} - -void KonqViewIface::reload() -{ - return m_pView->mainWindow()->slotReload( m_pView ); -} diff --git a/konqueror/KonqViewIface.cpp b/konqueror/KonqViewIface.cpp new file mode 100644 index 000000000..77bfbb61c --- /dev/null +++ b/konqueror/KonqViewIface.cpp @@ -0,0 +1,141 @@ +/* This file is part of the KDE project + Copyright (C) 2000 Simon Hausmann + Copyright (C) 2000 David Faure + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "KonqViewIface.h" +#include "konq_view.h" + +#include +#include +#include + +KonqViewIface::KonqViewIface( KonqView * view, const TQCString& name ) + : DCOPObject( name ), m_pView ( view ) +{ +} + +KonqViewIface::~KonqViewIface() +{ +} + +void KonqViewIface::openURL( TQString url, const TQString & locationBarURL, const TQString & nameFilter ) +{ + KURL u(url); + m_pView->openURL( u, locationBarURL, nameFilter ); +} + +bool KonqViewIface::changeViewMode( const TQString &serviceType, + const TQString &serviceName ) +{ + return m_pView->changeViewMode( serviceType, serviceName ); +} + +void KonqViewIface::lockHistory() + +{ + m_pView->lockHistory(); +} + +void KonqViewIface::stop() +{ + m_pView->stop(); +} + +TQString KonqViewIface::url() +{ + return m_pView->url().url(); +} + +TQString KonqViewIface::locationBarURL() +{ + return m_pView->locationBarURL(); +} + +TQString KonqViewIface::serviceType() +{ + return m_pView->serviceType(); +} + +TQStringList KonqViewIface::serviceTypes() +{ + return m_pView->serviceTypes(); +} + +DCOPRef KonqViewIface::part() +{ + DCOPRef res; + + KParts::ReadOnlyPart *part = m_pView->part(); + + if ( !part ) + return res; + + TQVariant dcopProperty = part->property( "dcopObjectId" ); + + if ( dcopProperty.type() != TQVariant::CString ) + return res; + + res.setRef( kapp->dcopClient()->appId(), dcopProperty.toCString() ); + return res; +} + +void KonqViewIface::enablePopupMenu( bool b ) +{ + m_pView->enablePopupMenu( b ); +} + +uint KonqViewIface::historyLength()const +{ + return m_pView->historyLength(); +} + +bool KonqViewIface::allowHTML() const +{ + return m_pView->allowHTML(); +} + +void KonqViewIface::goForward() +{ + m_pView->go(-1); +} + +void KonqViewIface::goBack() +{ + m_pView->go(+1); +} + +bool KonqViewIface::isPopupMenuEnabled() const +{ + return m_pView->isPopupMenuEnabled(); +} + +bool KonqViewIface::canGoBack()const +{ + return m_pView->canGoBack(); +} + +bool KonqViewIface::canGoForward()const +{ + return m_pView->canGoForward(); +} + +void KonqViewIface::reload() +{ + return m_pView->mainWindow()->slotReload( m_pView ); +} diff --git a/konqueror/KonquerorIface.cc b/konqueror/KonquerorIface.cc deleted file mode 100644 index cd3ed7591..000000000 --- a/konqueror/KonquerorIface.cc +++ /dev/null @@ -1,294 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 1998, 1999 Simon Hausmann - Copyright (C) 2000 David Faure - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "KonquerorIface.h" -#include "konq_misc.h" -#include "KonqMainWindowIface.h" -#include "konq_mainwindow.h" -#include "konq_viewmgr.h" -#include "konq_view.h" -#include -#include -#include -#include -#include -#include "konq_settingsxt.h" - -// these DCOP calls come from outside, so any windows created by these -// calls would have old user timestamps (for KWin's no-focus-stealing), -// it's better to reset the timestamp and rely on other means -// of detecting the time when the user action that triggered all this -// happened -// TODO a valid timestamp should be passed in the DCOP calls that -// are not for user scripting -#include - -KonquerorIface::KonquerorIface() - : DCOPObject( "KonquerorIface" ) -{ -} - -KonquerorIface::~KonquerorIface() -{ -} - -DCOPRef KonquerorIface::openBrowserWindow( const TQString &url ) -{ - SET_QT_X_USER_TIME(0); - KonqMainWindow *res = KonqMisc::createSimpleWindow( KURL(url) ); - if ( !res ) - return DCOPRef(); - return res->dcopObject(); -} - -DCOPRef KonquerorIface::openBrowserWindowASN( const TQString &url, const TQCString& startup_id ) -{ - kapp->setStartupId( startup_id ); - return openBrowserWindow( url ); -} - -DCOPRef KonquerorIface::createNewWindow( const TQString &url ) -{ - return createNewWindow( url, TQString::null, false ); -} - -DCOPRef KonquerorIface::createNewWindowASN( const TQString &url, const TQCString& startup_id, bool tempFile ) -{ - kapp->setStartupId( startup_id ); - return createNewWindow( url, TQString::null, tempFile ); -} - -DCOPRef KonquerorIface::createNewWindowWithSelection( const TQString &url, TQStringList filesToSelect ) -{ - SET_QT_X_USER_TIME(0); - KonqMainWindow *res = KonqMisc::createNewWindow( KURL(url), KParts::URLArgs(), false, filesToSelect ); - if ( !res ) - return DCOPRef(); - return res->dcopObject(); -} - -DCOPRef KonquerorIface::createNewWindowWithSelectionASN( const TQString &url, TQStringList filesToSelect, const TQCString &startup_id ) -{ - kapp->setStartupId( startup_id ); - return createNewWindowWithSelection( url, filesToSelect ); -} - -DCOPRef KonquerorIface::createNewWindow( const TQString &url, const TQString &mimetype, bool tempFile ) -{ - SET_QT_X_USER_TIME(0); - KParts::URLArgs args; - args.serviceType = mimetype; - // Filter the URL, so that "kfmclient openURL gg:foo" works also when konq is already running - KURL finalURL = KonqMisc::konqFilteredURL( 0, url ); - KonqMainWindow *res = KonqMisc::createNewWindow( finalURL, args, false, TQStringList(), tempFile ); - if ( !res ) - return DCOPRef(); - return res->dcopObject(); -} - -DCOPRef KonquerorIface::createNewWindowASN( const TQString &url, const TQString &mimetype, - const TQCString& startup_id, bool tempFile ) -{ - kapp->setStartupId( startup_id ); - return createNewWindow( url, mimetype, tempFile ); -} - -DCOPRef KonquerorIface::createBrowserWindowFromProfile( const TQString &path ) -{ - SET_QT_X_USER_TIME(0); - kdDebug(1202) << "void KonquerorIface::createBrowserWindowFromProfile( const TQString &path ) " << endl; - kdDebug(1202) << path << endl; - KonqMainWindow *res = KonqMisc::createBrowserWindowFromProfile( path, TQString::null ); - if ( !res ) - return DCOPRef(); - return res->dcopObject(); -} - -DCOPRef KonquerorIface::createBrowserWindowFromProfileASN( const TQString &path, const TQCString& startup_id ) -{ - kapp->setStartupId( startup_id ); - return createBrowserWindowFromProfile( path ); -} - -DCOPRef KonquerorIface::createBrowserWindowFromProfile( const TQString & path, const TQString &filename ) -{ - SET_QT_X_USER_TIME(0); - kdDebug(1202) << "void KonquerorIface::createBrowserWindowFromProfile( path, filename ) " << endl; - kdDebug(1202) << path << "," << filename << endl; - KonqMainWindow *res = KonqMisc::createBrowserWindowFromProfile( path, filename ); - if ( !res ) - return DCOPRef(); - return res->dcopObject(); -} - -DCOPRef KonquerorIface::createBrowserWindowFromProfileASN( const TQString &path, const TQString &filename, - const TQCString& startup_id ) -{ - kapp->setStartupId( startup_id ); - return createBrowserWindowFromProfile( path, filename ); -} - -DCOPRef KonquerorIface::createBrowserWindowFromProfileAndURL( const TQString & path, const TQString &filename, const TQString &url ) -{ - SET_QT_X_USER_TIME(0); - KonqMainWindow *res = KonqMisc::createBrowserWindowFromProfile( path, filename, KURL(url) ); - if ( !res ) - return DCOPRef(); - return res->dcopObject(); -} - -DCOPRef KonquerorIface::createBrowserWindowFromProfileAndURLASN( const TQString & path, const TQString &filename, const TQString &url, - const TQCString& startup_id ) -{ - kapp->setStartupId( startup_id ); - return createBrowserWindowFromProfileAndURL( path, filename, url ); -} - -DCOPRef KonquerorIface::createBrowserWindowFromProfileAndURL( const TQString &path, const TQString &filename, const TQString &url, const TQString &mimetype ) -{ - SET_QT_X_USER_TIME(0); - KParts::URLArgs args; - args.serviceType = mimetype; - KonqMainWindow *res = KonqMisc::createBrowserWindowFromProfile( path, filename, KURL(url), args ); - if ( !res ) - return DCOPRef(); - return res->dcopObject(); -} - -DCOPRef KonquerorIface::createBrowserWindowFromProfileAndURLASN( const TQString & path, const TQString &filename, const TQString &url, const TQString &mimetype, - const TQCString& startup_id ) -{ - kapp->setStartupId( startup_id ); - return createBrowserWindowFromProfileAndURL( path, filename, url, mimetype ); -} - - -void KonquerorIface::reparseConfiguration() -{ - TDEGlobal::config()->reparseConfiguration(); - KonqFMSettings::reparseConfiguration(); - - TQPtrList *mainWindows = KonqMainWindow::mainWindowList(); - if ( mainWindows ) - { - TQPtrListIterator it( *mainWindows ); - for (; it.current(); ++it ) - it.current()->reparseConfiguration(); - } -} - -void KonquerorIface::updateProfileList() -{ - TQPtrList *mainWindows = KonqMainWindow::mainWindowList(); - if ( !mainWindows ) - return; - - TQPtrListIterator it( *mainWindows ); - for (; it.current(); ++it ) - it.current()->viewManager()->profileListDirty( false ); -} - -TQString KonquerorIface::crashLogFile() -{ - return KonqMainWindow::s_crashlog_file->name(); -} - -TQValueList KonquerorIface::getWindows() -{ - TQValueList lst; - TQPtrList *mainWindows = KonqMainWindow::mainWindowList(); - if ( mainWindows ) - { - TQPtrListIterator it( *mainWindows ); - for (; it.current(); ++it ) - lst.append( DCOPRef( kapp->dcopClient()->appId(), it.current()->dcopObject()->objId() ) ); - } - return lst; -} - -void KonquerorIface::addToCombo( TQString url, TQCString objId ) -{ - KonqMainWindow::comboAction( KonqMainWindow::ComboAdd, url, objId ); -} - -void KonquerorIface::removeFromCombo( TQString url, TQCString objId ) -{ - KonqMainWindow::comboAction( KonqMainWindow::ComboRemove, url, objId ); -} - -void KonquerorIface::comboCleared( TQCString objId ) -{ - KonqMainWindow::comboAction( KonqMainWindow::ComboClear, - TQString::null, objId ); -} - -bool KonquerorIface::processCanBeReused( int screen ) -{ - if( tqt_xscreen() != screen ) - return false; // this instance run on different screen, and Qt apps can't migrate - if( KonqMainWindow::isPreloaded()) - return false; // will be handled by preloading related code instead - TQPtrList* windows = KonqMainWindow::mainWindowList(); - if( windows == NULL ) - return true; - TQStringList allowed_parts = KonqSettings::safeParts(); - bool all_parts_allowed = false; - - if( allowed_parts.count() == 1 && allowed_parts.first() == TQString::fromLatin1( "SAFE" )) - { - allowed_parts.clear(); - // is duplicated in client/kfmclient.cc - allowed_parts << TQString::fromLatin1( "konq_iconview.desktop" ) - << TQString::fromLatin1( "konq_multicolumnview.desktop" ) - << TQString::fromLatin1( "konq_sidebartng.desktop" ) - << TQString::fromLatin1( "konq_infolistview.desktop" ) - << TQString::fromLatin1( "konq_treeview.desktop" ) - << TQString::fromLatin1( "konq_detailedlistview.desktop" ); - } - else if( allowed_parts.count() == 1 && allowed_parts.first() == TQString::fromLatin1( "ALL" )) - { - allowed_parts.clear(); - all_parts_allowed = true; - } - if( all_parts_allowed ) - return true; - for( TQPtrListIterator it1( *windows ); - it1 != NULL; - ++it1 ) - { - kdDebug(1202) << "processCanBeReused: count=" << (*it1)->viewCount() << endl; - const KonqMainWindow::MapViews& views = (*it1)->viewMap(); - for( KonqMainWindow::MapViews::ConstIterator it2 = views.begin(); - it2 != views.end(); - ++it2 ) - { - kdDebug(1202) << "processCanBeReused: part=" << (*it2)->service()->desktopEntryPath() << ", URL=" << (*it2)->url().prettyURL() << endl; - if( !allowed_parts.contains( (*it2)->service()->desktopEntryPath())) - return false; - } - } - return true; -} - -void KonquerorIface::terminatePreloaded() -{ - if( KonqMainWindow::isPreloaded()) - kapp->exit(); -} diff --git a/konqueror/KonquerorIface.cpp b/konqueror/KonquerorIface.cpp new file mode 100644 index 000000000..6a164b160 --- /dev/null +++ b/konqueror/KonquerorIface.cpp @@ -0,0 +1,294 @@ +/* This file is part of the KDE project + Copyright (C) 1998, 1999 Simon Hausmann + Copyright (C) 2000 David Faure + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "KonquerorIface.h" +#include "konq_misc.h" +#include "KonqMainWindowIface.h" +#include "konq_mainwindow.h" +#include "konq_viewmgr.h" +#include "konq_view.h" +#include +#include +#include +#include +#include +#include "konq_settingsxt.h" + +// these DCOP calls come from outside, so any windows created by these +// calls would have old user timestamps (for KWin's no-focus-stealing), +// it's better to reset the timestamp and rely on other means +// of detecting the time when the user action that triggered all this +// happened +// TODO a valid timestamp should be passed in the DCOP calls that +// are not for user scripting +#include + +KonquerorIface::KonquerorIface() + : DCOPObject( "KonquerorIface" ) +{ +} + +KonquerorIface::~KonquerorIface() +{ +} + +DCOPRef KonquerorIface::openBrowserWindow( const TQString &url ) +{ + SET_QT_X_USER_TIME(0); + KonqMainWindow *res = KonqMisc::createSimpleWindow( KURL(url) ); + if ( !res ) + return DCOPRef(); + return res->dcopObject(); +} + +DCOPRef KonquerorIface::openBrowserWindowASN( const TQString &url, const TQCString& startup_id ) +{ + kapp->setStartupId( startup_id ); + return openBrowserWindow( url ); +} + +DCOPRef KonquerorIface::createNewWindow( const TQString &url ) +{ + return createNewWindow( url, TQString::null, false ); +} + +DCOPRef KonquerorIface::createNewWindowASN( const TQString &url, const TQCString& startup_id, bool tempFile ) +{ + kapp->setStartupId( startup_id ); + return createNewWindow( url, TQString::null, tempFile ); +} + +DCOPRef KonquerorIface::createNewWindowWithSelection( const TQString &url, TQStringList filesToSelect ) +{ + SET_QT_X_USER_TIME(0); + KonqMainWindow *res = KonqMisc::createNewWindow( KURL(url), KParts::URLArgs(), false, filesToSelect ); + if ( !res ) + return DCOPRef(); + return res->dcopObject(); +} + +DCOPRef KonquerorIface::createNewWindowWithSelectionASN( const TQString &url, TQStringList filesToSelect, const TQCString &startup_id ) +{ + kapp->setStartupId( startup_id ); + return createNewWindowWithSelection( url, filesToSelect ); +} + +DCOPRef KonquerorIface::createNewWindow( const TQString &url, const TQString &mimetype, bool tempFile ) +{ + SET_QT_X_USER_TIME(0); + KParts::URLArgs args; + args.serviceType = mimetype; + // Filter the URL, so that "kfmclient openURL gg:foo" works also when konq is already running + KURL finalURL = KonqMisc::konqFilteredURL( 0, url ); + KonqMainWindow *res = KonqMisc::createNewWindow( finalURL, args, false, TQStringList(), tempFile ); + if ( !res ) + return DCOPRef(); + return res->dcopObject(); +} + +DCOPRef KonquerorIface::createNewWindowASN( const TQString &url, const TQString &mimetype, + const TQCString& startup_id, bool tempFile ) +{ + kapp->setStartupId( startup_id ); + return createNewWindow( url, mimetype, tempFile ); +} + +DCOPRef KonquerorIface::createBrowserWindowFromProfile( const TQString &path ) +{ + SET_QT_X_USER_TIME(0); + kdDebug(1202) << "void KonquerorIface::createBrowserWindowFromProfile( const TQString &path ) " << endl; + kdDebug(1202) << path << endl; + KonqMainWindow *res = KonqMisc::createBrowserWindowFromProfile( path, TQString::null ); + if ( !res ) + return DCOPRef(); + return res->dcopObject(); +} + +DCOPRef KonquerorIface::createBrowserWindowFromProfileASN( const TQString &path, const TQCString& startup_id ) +{ + kapp->setStartupId( startup_id ); + return createBrowserWindowFromProfile( path ); +} + +DCOPRef KonquerorIface::createBrowserWindowFromProfile( const TQString & path, const TQString &filename ) +{ + SET_QT_X_USER_TIME(0); + kdDebug(1202) << "void KonquerorIface::createBrowserWindowFromProfile( path, filename ) " << endl; + kdDebug(1202) << path << "," << filename << endl; + KonqMainWindow *res = KonqMisc::createBrowserWindowFromProfile( path, filename ); + if ( !res ) + return DCOPRef(); + return res->dcopObject(); +} + +DCOPRef KonquerorIface::createBrowserWindowFromProfileASN( const TQString &path, const TQString &filename, + const TQCString& startup_id ) +{ + kapp->setStartupId( startup_id ); + return createBrowserWindowFromProfile( path, filename ); +} + +DCOPRef KonquerorIface::createBrowserWindowFromProfileAndURL( const TQString & path, const TQString &filename, const TQString &url ) +{ + SET_QT_X_USER_TIME(0); + KonqMainWindow *res = KonqMisc::createBrowserWindowFromProfile( path, filename, KURL(url) ); + if ( !res ) + return DCOPRef(); + return res->dcopObject(); +} + +DCOPRef KonquerorIface::createBrowserWindowFromProfileAndURLASN( const TQString & path, const TQString &filename, const TQString &url, + const TQCString& startup_id ) +{ + kapp->setStartupId( startup_id ); + return createBrowserWindowFromProfileAndURL( path, filename, url ); +} + +DCOPRef KonquerorIface::createBrowserWindowFromProfileAndURL( const TQString &path, const TQString &filename, const TQString &url, const TQString &mimetype ) +{ + SET_QT_X_USER_TIME(0); + KParts::URLArgs args; + args.serviceType = mimetype; + KonqMainWindow *res = KonqMisc::createBrowserWindowFromProfile( path, filename, KURL(url), args ); + if ( !res ) + return DCOPRef(); + return res->dcopObject(); +} + +DCOPRef KonquerorIface::createBrowserWindowFromProfileAndURLASN( const TQString & path, const TQString &filename, const TQString &url, const TQString &mimetype, + const TQCString& startup_id ) +{ + kapp->setStartupId( startup_id ); + return createBrowserWindowFromProfileAndURL( path, filename, url, mimetype ); +} + + +void KonquerorIface::reparseConfiguration() +{ + TDEGlobal::config()->reparseConfiguration(); + KonqFMSettings::reparseConfiguration(); + + TQPtrList *mainWindows = KonqMainWindow::mainWindowList(); + if ( mainWindows ) + { + TQPtrListIterator it( *mainWindows ); + for (; it.current(); ++it ) + it.current()->reparseConfiguration(); + } +} + +void KonquerorIface::updateProfileList() +{ + TQPtrList *mainWindows = KonqMainWindow::mainWindowList(); + if ( !mainWindows ) + return; + + TQPtrListIterator it( *mainWindows ); + for (; it.current(); ++it ) + it.current()->viewManager()->profileListDirty( false ); +} + +TQString KonquerorIface::crashLogFile() +{ + return KonqMainWindow::s_crashlog_file->name(); +} + +TQValueList KonquerorIface::getWindows() +{ + TQValueList lst; + TQPtrList *mainWindows = KonqMainWindow::mainWindowList(); + if ( mainWindows ) + { + TQPtrListIterator it( *mainWindows ); + for (; it.current(); ++it ) + lst.append( DCOPRef( kapp->dcopClient()->appId(), it.current()->dcopObject()->objId() ) ); + } + return lst; +} + +void KonquerorIface::addToCombo( TQString url, TQCString objId ) +{ + KonqMainWindow::comboAction( KonqMainWindow::ComboAdd, url, objId ); +} + +void KonquerorIface::removeFromCombo( TQString url, TQCString objId ) +{ + KonqMainWindow::comboAction( KonqMainWindow::ComboRemove, url, objId ); +} + +void KonquerorIface::comboCleared( TQCString objId ) +{ + KonqMainWindow::comboAction( KonqMainWindow::ComboClear, + TQString::null, objId ); +} + +bool KonquerorIface::processCanBeReused( int screen ) +{ + if( tqt_xscreen() != screen ) + return false; // this instance run on different screen, and Qt apps can't migrate + if( KonqMainWindow::isPreloaded()) + return false; // will be handled by preloading related code instead + TQPtrList* windows = KonqMainWindow::mainWindowList(); + if( windows == NULL ) + return true; + TQStringList allowed_parts = KonqSettings::safeParts(); + bool all_parts_allowed = false; + + if( allowed_parts.count() == 1 && allowed_parts.first() == TQString::fromLatin1( "SAFE" )) + { + allowed_parts.clear(); + // is duplicated in client/kfmclient.cpp + allowed_parts << TQString::fromLatin1( "konq_iconview.desktop" ) + << TQString::fromLatin1( "konq_multicolumnview.desktop" ) + << TQString::fromLatin1( "konq_sidebartng.desktop" ) + << TQString::fromLatin1( "konq_infolistview.desktop" ) + << TQString::fromLatin1( "konq_treeview.desktop" ) + << TQString::fromLatin1( "konq_detailedlistview.desktop" ); + } + else if( allowed_parts.count() == 1 && allowed_parts.first() == TQString::fromLatin1( "ALL" )) + { + allowed_parts.clear(); + all_parts_allowed = true; + } + if( all_parts_allowed ) + return true; + for( TQPtrListIterator it1( *windows ); + it1 != NULL; + ++it1 ) + { + kdDebug(1202) << "processCanBeReused: count=" << (*it1)->viewCount() << endl; + const KonqMainWindow::MapViews& views = (*it1)->viewMap(); + for( KonqMainWindow::MapViews::ConstIterator it2 = views.begin(); + it2 != views.end(); + ++it2 ) + { + kdDebug(1202) << "processCanBeReused: part=" << (*it2)->service()->desktopEntryPath() << ", URL=" << (*it2)->url().prettyURL() << endl; + if( !allowed_parts.contains( (*it2)->service()->desktopEntryPath())) + return false; + } + } + return true; +} + +void KonquerorIface::terminatePreloaded() +{ + if( KonqMainWindow::isPreloaded()) + kapp->exit(); +} diff --git a/konqueror/Makefile.am b/konqueror/Makefile.am index e84ddffcf..a81cabe84 100644 --- a/konqueror/Makefile.am +++ b/konqueror/Makefile.am @@ -22,23 +22,23 @@ METASOURCES = AUTO include_HEADERS = KonquerorIface.h libkonqueror_intern_la_SOURCES = konq_settingsxt.kcfgc -konqueror_la_SOURCES = konq_main.cc \ - KonquerorIface.cc KonquerorIface.skel \ - KonqMainWindowIface.cc KonqMainWindowIface.skel \ - KonqViewIface.cc KonqViewIface.skel \ - konq_guiclients.cc \ - konq_run.cc konq_view.cc konq_viewmgr.cc \ - konq_misc.cc \ - konq_frame.cc \ - konq_tabs.cc \ - konq_actions.cc \ - konq_profiledlg.cc \ - konq_factory.cc \ - konq_combo.cc \ - konq_browseriface.cc \ - delayedinitializer.cc \ - konq_mainwindow.cc \ - konq_extensionmanager.cc +konqueror_la_SOURCES = konq_main.cpp \ + KonquerorIface.cpp KonquerorIface.skel \ + KonqMainWindowIface.cpp KonqMainWindowIface.skel \ + KonqViewIface.cpp KonqViewIface.skel \ + konq_guiclients.cpp \ + konq_run.cpp konq_view.cpp konq_viewmgr.cpp \ + konq_misc.cpp \ + konq_frame.cpp \ + konq_tabs.cpp \ + konq_actions.cpp \ + konq_profiledlg.cpp \ + konq_factory.cpp \ + konq_combo.cpp \ + konq_browseriface.cpp \ + delayedinitializer.cpp \ + konq_mainwindow.cpp \ + konq_extensionmanager.cpp konqueror_la_PCH = AUTO @@ -59,14 +59,14 @@ konqueror_la_LIBADD = ../libkonq/libkonq.la libkonqueror_intern.la $(LIBMALLOC) # and make clean ; make konqueror_static in here. #check_PROGRAMS = konqueror_static # -#konqueror_static_SOURCES = dummy.cc +#konqueror_static_SOURCES = dummy.cpp #konqueror_static_LDADD = konqueror.la *view/*.la dirtree/*.la $(libdir)/libtdehtml.la #konqueror_static_LDFLAGS = $(all_libraries) -static messages: rc.cpp $(EXTRACTRC) *.rc */*.rc >> rc.cpp $(EXTRACTRC) sidebar/trees/history_module/history_dlg.ui >> rc.cpp - $(XGETTEXT) -kaliasLocal rc.cpp *.h *.cc *view/*h *view/*cc kedit*/*.h kedit*/*.cpp about/*.h about/*.cc remoteencodingplugin/*.cpp remoteencodingplugin/*.h shellcmdplugin/*.cpp -o `find sidebar -name "*.cpp"` `find sidebar -name "*.h"` -o $(podir)/konqueror.pot + $(XGETTEXT) -kaliasLocal rc.cpp *.h *.cpp *view/*h *view/*.cpp kedit*/*.h kedit*/*.cpp about/*.h about/*.cpp remoteencodingplugin/*.cpp remoteencodingplugin/*.h shellcmdplugin/*.cpp -o `find sidebar -name "*.cpp"` `find sidebar -name "*.h"` -o $(podir)/konqueror.pot xdg_apps_DATA = kfmclient.desktop kfmclient_dir.desktop kfmclient_html.desktop \ kfmclient_war.desktop konqbrowser.desktop konquerorsu.desktop Home.desktop diff --git a/konqueror/about/CMakeLists.txt b/konqueror/about/CMakeLists.txt index 9d77c04be..ffa5d4b96 100644 --- a/konqueror/about/CMakeLists.txt +++ b/konqueror/about/CMakeLists.txt @@ -47,7 +47,7 @@ install( FILES set( target konq_aboutpage ) tde_add_kpart( ${target} AUTOMOC - SOURCES konq_aboutpage.cc + SOURCES konq_aboutpage.cpp LINK tdehtml-shared DESTINATION ${PLUGIN_INSTALL_DIR} ) diff --git a/konqueror/about/Makefile.am b/konqueror/about/Makefile.am index 0a33f9bb7..f4ede2182 100644 --- a/konqueror/about/Makefile.am +++ b/konqueror/about/Makefile.am @@ -1,7 +1,7 @@ kde_module_LTLIBRARIES = konq_aboutpage.la INCLUDES = -I$(srcdir)/.. -I$(top_srcdir)/libkonq $(all_includes) -konq_aboutpage_la_SOURCES = konq_aboutpage.cc +konq_aboutpage_la_SOURCES = konq_aboutpage.cpp konq_aboutpage_la_LDFLAGS = $(all_libraries) $(KDE_PLUGIN) -module konq_aboutpage_la_LIBADD = $(LIB_TDEHTML) diff --git a/konqueror/about/konq_aboutpage.cc b/konqueror/about/konq_aboutpage.cc deleted file mode 100644 index cb2149f90..000000000 --- a/konqueror/about/konq_aboutpage.cc +++ /dev/null @@ -1,558 +0,0 @@ -#include "konq_aboutpage.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -K_EXPORT_COMPONENT_FACTORY( konq_aboutpage, KonqAboutPageFactory ) - -TDEInstance *KonqAboutPageFactory::s_instance = 0; -TQString *KonqAboutPageFactory::s_launch_html = 0; -TQString *KonqAboutPageFactory::s_intro_html = 0; -TQString *KonqAboutPageFactory::s_specs_html = 0; -TQString *KonqAboutPageFactory::s_tips_html = 0; -TQString *KonqAboutPageFactory::s_plugins_html = 0; - -KonqAboutPageFactory::KonqAboutPageFactory( TQObject *parent, const char *name ) - : KParts::Factory( parent, name ) -{ - s_instance = new TDEInstance( "konqaboutpage" ); -} - -KonqAboutPageFactory::~KonqAboutPageFactory() -{ - delete s_instance; - s_instance = 0; - delete s_launch_html; - s_launch_html = 0; - delete s_intro_html; - s_intro_html = 0; - delete s_specs_html; - s_specs_html = 0; - delete s_tips_html; - s_tips_html = 0; - delete s_plugins_html; - s_plugins_html = 0; -} - -KParts::Part *KonqAboutPageFactory::createPartObject( TQWidget *parentWidget, const char *widgetName, - TQObject *parent, const char *name, - const char *, const TQStringList & ) -{ - //KonqFrame *frame = tqt_dynamic_cast( parentWidget ); - //if ( !frame ) return 0; - - return new KonqAboutPage( //frame->childView()->mainWindow(), - parentWidget, widgetName, parent, name ); -} - -TQString KonqAboutPageFactory::loadFile( const TQString& file ) -{ - TQString res; - if ( file.isEmpty() ) - return res; - - TQFile f( file ); - - if ( !f.open( IO_ReadOnly ) ) - return res; - - TQTextStream t( &f ); - - res = t.read(); - - // otherwise all embedded objects are referenced as about:/... - TQString basehref = TQString::fromLatin1("\n"); - TQRegExp reg(""); - reg.setCaseSensitive(FALSE); - res.replace(reg, "\n\t" + basehref); - return res; -} - -TQString KonqAboutPageFactory::launch() -{ - // FIXME: only regenerate launch page if kuriikwsfilterrc changed. - /* - if ( s_launch_html ) - return *s_launch_html; - */ - - TQString res = loadFile( locate( "data", "konqueror/about/launch.html" )); - if ( res.isEmpty() ) - return res; - - TDEIconLoader *iconloader = TDEGlobal::iconLoader(); - int iconSize = iconloader->currentSize(TDEIcon::Desktop); - TQString home_icon_path = iconloader->iconPath("kfm_home", TDEIcon::Desktop ); - TQString storage_icon_path = iconloader->iconPath("computer", TDEIcon::Desktop ); - TQString remote_icon_path = iconloader->iconPath("network", TDEIcon::Desktop ); - TQString wastebin_icon_path = iconloader->iconPath("trashcan_full", TDEIcon::Desktop ); - TQString applications_icon_path = iconloader->iconPath("kmenu", TDEIcon::Desktop ); - TQString settings_icon_path = iconloader->iconPath("kcontrol", TDEIcon::Desktop ); - TQString help_icon_path = iconloader->iconPath("khelpcenter", TDEIcon::Desktop ); - TQString home_folder = TQDir::homeDirPath(); - TQString continue_icon_path = TQApplication::reverseLayout()?iconloader->iconPath("1leftarrow", TDEIcon::Small ):iconloader->iconPath("1rightarrow", TDEIcon::Small ); - - res = res.arg( locate( "data", "tdeui/about/kde_infopage.css" ) ); - if ( kapp->reverseLayout() ) - res = res.arg( "@import \"%1\";" ).arg( locate( "data", "tdeui/about/kde_infopage_rtl.css" ) ); - else - res = res.arg( "" ); - - // Try to split page in three. If it succeeds, insert the default search into the middle part. - TQStringList parts = TQStringList::split( "", res ); - if ( parts.count() == 3 ) { - TDEConfig config( "kuriikwsfilterrc", true /*read-only*/, false /*no KDE globals*/ ); - config.setGroup( "General" ); - TQString name = config.readEntry("DefaultSearchEngine"); - KService::Ptr service = - KService::serviceByDesktopPath(TQString("searchproviders/%1.desktop").arg(name)); - if ( service ) { - TQString searchBar = parts[1]; - searchBar = searchBar - .arg( iconSize ).arg( iconSize ) - .arg( service->name() ) - .arg( service->property("Keys").toStringList()[0] ) - ; - res = parts[0] + searchBar + parts[2]; - } - else res = parts[0] + parts[2]; - } - - res = res.arg( i18n("Conquer your Desktop!") ) - .arg( i18n( "Konqueror" ) ) - .arg( i18n("Conquer your Desktop!") ) - .arg( i18n("Konqueror is your file manager, web browser and universal document viewer.") ) - .arg( i18n( "Starting Points" ) ) - .arg( i18n( "Introduction" ) ) - .arg( i18n( "Tips" ) ) - .arg( i18n( "Specifications" ) ) - .arg( home_folder ) - .arg( home_icon_path ) - .arg(iconSize).arg(iconSize) - .arg( home_folder ) - .arg( i18n( "Home Folder" ) ) - .arg( i18n( "Your personal files" ) ) - .arg( storage_icon_path ) - .arg(iconSize).arg(iconSize) - .arg( i18n( "Storage Media" ) ) - .arg( i18n( "Disks and removable media" ) ) - .arg( remote_icon_path ) - .arg(iconSize).arg(iconSize) - .arg( i18n( "Network Folders" ) ) - .arg( i18n( "Shared files and folders" ) ) - .arg( wastebin_icon_path ) - .arg(iconSize).arg(iconSize) - .arg( i18n( "Trash" ) ) - .arg( i18n( "Browse and restore the trash" ) ) - .arg( applications_icon_path ) - .arg(iconSize).arg(iconSize) - .arg( i18n( "Applications" ) ) - .arg( i18n( "Installed programs" ) ) - .arg( settings_icon_path ) - .arg(iconSize).arg(iconSize) - .arg( i18n( "Settings" ) ) - .arg( i18n( "Desktop configuration" ) ) - .arg( continue_icon_path ) - .arg( TDEIcon::SizeSmall ).arg( TDEIcon::SizeSmall ) - .arg( i18n( "Next: An Introduction to Konqueror" ) ) - ; - i18n("Search the Web");//i18n for possible future use - - s_launch_html = new TQString( res ); - - return res; -} - -TQString KonqAboutPageFactory::intro() -{ - if ( s_intro_html ) - return *s_intro_html; - - TQString res = loadFile( locate( "data", "konqueror/about/intro.html" )); - if ( res.isEmpty() ) - return res; - - TDEIconLoader *iconloader = TDEGlobal::iconLoader(); - TQString back_icon_path = TQApplication::reverseLayout()?iconloader->iconPath("forward", TDEIcon::Small ):iconloader->iconPath("back", TDEIcon::Small ); - TQString gohome_icon_path = iconloader->iconPath("go-home", TDEIcon::Small ); - TQString continue_icon_path = TQApplication::reverseLayout()?iconloader->iconPath("1leftarrow", TDEIcon::Small ):iconloader->iconPath("1rightarrow", TDEIcon::Small ); - - res = res.arg( locate( "data", "tdeui/about/kde_infopage.css" ) ); - if ( kapp->reverseLayout() ) - res = res.arg( "@import \"%1\";" ).arg( locate( "data", "tdeui/about/kde_infopage_rtl.css" ) ); - else - res = res.arg( "" ); - - res = res.arg( i18n("Conquer your Desktop!") ) - .arg( i18n( "Konqueror" ) ) - .arg( i18n( "Conquer your Desktop!") ) - .arg( i18n( "Konqueror is your file manager, web browser and universal document viewer.") ) - .arg( i18n( "Starting Points" ) ) - .arg( i18n( "Introduction" ) ) - .arg( i18n( "Tips" ) ) - .arg( i18n( "Specifications" ) ) - .arg( i18n( "Konqueror makes working with and managing your files easy. You can browse " - "both local and networked folders while enjoying advanced features " - "such as the powerful sidebar and file previews." - ) ) - .arg( i18n( "Konqueror is also a full featured and easy to use web browser which you " - "can use to explore the Internet. " - "Enter the address (e.g. http://www.trinitydesktop.org) " - "of a web page you would like to visit in the location bar and press Enter, " - "or choose an entry from the Bookmarks menu.") ) - .arg( i18n( "To return to the previous " - "location, press the back button " - "in the toolbar. ").arg( back_icon_path ) ) - .arg( i18n( "To quickly go to your Home folder press the " - " home button ." ).arg(gohome_icon_path) ) - .arg( i18n( "For more detailed documentation on Konqueror click here." ) - .arg("exec:/khelpcenter") ) - .arg( i18n( "Tuning Tip: If you want the Konqueror web browser to start faster," - " you can turn off this information screen by clicking here. You can re-enable it" - " by choosing the Help -> Konqueror Introduction menu option, and then pressing " - "Settings -> Save View Profile \"Web Browsing\".").arg("config:/disable_overview") ) - .arg( "" ).arg( continue_icon_path ) - .arg( i18n( "Next: Tips & Tricks" ) ) - ; - - - s_intro_html = new TQString( res ); - - return res; -} - -TQString KonqAboutPageFactory::specs() -{ - if ( s_specs_html ) - return *s_specs_html; - - TDEIconLoader *iconloader = TDEGlobal::iconLoader(); - TQString res = loadFile( locate( "data", "konqueror/about/specs.html" )); - TQString continue_icon_path = TQApplication::reverseLayout()?iconloader->iconPath("1leftarrow", TDEIcon::Small ):iconloader->iconPath("1rightarrow", TDEIcon::Small ); - if ( res.isEmpty() ) - return res; - - res = res.arg( locate( "data", "tdeui/about/kde_infopage.css" ) ); - if ( kapp->reverseLayout() ) - res = res.arg( "@import \"%1\";" ).arg( locate( "data", "tdeui/about/kde_infopage_rtl.css" ) ); - else - res = res.arg( "" ); - - res = res.arg( i18n("Conquer your Desktop!") ) - .arg( i18n( "Konqueror" ) ) - .arg( i18n("Conquer your Desktop!") ) - .arg( i18n("Konqueror is your file manager, web browser and universal document viewer.") ) - .arg( i18n( "Starting Points" ) ) - .arg( i18n( "Introduction" ) ) - .arg( i18n( "Tips" ) ) - .arg( i18n( "Specifications" ) ) - .arg( i18n("Specifications") ) - .arg( i18n("Konqueror is designed to embrace and support Internet standards. " - "The aim is to fully implement the officially sanctioned standards " - "from organizations such as the W3 and OASIS, while also adding " - "extra support for other common usability features that arise as " - "de facto standards across the Internet. Along with this support, " - "for such functions as favicons, Internet Keywords, and XBEL bookmarks, " - "Konqueror also implements:").arg("http://pyxml.sourceforge.net/topics/xbel/") ) - .arg( i18n("Web Browsing") ) - .arg( i18n("Supported standards") ) - .arg( i18n("Additional requirements*") ) - .arg( i18n("DOM (Level 1, partially Level 2) based " - "HTML 4.01").arg("http://www.w3.org/DOM").arg("http://www.w3.org/TR/html4/") ) - .arg( i18n("built-in") ) - .arg( i18n("Cascading Style Sheets (CSS 1, partially CSS 2)").arg("http://www.w3.org/Style/CSS/") ) - .arg( i18n("built-in") ) - .arg( i18n("ECMA-262 Edition 3 (roughly equals JavaScript 1.5)").arg("http://www.ecma.ch/ecma1/STAND/ECMA-262.HTM") ) - .arg( i18n("JavaScript disabled (globally). Enable JavaScript here.").arg("exec:/tdecmshell tdehtml_java_js") ) - .arg( i18n("JavaScript enabled (globally). Configure JavaScript here.").arg("exec:/tdecmshell tdehtml_java_js") ) // leave the double backslashes here, they are necessary for javascript ! - .arg( i18n("Secure Java® support").arg("http://java.sun.com") ) - .arg( i18n("JDK 1.2.0 (Java 2) compatible VM (Blackdown, IBM or Sun)") - .arg("http://www.blackdown.org").arg("http://www.ibm.com").arg("http://java.sun.com") ) - .arg( i18n("Enable Java (globally) here.").arg("exec:/tdecmshell tdehtml_java_js") ) // TODO Maybe test if Java is enabled ? - .arg( i18n("Netscape Communicator® plugins (for viewing Flash®, Real®Audio, Real®Video, etc.)") - .arg("http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash") - .arg("http://www.real.com").arg("http://www.real.com") - .arg("about:plugins") ) - .arg( i18n("built-in") ) - .arg( i18n("Secure Sockets Layer") ) - .arg( i18n("(TLS/SSL v2/3) for secure communications up to 168bit") ) - .arg( i18n("OpenSSL") ) - .arg( i18n("Bidirectional 16bit unicode support") ) - .arg( i18n("built-in") ) - .arg( i18n("AutoCompletion for forms") ) - .arg( i18n("built-in") ) - .arg( i18n("G E N E R A L") ) - .arg( i18n("Feature") ) - .arg( i18n("Details") ) - .arg( i18n("Image formats") ) - .arg( i18n("Transfer protocols") ) - .arg( i18n("HTTP 1.1 (including gzip/bzip2 compression)") ) - .arg( i18n("FTP") ) - .arg( i18n("and many more...").arg("exec:/tdecmshell ioslaveinfo") ) - .arg( i18n("URL-Completion") ) - .arg( i18n("Manual")) - .arg( i18n("Popup")) - .arg( i18n("(Short-) Automatic")) - .arg( "" ).arg( continue_icon_path ) - .arg( i18n("Return to Starting Points").arg("launch.html") ) - - ; - - s_specs_html = new TQString( res ); - - return res; -} - -TQString KonqAboutPageFactory::tips() -{ - if ( s_tips_html ) - return *s_tips_html; - - TQString res = loadFile( locate( "data", "konqueror/about/tips.html" )); - if ( res.isEmpty() ) - return res; - - TDEIconLoader *iconloader = TDEGlobal::iconLoader(); - TQString viewmag_icon_path = - iconloader->iconPath("viewmag", TDEIcon::Small ); - TQString history_icon_path = - iconloader->iconPath("history", TDEIcon::Small ); - TQString openterm_icon_path = - iconloader->iconPath("openterm", TDEIcon::Small ); - TQString locationbar_erase_rtl_icon_path = - iconloader->iconPath("clear_left", TDEIcon::Small ); - TQString locationbar_erase_icon_path = - iconloader->iconPath("locationbar_erase", TDEIcon::Small ); - TQString window_fullscreen_icon_path = - iconloader->iconPath("view-fullscreen", TDEIcon::Small ); - TQString view_left_right_icon_path = - iconloader->iconPath("view_left_right", TDEIcon::Small ); - TQString continue_icon_path = TQApplication::reverseLayout()?iconloader->iconPath("1leftarrow", TDEIcon::Small ):iconloader->iconPath("1rightarrow", TDEIcon::Small ); - - res = res.arg( locate( "data", "tdeui/about/kde_infopage.css" ) ); - if ( kapp->reverseLayout() ) - res = res.arg( "@import \"%1\";" ).arg( locate( "data", "tdeui/about/kde_infopage_rtl.css" ) ); - else - res = res.arg( "" ); - - res = res.arg( i18n("Conquer your Desktop!") ) - .arg( i18n( "Konqueror" ) ) - .arg( i18n("Conquer your Desktop!") ) - .arg( i18n("Konqueror is your file manager, web browser and universal document viewer.") ) - .arg( i18n( "Starting Points" ) ) - .arg( i18n( "Introduction" ) ) - .arg( i18n( "Tips" ) ) - .arg( i18n( "Specifications" ) ) - .arg( i18n( "Tips & Tricks" ) ) - .arg( i18n( "Use Internet-Keywords and Web-Shortcuts: by typing \"gg: Trinity Desktop\" one can search the Internet, " - "using Google, for the search phrase \"Trinity Desktop\". There are a lot of " - "Web-Shortcuts predefined to make searching for software or looking " - "up certain words in an encyclopedia a breeze. You can even " - "create your own Web-Shortcuts." ).arg("exec:/tdecmshell ebrowsing") ) - .arg( i18n( "Use the magnifier button in the" - " toolbar to increase the font size on your web page.").arg(viewmag_icon_path) ) - .arg( i18n( "When you want to paste a new address into the Location toolbar you might want to " - "clear the current entry by pressing the black arrow with the white cross " - " in the toolbar.") - .arg(TQApplication::reverseLayout() ? locationbar_erase_rtl_icon_path : locationbar_erase_icon_path)) - .arg( i18n( "To create a link on your desktop pointing to the current page, " - "simply drag the \"Location\" label that is to the left of the Location toolbar, drop it on to " - "the desktop, and choose \"Link\"." ) ) - .arg( i18n( "You can also find \"Full-Screen Mode\" " - "in the Settings menu. This feature is very useful for \"Talk\" " - "sessions.").arg(window_fullscreen_icon_path) ) - .arg( i18n( "Divide et impera (lat. \"Divide and conquer\") - by splitting a window " - "into two parts (e.g. Window -> Split View " - "Left/Right) you can make Konqueror appear the way you like. You" - " can even load some example view-profiles (e.g. Midnight Commander)" - ", or create your own ones." ).arg(view_left_right_icon_path)) - .arg( i18n( "Use the user-agent feature if the website you are visiting " - "asks you to use a different browser " - "(and do not forget to send a complaint to the webmaster!)" ).arg("exec:/tdecmshell useragent") ) - .arg( i18n( "The History in your SideBar ensures " - "that you can keep track of the pages you have visited recently.").arg(history_icon_path) ) - .arg( i18n( "Use a caching proxy to speed up your" - " Internet connection.").arg("exec:/tdecmshell proxy") ) - .arg( i18n( "Advanced users will appreciate the Konsole which you can embed into " - "Konqueror (Window -> Show " - "Terminal Emulator).").arg(openterm_icon_path)) - .arg( i18n( "Thanks to DCOP you can have full control over Konqueror using a script." -).arg("exec:/kdcop") ) - .arg( i18n( "" ).arg( continue_icon_path ) ) - .arg( i18n( "Next: Specifications" ) ) - ; - - - s_tips_html = new TQString( res ); - - return res; -} - - -TQString KonqAboutPageFactory::plugins() -{ - if ( s_plugins_html ) - return *s_plugins_html; - - TQString res = loadFile( locate( "data", kapp->reverseLayout() ? "konqueror/about/plugins_rtl.html" : "konqueror/about/plugins.html" )) - .arg(i18n("Installed Plugins")) - .arg(i18n("PluginDescriptionFileTypes")) - .arg(i18n("Installed")) - .arg(i18n("Mime TypeDescriptionSuffixesPlugin")); - if ( res.isEmpty() ) - return res; - - s_plugins_html = new TQString( res ); - - return res; -} - - -KonqAboutPage::KonqAboutPage( //KonqMainWindow * - TQWidget *parentWidget, const char *widgetName, - TQObject *parent, const char *name ) - : TDEHTMLPart( parentWidget, widgetName, parent, name, BrowserViewGUI ) -{ - //m_mainWindow = mainWindow; - TQTextCodec* codec = TDEGlobal::locale()->codecForEncoding(); - if (codec) - setCharset(codec->name(), true); - else - setCharset("iso-8859-1", true); - // about:blah isn't a tdeioslave -> disable View source - TDEAction * act = actionCollection()->action("viewDocumentSource"); - if ( act ) - act->setEnabled( false ); -} - -KonqAboutPage::~KonqAboutPage() -{ -} - -bool KonqAboutPage::openURL( const KURL &u ) -{ - kdDebug(1202) << "now in KonqAboutPage::openURL( \"" << u.url() << "\" )" << endl; - if ( u.url() == "about:plugins" ) - serve( KonqAboutPageFactory::plugins(), "plugins" ); - else if ( !u.query().isEmpty() ) { - TQMap< TQString, TQString > queryItems = u.queryItems( 0 ); - TQMap< TQString, TQString >::ConstIterator query = queryItems.begin(); - TQString newUrl; - if (query.key() == "strigi") { - newUrl = KURIFilter::self()->filteredURI( query.key() + ":?q=" + query.data() ); - } else { - newUrl = KURIFilter::self()->filteredURI( query.key() + ":" + query.data() ); - } - kdDebug(1202) << "scheduleRedirection( 0, \"" << newUrl << "\" )" << endl; - scheduleRedirection( 0, newUrl ); - } - else serve( KonqAboutPageFactory::launch(), "konqueror" ); - return true; -} - -bool KonqAboutPage::openFile() -{ - return true; -} - -void KonqAboutPage::saveState( TQDataStream &stream ) -{ - stream << m_htmlDoc; - stream << m_what; -} - -void KonqAboutPage::restoreState( TQDataStream &stream ) -{ - stream >> m_htmlDoc; - stream >> m_what; - serve( m_htmlDoc, m_what ); -} - -void KonqAboutPage::serve( const TQString& html, const TQString& what ) -{ - m_what = what; - begin( KURL( TQString("about:%1").arg(what) ) ); - write( html ); - end(); - m_htmlDoc = html; -} - -void KonqAboutPage::urlSelected( const TQString &url, int button, int state, const TQString &target, KParts::URLArgs _args ) -{ - KURL u( url ); - if ( u.protocol() == "exec" ) - { - TQStringList args = TQStringList::split( TQChar( ' ' ), url.mid( 6 ) ); - TQString executable = args[ 0 ]; - args.remove( args.begin() ); - TDEApplication::tdeinitExec( executable, args ); - return; - } - - if ( url == TQString::fromLatin1("launch.html") ) - { - emit browserExtension()->openURLNotify(); - serve( KonqAboutPageFactory::launch(), "konqueror" ); - return; - } - else if ( url == TQString::fromLatin1("intro.html") ) - { - emit browserExtension()->openURLNotify(); - serve( KonqAboutPageFactory::intro(), "konqueror" ); - return; - } - else if ( url == TQString::fromLatin1("specs.html") ) - { - emit browserExtension()->openURLNotify(); - serve( KonqAboutPageFactory::specs(), "konqueror" ); - return; - } - else if ( url == TQString::fromLatin1("tips.html") ) - { - emit browserExtension()->openURLNotify(); - serve( KonqAboutPageFactory::tips(), "konqueror" ); - return; - } - - else if ( url == TQString::fromLatin1("config:/disable_overview") ) - { - if ( KMessageBox::questionYesNo( widget(), - i18n("Do you want to disable showing " - "the introduction in the webbrowsing profile?"), - i18n("Faster Startup?"),i18n("Disable"),i18n("Keep") ) - == KMessageBox::Yes ) - { - TQString profile = locateLocal("data", "konqueror/profiles/webbrowsing"); - KSaveFile file( profile ); - if ( file.status() == 0 ) { - TQCString content = "[Profile]\n" - "Name=Web-Browser"; - fputs( content.data(), file.fstream() ); - file.close(); - } - } - return; - } - - TDEHTMLPart::urlSelected( url, button, state, target, _args ); -} - -#include "konq_aboutpage.moc" diff --git a/konqueror/about/konq_aboutpage.cpp b/konqueror/about/konq_aboutpage.cpp new file mode 100644 index 000000000..cb2149f90 --- /dev/null +++ b/konqueror/about/konq_aboutpage.cpp @@ -0,0 +1,558 @@ +#include "konq_aboutpage.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +K_EXPORT_COMPONENT_FACTORY( konq_aboutpage, KonqAboutPageFactory ) + +TDEInstance *KonqAboutPageFactory::s_instance = 0; +TQString *KonqAboutPageFactory::s_launch_html = 0; +TQString *KonqAboutPageFactory::s_intro_html = 0; +TQString *KonqAboutPageFactory::s_specs_html = 0; +TQString *KonqAboutPageFactory::s_tips_html = 0; +TQString *KonqAboutPageFactory::s_plugins_html = 0; + +KonqAboutPageFactory::KonqAboutPageFactory( TQObject *parent, const char *name ) + : KParts::Factory( parent, name ) +{ + s_instance = new TDEInstance( "konqaboutpage" ); +} + +KonqAboutPageFactory::~KonqAboutPageFactory() +{ + delete s_instance; + s_instance = 0; + delete s_launch_html; + s_launch_html = 0; + delete s_intro_html; + s_intro_html = 0; + delete s_specs_html; + s_specs_html = 0; + delete s_tips_html; + s_tips_html = 0; + delete s_plugins_html; + s_plugins_html = 0; +} + +KParts::Part *KonqAboutPageFactory::createPartObject( TQWidget *parentWidget, const char *widgetName, + TQObject *parent, const char *name, + const char *, const TQStringList & ) +{ + //KonqFrame *frame = tqt_dynamic_cast( parentWidget ); + //if ( !frame ) return 0; + + return new KonqAboutPage( //frame->childView()->mainWindow(), + parentWidget, widgetName, parent, name ); +} + +TQString KonqAboutPageFactory::loadFile( const TQString& file ) +{ + TQString res; + if ( file.isEmpty() ) + return res; + + TQFile f( file ); + + if ( !f.open( IO_ReadOnly ) ) + return res; + + TQTextStream t( &f ); + + res = t.read(); + + // otherwise all embedded objects are referenced as about:/... + TQString basehref = TQString::fromLatin1("\n"); + TQRegExp reg(""); + reg.setCaseSensitive(FALSE); + res.replace(reg, "\n\t" + basehref); + return res; +} + +TQString KonqAboutPageFactory::launch() +{ + // FIXME: only regenerate launch page if kuriikwsfilterrc changed. + /* + if ( s_launch_html ) + return *s_launch_html; + */ + + TQString res = loadFile( locate( "data", "konqueror/about/launch.html" )); + if ( res.isEmpty() ) + return res; + + TDEIconLoader *iconloader = TDEGlobal::iconLoader(); + int iconSize = iconloader->currentSize(TDEIcon::Desktop); + TQString home_icon_path = iconloader->iconPath("kfm_home", TDEIcon::Desktop ); + TQString storage_icon_path = iconloader->iconPath("computer", TDEIcon::Desktop ); + TQString remote_icon_path = iconloader->iconPath("network", TDEIcon::Desktop ); + TQString wastebin_icon_path = iconloader->iconPath("trashcan_full", TDEIcon::Desktop ); + TQString applications_icon_path = iconloader->iconPath("kmenu", TDEIcon::Desktop ); + TQString settings_icon_path = iconloader->iconPath("kcontrol", TDEIcon::Desktop ); + TQString help_icon_path = iconloader->iconPath("khelpcenter", TDEIcon::Desktop ); + TQString home_folder = TQDir::homeDirPath(); + TQString continue_icon_path = TQApplication::reverseLayout()?iconloader->iconPath("1leftarrow", TDEIcon::Small ):iconloader->iconPath("1rightarrow", TDEIcon::Small ); + + res = res.arg( locate( "data", "tdeui/about/kde_infopage.css" ) ); + if ( kapp->reverseLayout() ) + res = res.arg( "@import \"%1\";" ).arg( locate( "data", "tdeui/about/kde_infopage_rtl.css" ) ); + else + res = res.arg( "" ); + + // Try to split page in three. If it succeeds, insert the default search into the middle part. + TQStringList parts = TQStringList::split( "", res ); + if ( parts.count() == 3 ) { + TDEConfig config( "kuriikwsfilterrc", true /*read-only*/, false /*no KDE globals*/ ); + config.setGroup( "General" ); + TQString name = config.readEntry("DefaultSearchEngine"); + KService::Ptr service = + KService::serviceByDesktopPath(TQString("searchproviders/%1.desktop").arg(name)); + if ( service ) { + TQString searchBar = parts[1]; + searchBar = searchBar + .arg( iconSize ).arg( iconSize ) + .arg( service->name() ) + .arg( service->property("Keys").toStringList()[0] ) + ; + res = parts[0] + searchBar + parts[2]; + } + else res = parts[0] + parts[2]; + } + + res = res.arg( i18n("Conquer your Desktop!") ) + .arg( i18n( "Konqueror" ) ) + .arg( i18n("Conquer your Desktop!") ) + .arg( i18n("Konqueror is your file manager, web browser and universal document viewer.") ) + .arg( i18n( "Starting Points" ) ) + .arg( i18n( "Introduction" ) ) + .arg( i18n( "Tips" ) ) + .arg( i18n( "Specifications" ) ) + .arg( home_folder ) + .arg( home_icon_path ) + .arg(iconSize).arg(iconSize) + .arg( home_folder ) + .arg( i18n( "Home Folder" ) ) + .arg( i18n( "Your personal files" ) ) + .arg( storage_icon_path ) + .arg(iconSize).arg(iconSize) + .arg( i18n( "Storage Media" ) ) + .arg( i18n( "Disks and removable media" ) ) + .arg( remote_icon_path ) + .arg(iconSize).arg(iconSize) + .arg( i18n( "Network Folders" ) ) + .arg( i18n( "Shared files and folders" ) ) + .arg( wastebin_icon_path ) + .arg(iconSize).arg(iconSize) + .arg( i18n( "Trash" ) ) + .arg( i18n( "Browse and restore the trash" ) ) + .arg( applications_icon_path ) + .arg(iconSize).arg(iconSize) + .arg( i18n( "Applications" ) ) + .arg( i18n( "Installed programs" ) ) + .arg( settings_icon_path ) + .arg(iconSize).arg(iconSize) + .arg( i18n( "Settings" ) ) + .arg( i18n( "Desktop configuration" ) ) + .arg( continue_icon_path ) + .arg( TDEIcon::SizeSmall ).arg( TDEIcon::SizeSmall ) + .arg( i18n( "Next: An Introduction to Konqueror" ) ) + ; + i18n("Search the Web");//i18n for possible future use + + s_launch_html = new TQString( res ); + + return res; +} + +TQString KonqAboutPageFactory::intro() +{ + if ( s_intro_html ) + return *s_intro_html; + + TQString res = loadFile( locate( "data", "konqueror/about/intro.html" )); + if ( res.isEmpty() ) + return res; + + TDEIconLoader *iconloader = TDEGlobal::iconLoader(); + TQString back_icon_path = TQApplication::reverseLayout()?iconloader->iconPath("forward", TDEIcon::Small ):iconloader->iconPath("back", TDEIcon::Small ); + TQString gohome_icon_path = iconloader->iconPath("go-home", TDEIcon::Small ); + TQString continue_icon_path = TQApplication::reverseLayout()?iconloader->iconPath("1leftarrow", TDEIcon::Small ):iconloader->iconPath("1rightarrow", TDEIcon::Small ); + + res = res.arg( locate( "data", "tdeui/about/kde_infopage.css" ) ); + if ( kapp->reverseLayout() ) + res = res.arg( "@import \"%1\";" ).arg( locate( "data", "tdeui/about/kde_infopage_rtl.css" ) ); + else + res = res.arg( "" ); + + res = res.arg( i18n("Conquer your Desktop!") ) + .arg( i18n( "Konqueror" ) ) + .arg( i18n( "Conquer your Desktop!") ) + .arg( i18n( "Konqueror is your file manager, web browser and universal document viewer.") ) + .arg( i18n( "Starting Points" ) ) + .arg( i18n( "Introduction" ) ) + .arg( i18n( "Tips" ) ) + .arg( i18n( "Specifications" ) ) + .arg( i18n( "Konqueror makes working with and managing your files easy. You can browse " + "both local and networked folders while enjoying advanced features " + "such as the powerful sidebar and file previews." + ) ) + .arg( i18n( "Konqueror is also a full featured and easy to use web browser which you " + "can use to explore the Internet. " + "Enter the address (e.g. http://www.trinitydesktop.org) " + "of a web page you would like to visit in the location bar and press Enter, " + "or choose an entry from the Bookmarks menu.") ) + .arg( i18n( "To return to the previous " + "location, press the back button " + "in the toolbar. ").arg( back_icon_path ) ) + .arg( i18n( "To quickly go to your Home folder press the " + " home button ." ).arg(gohome_icon_path) ) + .arg( i18n( "For more detailed documentation on Konqueror click here." ) + .arg("exec:/khelpcenter") ) + .arg( i18n( "Tuning Tip: If you want the Konqueror web browser to start faster," + " you can turn off this information screen by clicking here. You can re-enable it" + " by choosing the Help -> Konqueror Introduction menu option, and then pressing " + "Settings -> Save View Profile \"Web Browsing\".").arg("config:/disable_overview") ) + .arg( "" ).arg( continue_icon_path ) + .arg( i18n( "Next: Tips & Tricks" ) ) + ; + + + s_intro_html = new TQString( res ); + + return res; +} + +TQString KonqAboutPageFactory::specs() +{ + if ( s_specs_html ) + return *s_specs_html; + + TDEIconLoader *iconloader = TDEGlobal::iconLoader(); + TQString res = loadFile( locate( "data", "konqueror/about/specs.html" )); + TQString continue_icon_path = TQApplication::reverseLayout()?iconloader->iconPath("1leftarrow", TDEIcon::Small ):iconloader->iconPath("1rightarrow", TDEIcon::Small ); + if ( res.isEmpty() ) + return res; + + res = res.arg( locate( "data", "tdeui/about/kde_infopage.css" ) ); + if ( kapp->reverseLayout() ) + res = res.arg( "@import \"%1\";" ).arg( locate( "data", "tdeui/about/kde_infopage_rtl.css" ) ); + else + res = res.arg( "" ); + + res = res.arg( i18n("Conquer your Desktop!") ) + .arg( i18n( "Konqueror" ) ) + .arg( i18n("Conquer your Desktop!") ) + .arg( i18n("Konqueror is your file manager, web browser and universal document viewer.") ) + .arg( i18n( "Starting Points" ) ) + .arg( i18n( "Introduction" ) ) + .arg( i18n( "Tips" ) ) + .arg( i18n( "Specifications" ) ) + .arg( i18n("Specifications") ) + .arg( i18n("Konqueror is designed to embrace and support Internet standards. " + "The aim is to fully implement the officially sanctioned standards " + "from organizations such as the W3 and OASIS, while also adding " + "extra support for other common usability features that arise as " + "de facto standards across the Internet. Along with this support, " + "for such functions as favicons, Internet Keywords, and XBEL bookmarks, " + "Konqueror also implements:").arg("http://pyxml.sourceforge.net/topics/xbel/") ) + .arg( i18n("Web Browsing") ) + .arg( i18n("Supported standards") ) + .arg( i18n("Additional requirements*") ) + .arg( i18n("DOM (Level 1, partially Level 2) based " + "HTML 4.01").arg("http://www.w3.org/DOM").arg("http://www.w3.org/TR/html4/") ) + .arg( i18n("built-in") ) + .arg( i18n("Cascading Style Sheets (CSS 1, partially CSS 2)").arg("http://www.w3.org/Style/CSS/") ) + .arg( i18n("built-in") ) + .arg( i18n("ECMA-262 Edition 3 (roughly equals JavaScript 1.5)").arg("http://www.ecma.ch/ecma1/STAND/ECMA-262.HTM") ) + .arg( i18n("JavaScript disabled (globally). Enable JavaScript here.").arg("exec:/tdecmshell tdehtml_java_js") ) + .arg( i18n("JavaScript enabled (globally). Configure JavaScript here.").arg("exec:/tdecmshell tdehtml_java_js") ) // leave the double backslashes here, they are necessary for javascript ! + .arg( i18n("Secure Java® support").arg("http://java.sun.com") ) + .arg( i18n("JDK 1.2.0 (Java 2) compatible VM (Blackdown, IBM or Sun)") + .arg("http://www.blackdown.org").arg("http://www.ibm.com").arg("http://java.sun.com") ) + .arg( i18n("Enable Java (globally) here.").arg("exec:/tdecmshell tdehtml_java_js") ) // TODO Maybe test if Java is enabled ? + .arg( i18n("Netscape Communicator® plugins (for viewing Flash®, Real®Audio, Real®Video, etc.)") + .arg("http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash") + .arg("http://www.real.com").arg("http://www.real.com") + .arg("about:plugins") ) + .arg( i18n("built-in") ) + .arg( i18n("Secure Sockets Layer") ) + .arg( i18n("(TLS/SSL v2/3) for secure communications up to 168bit") ) + .arg( i18n("OpenSSL") ) + .arg( i18n("Bidirectional 16bit unicode support") ) + .arg( i18n("built-in") ) + .arg( i18n("AutoCompletion for forms") ) + .arg( i18n("built-in") ) + .arg( i18n("G E N E R A L") ) + .arg( i18n("Feature") ) + .arg( i18n("Details") ) + .arg( i18n("Image formats") ) + .arg( i18n("Transfer protocols") ) + .arg( i18n("HTTP 1.1 (including gzip/bzip2 compression)") ) + .arg( i18n("FTP") ) + .arg( i18n("and many more...").arg("exec:/tdecmshell ioslaveinfo") ) + .arg( i18n("URL-Completion") ) + .arg( i18n("Manual")) + .arg( i18n("Popup")) + .arg( i18n("(Short-) Automatic")) + .arg( "" ).arg( continue_icon_path ) + .arg( i18n("Return to Starting Points").arg("launch.html") ) + + ; + + s_specs_html = new TQString( res ); + + return res; +} + +TQString KonqAboutPageFactory::tips() +{ + if ( s_tips_html ) + return *s_tips_html; + + TQString res = loadFile( locate( "data", "konqueror/about/tips.html" )); + if ( res.isEmpty() ) + return res; + + TDEIconLoader *iconloader = TDEGlobal::iconLoader(); + TQString viewmag_icon_path = + iconloader->iconPath("viewmag", TDEIcon::Small ); + TQString history_icon_path = + iconloader->iconPath("history", TDEIcon::Small ); + TQString openterm_icon_path = + iconloader->iconPath("openterm", TDEIcon::Small ); + TQString locationbar_erase_rtl_icon_path = + iconloader->iconPath("clear_left", TDEIcon::Small ); + TQString locationbar_erase_icon_path = + iconloader->iconPath("locationbar_erase", TDEIcon::Small ); + TQString window_fullscreen_icon_path = + iconloader->iconPath("view-fullscreen", TDEIcon::Small ); + TQString view_left_right_icon_path = + iconloader->iconPath("view_left_right", TDEIcon::Small ); + TQString continue_icon_path = TQApplication::reverseLayout()?iconloader->iconPath("1leftarrow", TDEIcon::Small ):iconloader->iconPath("1rightarrow", TDEIcon::Small ); + + res = res.arg( locate( "data", "tdeui/about/kde_infopage.css" ) ); + if ( kapp->reverseLayout() ) + res = res.arg( "@import \"%1\";" ).arg( locate( "data", "tdeui/about/kde_infopage_rtl.css" ) ); + else + res = res.arg( "" ); + + res = res.arg( i18n("Conquer your Desktop!") ) + .arg( i18n( "Konqueror" ) ) + .arg( i18n("Conquer your Desktop!") ) + .arg( i18n("Konqueror is your file manager, web browser and universal document viewer.") ) + .arg( i18n( "Starting Points" ) ) + .arg( i18n( "Introduction" ) ) + .arg( i18n( "Tips" ) ) + .arg( i18n( "Specifications" ) ) + .arg( i18n( "Tips & Tricks" ) ) + .arg( i18n( "Use Internet-Keywords and Web-Shortcuts: by typing \"gg: Trinity Desktop\" one can search the Internet, " + "using Google, for the search phrase \"Trinity Desktop\". There are a lot of " + "Web-Shortcuts predefined to make searching for software or looking " + "up certain words in an encyclopedia a breeze. You can even " + "create your own Web-Shortcuts." ).arg("exec:/tdecmshell ebrowsing") ) + .arg( i18n( "Use the magnifier button in the" + " toolbar to increase the font size on your web page.").arg(viewmag_icon_path) ) + .arg( i18n( "When you want to paste a new address into the Location toolbar you might want to " + "clear the current entry by pressing the black arrow with the white cross " + " in the toolbar.") + .arg(TQApplication::reverseLayout() ? locationbar_erase_rtl_icon_path : locationbar_erase_icon_path)) + .arg( i18n( "To create a link on your desktop pointing to the current page, " + "simply drag the \"Location\" label that is to the left of the Location toolbar, drop it on to " + "the desktop, and choose \"Link\"." ) ) + .arg( i18n( "You can also find \"Full-Screen Mode\" " + "in the Settings menu. This feature is very useful for \"Talk\" " + "sessions.").arg(window_fullscreen_icon_path) ) + .arg( i18n( "Divide et impera (lat. \"Divide and conquer\") - by splitting a window " + "into two parts (e.g. Window -> Split View " + "Left/Right) you can make Konqueror appear the way you like. You" + " can even load some example view-profiles (e.g. Midnight Commander)" + ", or create your own ones." ).arg(view_left_right_icon_path)) + .arg( i18n( "Use the user-agent feature if the website you are visiting " + "asks you to use a different browser " + "(and do not forget to send a complaint to the webmaster!)" ).arg("exec:/tdecmshell useragent") ) + .arg( i18n( "The History in your SideBar ensures " + "that you can keep track of the pages you have visited recently.").arg(history_icon_path) ) + .arg( i18n( "Use a caching proxy to speed up your" + " Internet connection.").arg("exec:/tdecmshell proxy") ) + .arg( i18n( "Advanced users will appreciate the Konsole which you can embed into " + "Konqueror (Window -> Show " + "Terminal Emulator).").arg(openterm_icon_path)) + .arg( i18n( "Thanks to DCOP you can have full control over Konqueror using a script." +).arg("exec:/kdcop") ) + .arg( i18n( "" ).arg( continue_icon_path ) ) + .arg( i18n( "Next: Specifications" ) ) + ; + + + s_tips_html = new TQString( res ); + + return res; +} + + +TQString KonqAboutPageFactory::plugins() +{ + if ( s_plugins_html ) + return *s_plugins_html; + + TQString res = loadFile( locate( "data", kapp->reverseLayout() ? "konqueror/about/plugins_rtl.html" : "konqueror/about/plugins.html" )) + .arg(i18n("Installed Plugins")) + .arg(i18n("PluginDescriptionFileTypes")) + .arg(i18n("Installed")) + .arg(i18n("Mime TypeDescriptionSuffixesPlugin")); + if ( res.isEmpty() ) + return res; + + s_plugins_html = new TQString( res ); + + return res; +} + + +KonqAboutPage::KonqAboutPage( //KonqMainWindow * + TQWidget *parentWidget, const char *widgetName, + TQObject *parent, const char *name ) + : TDEHTMLPart( parentWidget, widgetName, parent, name, BrowserViewGUI ) +{ + //m_mainWindow = mainWindow; + TQTextCodec* codec = TDEGlobal::locale()->codecForEncoding(); + if (codec) + setCharset(codec->name(), true); + else + setCharset("iso-8859-1", true); + // about:blah isn't a tdeioslave -> disable View source + TDEAction * act = actionCollection()->action("viewDocumentSource"); + if ( act ) + act->setEnabled( false ); +} + +KonqAboutPage::~KonqAboutPage() +{ +} + +bool KonqAboutPage::openURL( const KURL &u ) +{ + kdDebug(1202) << "now in KonqAboutPage::openURL( \"" << u.url() << "\" )" << endl; + if ( u.url() == "about:plugins" ) + serve( KonqAboutPageFactory::plugins(), "plugins" ); + else if ( !u.query().isEmpty() ) { + TQMap< TQString, TQString > queryItems = u.queryItems( 0 ); + TQMap< TQString, TQString >::ConstIterator query = queryItems.begin(); + TQString newUrl; + if (query.key() == "strigi") { + newUrl = KURIFilter::self()->filteredURI( query.key() + ":?q=" + query.data() ); + } else { + newUrl = KURIFilter::self()->filteredURI( query.key() + ":" + query.data() ); + } + kdDebug(1202) << "scheduleRedirection( 0, \"" << newUrl << "\" )" << endl; + scheduleRedirection( 0, newUrl ); + } + else serve( KonqAboutPageFactory::launch(), "konqueror" ); + return true; +} + +bool KonqAboutPage::openFile() +{ + return true; +} + +void KonqAboutPage::saveState( TQDataStream &stream ) +{ + stream << m_htmlDoc; + stream << m_what; +} + +void KonqAboutPage::restoreState( TQDataStream &stream ) +{ + stream >> m_htmlDoc; + stream >> m_what; + serve( m_htmlDoc, m_what ); +} + +void KonqAboutPage::serve( const TQString& html, const TQString& what ) +{ + m_what = what; + begin( KURL( TQString("about:%1").arg(what) ) ); + write( html ); + end(); + m_htmlDoc = html; +} + +void KonqAboutPage::urlSelected( const TQString &url, int button, int state, const TQString &target, KParts::URLArgs _args ) +{ + KURL u( url ); + if ( u.protocol() == "exec" ) + { + TQStringList args = TQStringList::split( TQChar( ' ' ), url.mid( 6 ) ); + TQString executable = args[ 0 ]; + args.remove( args.begin() ); + TDEApplication::tdeinitExec( executable, args ); + return; + } + + if ( url == TQString::fromLatin1("launch.html") ) + { + emit browserExtension()->openURLNotify(); + serve( KonqAboutPageFactory::launch(), "konqueror" ); + return; + } + else if ( url == TQString::fromLatin1("intro.html") ) + { + emit browserExtension()->openURLNotify(); + serve( KonqAboutPageFactory::intro(), "konqueror" ); + return; + } + else if ( url == TQString::fromLatin1("specs.html") ) + { + emit browserExtension()->openURLNotify(); + serve( KonqAboutPageFactory::specs(), "konqueror" ); + return; + } + else if ( url == TQString::fromLatin1("tips.html") ) + { + emit browserExtension()->openURLNotify(); + serve( KonqAboutPageFactory::tips(), "konqueror" ); + return; + } + + else if ( url == TQString::fromLatin1("config:/disable_overview") ) + { + if ( KMessageBox::questionYesNo( widget(), + i18n("Do you want to disable showing " + "the introduction in the webbrowsing profile?"), + i18n("Faster Startup?"),i18n("Disable"),i18n("Keep") ) + == KMessageBox::Yes ) + { + TQString profile = locateLocal("data", "konqueror/profiles/webbrowsing"); + KSaveFile file( profile ); + if ( file.status() == 0 ) { + TQCString content = "[Profile]\n" + "Name=Web-Browser"; + fputs( content.data(), file.fstream() ); + file.close(); + } + } + return; + } + + TDEHTMLPart::urlSelected( url, button, state, target, _args ); +} + +#include "konq_aboutpage.moc" diff --git a/konqueror/client/CMakeLists.txt b/konqueror/client/CMakeLists.txt index 3ae477d32..fe45ce141 100644 --- a/konqueror/client/CMakeLists.txt +++ b/konqueror/client/CMakeLists.txt @@ -32,7 +32,7 @@ install( PROGRAMS kfmclient_3_2_update.sh DESTINATION ${DATA_INSTALL_DIR}/tdecon set( target kfmclient ) set( ${target}_SRCS - kfmclient.cc + kfmclient.cpp ${CMAKE_SOURCE_DIR}/konqueror/KonquerorIface.stub ${CMAKE_SOURCE_DIR}/kdesktop/KDesktopIface.stub ) diff --git a/konqueror/client/Makefile.am b/konqueror/client/Makefile.am index c66ed555c..872951b4e 100644 --- a/konqueror/client/Makefile.am +++ b/konqueror/client/Makefile.am @@ -7,7 +7,7 @@ tdeinit_LTLIBRARIES = kfmclient.la INCLUDES= -I.. $(all_includes) kfmclient_la_LDFLAGS = $(all_libraries) -module -avoid-version kfmclient_la_LIBADD = $(LIB_TDEIO) -kfmclient_la_SOURCES = kfmclient.cc KonquerorIface.stub KDesktopIface.stub +kfmclient_la_SOURCES = kfmclient.cpp KonquerorIface.stub KDesktopIface.stub noinst_HEADERS = kfmclient.h METASOURCES = AUTO @@ -16,7 +16,7 @@ KonquerorIface_DIR = $(srcdir)/.. KDesktopIface_DIR = $(top_srcdir)/kdesktop messages: - $(XGETTEXT) -kaliasLocal *.h *.cc -o $(podir)/kfmclient.pot + $(XGETTEXT) -kaliasLocal *.h *.cpp -o $(podir)/kfmclient.pot updatedir = $(kde_datadir)/tdeconf_update update_DATA = kfmclient_3_2.upd diff --git a/konqueror/client/kfmclient.cc b/konqueror/client/kfmclient.cc deleted file mode 100644 index c0f0c5c69..000000000 --- a/konqueror/client/kfmclient.cc +++ /dev/null @@ -1,653 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 1999 David Faure - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "kfmclient.h" -#include "KonquerorIface_stub.h" -#include "KDesktopIface_stub.h" -#include "twin.h" - -#include - -static const char appName[] = "kfmclient"; -static const char programName[] = I18N_NOOP("kfmclient"); - -static const char description[] = I18N_NOOP("TDE tool for opening URLs from the command line"); - -static const char version[] = "2.0"; - -TQCString clientApp::startup_id_str; -bool clientApp::m_ok = true; -bool s_interactive = true; - -static const TDECmdLineOptions options[] = -{ - { "noninteractive", I18N_NOOP("Non interactive use: no message boxes"), 0}, - { "commands", I18N_NOOP("Show available commands"), 0}, - { "+command", I18N_NOOP("Command (see --commands)"), 0}, - { "+[URL(s)]", I18N_NOOP("Arguments for command"), 0}, - TDECmdLineLastOption -}; - -extern "C" KDE_EXPORT int kdemain( int argc, char **argv ) -{ - TDECmdLineArgs::init(argc, argv, appName, programName, description, version, false); - - TDECmdLineArgs::addCmdLineOptions( options ); - TDECmdLineArgs::addTempFileOption(); - - TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs(); - - if ( args->isSet("commands") ) - { - TDECmdLineArgs::enable_i18n(); - puts(i18n("\nSyntax:\n").local8Bit()); - puts(i18n(" kfmclient openURL 'url' ['mimetype']\n" - " # Opens a window showing 'url'.\n" - " # 'url' may be a relative path\n" - " # or file name, such as . or subdir/\n" - " # If 'url' is omitted, $HOME is used instead.\n\n").local8Bit()); - puts(i18n(" # If 'mimetype' is specified, it will be used to determine the\n" - " # component that Konqueror should use. For instance, set it to\n" - " # text/html for a web page, to make it appear faster\n\n").local8Bit()); - - puts(i18n(" kfmclient newTab 'url' ['mimetype']\n" - " # Same as above but opens a new tab with 'url' in an existing Konqueror\n" - " # window on the current active desktop if possible.\n\n").local8Bit()); - - puts(i18n(" kfmclient openProfile 'profile' ['url']\n" - " # Opens a window using the given profile.\n" - " # 'profile' is a file under ~/.trinity/share/apps/konqueror/profiles.\n" - " # 'url' is an optional URL to open.\n\n").local8Bit()); - - puts(i18n(" kfmclient openProperties 'url'\n" - " # Opens a properties menu\n\n").local8Bit()); - puts(i18n(" kfmclient exec ['url' ['binding']]\n" - " # Tries to execute 'url'. 'url' may be a usual\n" - " # URL, this URL will be opened. You may omit\n" - " # 'binding'. In this case the default binding\n").local8Bit()); - puts(i18n(" # is tried. Of course URL may be the URL of a\n" - " # document, or it may be a *.desktop file.\n").local8Bit()); - puts(i18n(" # This way you could for example mount a device\n" - " # by passing 'Mount default' as binding to \n" - " # 'cdrom.desktop'\n\n").local8Bit()); - puts(i18n(" kfmclient move 'src' 'dest'\n" - " # Moves the URL 'src' to 'dest'.\n" - " # 'src' may be a list of URLs.\n").local8Bit()); - //puts(i18n(" # 'dest' may be \"trash:/\" to move the files\n" - // " # in the trash bin.\n\n").local8Bit()); - puts(i18n(" kfmclient download ['src']\n" - " # Copies the URL 'src' to a user specified location'.\n" - " # 'src' may be a list of URLs, if not present then\n" - " # a URL will be requested.\n\n").local8Bit()); - puts(i18n(" kfmclient copy 'src' 'dest'\n" - " # Copies the URL 'src' to 'dest'.\n" - " # 'src' may be a list of URLs.\n\n").local8Bit()); - puts(i18n(" kfmclient sortDesktop\n" - " # Rearranges all icons on the desktop.\n\n").local8Bit()); - puts(i18n(" kfmclient openBrowser\n" - " # Opens the system default Web browser.\n\n").local8Bit()); - puts(i18n(" kfmclient configure\n" - " # Re-read Konqueror's configuration.\n\n").local8Bit()); - puts(i18n(" kfmclient configureDesktop\n" - " # Re-read kdesktop's configuration.\n\n").local8Bit()); - - puts(i18n("*** Examples:\n" - " kfmclient exec file:/root/Desktop/cdrom.desktop \"Mount default\"\n" - " // Mounts the CD-ROM\n\n").local8Bit()); - puts(i18n(" kfmclient exec file:/home/weis/data/test.html\n" - " // Opens the file with default binding\n\n").local8Bit()); - puts(i18n(" kfmclient exec file:/home/weis/data/test.html Netscape\n" - " // Opens the file with netscape\n\n").local8Bit()); - puts(i18n(" kfmclient exec ftp://localhost/\n" - " // Opens new window with URL\n\n").local8Bit()); - puts(i18n(" kfmclient exec file:/root/Desktop/emacs.desktop\n" - " // Starts emacs\n\n").local8Bit()); - puts(i18n(" kfmclient exec file:/root/Desktop/cdrom.desktop\n" - " // Opens the CD-ROM's mount directory\n\n").local8Bit()); - puts(i18n(" kfmclient exec .\n" - " // Opens the current directory. Very convenient.\n\n").local8Bit()); - return 0; - } - - return clientApp::doIt() ? 0 /*no error*/ : 1 /*error*/; -} - -/* - Whether to start a new konqueror or reuse an existing process. - - First of all, this concept is actually broken, as the view used to show - the data may change at any time, and therefore Konqy reused to browse - "safe" data may eventually browse something completely different. - Moreover, it's quite difficult to find out when to reuse, and thus this - function is an ugly hack. You've been warned. - - Kfmclient will attempt to find an instance for reusing if either reusing - is configured to reuse always, - or it's not configured to never reuse, and the URL to-be-opened is "safe". - The URL is safe, if the view used to view it is listed in the allowed KPart's. - In order to find out the part, mimetype is needed, and TDETrader is needed. - If mimetype is not known, KMimeType is used (which doesn't work e.g. for remote - URLs, but oh well). Since this function may be running without a TDEApplication - instance, I'm actually quite surprised it works, and it may sooner or later break. - Nice, isn't it? - - If a profile is being used, and no url has been explicitly given, it needs to be - read from the profile. If there's more than one URL listed in the profile, no reusing - will be done (oh well), if there's no URL, no reusing will be done either (also - because the webbrowsing profile doesn't have any URL listed). -*/ -static bool startNewKonqueror( TQString url, TQString mimetype, const TQString& profile ) -{ - TDEConfig cfg( TQString::fromLatin1( "konquerorrc" ), true ); - cfg.setGroup( "Reusing" ); - TQStringList allowed_parts; - // is duplicated in ../KonquerorIface.cc - allowed_parts << TQString::fromLatin1( "konq_iconview.desktop" ) - << TQString::fromLatin1( "konq_multicolumnview.desktop" ) - << TQString::fromLatin1( "konq_sidebartng.desktop" ) - << TQString::fromLatin1( "konq_infolistview.desktop" ) - << TQString::fromLatin1( "konq_treeview.desktop" ) - << TQString::fromLatin1( "konq_detailedlistview.desktop" ); - if( cfg.hasKey( "SafeParts" ) - && cfg.readEntry( "SafeParts" ) != TQString::fromLatin1( "SAFE" )) - allowed_parts = cfg.readListEntry( "SafeParts" ); - if( allowed_parts.count() == 1 && allowed_parts.first() == TQString::fromLatin1( "ALL" )) - return false; // all parts allowed - if( url.isEmpty()) - { - if( profile.isEmpty()) - return true; - TQString profilepath = locate( "data", TQString::fromLatin1("konqueror/profiles/") + profile ); - if( profilepath.isEmpty()) - return true; - TDEConfig cfg( profilepath, true ); - cfg.setDollarExpansion( true ); - cfg.setGroup( "Profile" ); - TQMap< TQString, TQString > entries = cfg.entryMap( TQString::fromLatin1( "Profile" )); - TQRegExp urlregexp( TQString::fromLatin1( "^View[0-9]*_URL$" )); - TQStringList urls; - for( TQMap< TQString, TQString >::ConstIterator it = entries.begin(); - it != entries.end(); - ++it ) - { - // don't read value from map, dollar expansion is needed - TQString value = cfg.readEntry( it.key()); - if( urlregexp.search( it.key()) >= 0 && !value.isEmpty()) - urls << value; - } - if( urls.count() != 1 ) - return true; - url = urls.first(); - mimetype = TQString::fromLatin1( "" ); - } - if( mimetype.isEmpty()) - mimetype = KMimeType::findByURL( KURL( url ) )->name(); - TDETrader::OfferList offers = TDETrader::self()->query( mimetype, TQString::fromLatin1( "KParts/ReadOnlyPart" ), - TQString::null, TQString::null ); - KService::Ptr serv; - if( offers.count() > 0 ) - serv = offers.first(); - return serv == NULL || !allowed_parts.contains( serv->desktopEntryName() + TQString::fromLatin1(".desktop") ); -} - -static int currentScreen() -{ - if( tqt_xdisplay() != NULL ) - return tqt_xscreen(); - // case when there's no TDEApplication instance - const char* env = getenv( "DISPLAY" ); - if( env == NULL ) - return 0; - const char* dotpos = strrchr( env, '.' ); - const char* colonpos = strrchr( env, ':' ); - if( dotpos != NULL && colonpos != NULL && dotpos > colonpos ) - return atoi( dotpos + 1 ); - return 0; -} - -// when reusing a preloaded konqy, make sure your always use a DCOP call which opens a profile ! -static TQCString getPreloadedKonqy() -{ - TDEConfig cfg( TQString::fromLatin1( "konquerorrc" ), true ); - cfg.setGroup( "Reusing" ); - if( cfg.readNumEntry( "MaxPreloadCount", 1 ) == 0 ) - return ""; - DCOPRef ref( "kded", "konqy_preloader" ); - TQCString ret; - if( ref.callExt( "getPreloadedKonqy", DCOPRef::NoEventLoop, 3000, currentScreen()).get( ret )) - return ret; - return TQCString(); -} - - -static TQCString konqyToReuse( const TQString& url, const TQString& mimetype, const TQString& profile ) -{ // prefer(?) preloaded ones - TQCString ret = getPreloadedKonqy(); - if( !ret.isEmpty()) - return ret; - if( startNewKonqueror( url, mimetype, profile )) - return ""; - TQCString appObj; - TQByteArray data; - TQDataStream str( data, IO_WriteOnly ); - str << currentScreen(); - if( !TDEApplication::dcopClient()->findObject( "konqueror*", "KonquerorIface", - "processCanBeReused( int )", data, ret, appObj, false, 3000 ) ) - return ""; - return ret; -} - -static bool krun_has_error = false; - -void clientApp::sendASNChange() -{ - TDEStartupInfoId id; - id.initId( startup_id_str ); - TDEStartupInfoData data; - data.addPid( 0 ); // say there's another process for this ASN with unknown PID - data.setHostname(); // ( no need to bother to get this konqy's PID ) - Display* dpy = tqt_xdisplay(); - if( dpy == NULL ) // we may be running without TQApplication here - dpy = XOpenDisplay( NULL ); - if( dpy != NULL ) - TDEStartupInfo::sendChangeX( dpy, id, data ); - if( dpy != NULL && dpy != tqt_xdisplay()) - XCloseDisplay( dpy ); -} - -bool clientApp::createNewWindow(const KURL & url, bool newTab, bool tempFile, const TQString & mimetype) -{ - kdDebug( 1202 ) << "clientApp::createNewWindow " << url.url() << " mimetype=" << mimetype << endl; - // check if user wants to use external browser - // ###### this option seems to have no GUI and to be redundant with BrowserApplication now. - // ###### KDE4: remove - TDEConfig config( TQString::fromLatin1("kfmclientrc")); - config.setGroup( TQString::fromLatin1("Settings")); - TQString strBrowser = config.readPathEntry("ExternalBrowser"); - if (!strBrowser.isEmpty()) - { - if ( tempFile ) - kdWarning() << "kfmclient used with --tempfile but is passing to an external browser! Tempfile will never be deleted" << endl; - TDEProcess proc; - proc << strBrowser << url.url(); - proc.start( TDEProcess::DontCare ); - return true; - } - - if (url.protocol().startsWith(TQString::fromLatin1("http"))) - { - config.setGroup("General"); - if (!config.readEntry("BrowserApplication").isEmpty()) - { - clientApp app; - TDEStartupInfo::appStarted(); - - KRun * run = new KRun( url, 0, 0, false, false /* no progress window */ ); // TODO pass tempFile [needs support in the KRun ctor] - TQObject::connect( run, TQT_SIGNAL( finished() ), &app, TQT_SLOT( delayedQuit() )); - TQObject::connect( run, TQT_SIGNAL( error() ), &app, TQT_SLOT( delayedQuit() )); - app.exec(); - return !krun_has_error; - } - } - - TDEConfig cfg( TQString::fromLatin1( "konquerorrc" ), true ); - cfg.setGroup( "FMSettings" ); - if ( newTab || cfg.readBoolEntry( "KonquerorTabforExternalURL", false ) ) - { - TQCString foundApp, foundObj; - TQByteArray data; - TQDataStream str( data, IO_WriteOnly ); - if( TDEApplication::dcopClient()->findObject( "konqueror*", "konqueror-mainwindow*", - "windowCanBeUsedForTab()", data, foundApp, foundObj, false, 3000 ) ) - { - DCOPRef ref( foundApp, foundObj ); - DCOPReply reply = ref.call( "newTabASN", url.url(), startup_id_str, tempFile ); - if ( reply.isValid() ) { - sendASNChange(); - return true; - } - } - } - - TQCString appId = konqyToReuse( url.url(), mimetype, TQString::null ); - if( !appId.isEmpty()) - { - kdDebug( 1202 ) << "clientApp::createNewWindow using existing konqueror" << endl; - KonquerorIface_stub konqy( appId, "KonquerorIface" ); - konqy.createNewWindowASN( url.url(), mimetype, startup_id_str, tempFile ); - sendASNChange(); - } - else - { - TQString error; - /* Well, we can't pass a mimetype through startServiceByDesktopPath ! - if ( TDEApplication::startServiceByDesktopPath( TQString::fromLatin1("konqueror.desktop"), - url.url(), &error ) > 0 ) - { - kdError() << "Couldn't start konqueror from konqueror.desktop: " << error << endl; - */ - // pass kfmclient's startup id to konqueror using kshell - TDEStartupInfoId id; - id.initId( startup_id_str ); - id.setupStartupEnv(); - TDEProcess proc; - proc << "kshell" << "konqueror"; - if ( !mimetype.isEmpty() ) - proc << "-mimetype" << mimetype; - if ( tempFile ) - proc << "-tempfile"; - proc << url.url(); - proc.start( TDEProcess::DontCare ); - TDEStartupInfo::resetStartupEnv(); - kdDebug( 1202 ) << "clientApp::createNewWindow TDEProcess started" << endl; - //} - } - return true; -} - -bool clientApp::openProfile( const TQString & profileName, const TQString & url, const TQString & mimetype ) -{ - TQCString appId = konqyToReuse( url, mimetype, profileName ); - if( appId.isEmpty()) - { - TQString error; - if ( TDEApplication::startServiceByDesktopPath( TQString::fromLatin1("konqueror.desktop"), - TQString::fromLatin1("--silent"), &error, &appId, NULL, startup_id_str ) > 0 ) - { - kdError() << "Couldn't start konqueror from konqueror.desktop: " << error << endl; - return false; - } - // startServiceByDesktopPath waits for the app to register with DCOP - // so when we arrive here, konq is up and running already, and appId contains the identification - } - - TQString profile = locate( "data", TQString::fromLatin1("konqueror/profiles/") + profileName ); - if ( profile.isEmpty() ) - { - fprintf( stderr, "%s", i18n("Profile %1 not found\n").arg(profileName).local8Bit().data() ); - ::exit( 0 ); - } - KonquerorIface_stub konqy( appId, "KonquerorIface" ); - if ( url.isEmpty() ) - konqy.createBrowserWindowFromProfileASN( profile, profileName, startup_id_str ); - else if ( mimetype.isEmpty() ) - konqy.createBrowserWindowFromProfileAndURLASN( profile, profileName, url, startup_id_str ); - else - konqy.createBrowserWindowFromProfileAndURLASN( profile, profileName, url, mimetype, startup_id_str ); - sleep(2); // Martin Schenk says this is necessary to let the server read from the socket - sendASNChange(); - return true; -} - -void clientApp::delayedQuit() -{ - // Quit in 2 seconds. This leaves time for KRun to pop up - // "app not found" in TDEProcessRunner, if that was the case. - TQTimer::singleShot( 2000, this, TQT_SLOT(deref()) ); - // don't access the KRun instance later, it will be deleted after calling slots - if( static_cast< const KRun* >( sender())->hasError()) - krun_has_error = true; -} - -static void checkArgumentCount(int count, int min, int max) -{ - if (count < min) - { - fputs( i18n("Syntax Error: Not enough arguments\n").local8Bit(), stderr ); - ::exit(1); - } - if (max && (count > max)) - { - fputs( i18n("Syntax Error: Too many arguments\n").local8Bit(), stderr ); - ::exit(1); - } -} - -bool clientApp::doIt() -{ - TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs(); - int argc = args->count(); - checkArgumentCount(argc, 1, 0); - - if ( !args->isSet( "ninteractive" ) ) { - s_interactive = false; - } - TQCString command = args->arg(0); - - // read ASN env. variable for non-KApp cases - startup_id_str = TDEStartupInfo::currentStartupIdEnv().id(); - - if ( command == "openURL" || command == "newTab" ) - { - TDEInstance inst(appName); - if( !TDEApplication::dcopClient()->attach()) - { - TDEApplication::startKdeinit(); - TDEApplication::dcopClient()->attach(); - } - checkArgumentCount(argc, 1, 3); - bool tempFile = TDECmdLineArgs::isTempFileSet(); - if ( argc == 1 ) - { - KURL url; - url.setPath(TQDir::homeDirPath()); - return createNewWindow( url, command == "newTab", tempFile ); - } - if ( argc == 2 ) - { - return createNewWindow( args->url(1), command == "newTab", tempFile ); - } - if ( argc == 3 ) - { - return createNewWindow( args->url(1), command == "newTab", tempFile, TQString::fromLatin1(args->arg(2)) ); - } - } - else if ( command == "openProfile" ) - { - TDEInstance inst(appName); - if( !TDEApplication::dcopClient()->attach()) - { - TDEApplication::startKdeinit(); - TDEApplication::dcopClient()->attach(); - } - checkArgumentCount(argc, 2, 3); - TQString url; - if ( argc == 3 ) - url = args->url(2).url(); - return openProfile( TQString::fromLocal8Bit(args->arg(1)), url ); - } - - // the following commands need TDEApplication - clientApp app; - - if ( command == "openProperties" ) - { - checkArgumentCount(argc, 2, 2); - KPropertiesDialog * p = new KPropertiesDialog( args->url(1) ); - TQObject::connect( p, TQT_SIGNAL( destroyed() ), &app, TQT_SLOT( quit() )); - TQObject::connect( p, TQT_SIGNAL( canceled() ), &app, TQT_SLOT( slotDialogCanceled() )); - app.exec(); - return m_ok; - } - else if ( command == "exec" ) - { - checkArgumentCount(argc, 1, 3); - if ( argc == 1 ) - { - KDesktopIface_stub kdesky( "kdesktop", "KDesktopIface" ); - kdesky.popupExecuteCommand(); - } - else if ( argc == 2 ) - { - KRun * run = new KRun( args->url(1), 0, 0, false, false /* no progress window */ ); - TQObject::connect( run, TQT_SIGNAL( finished() ), &app, TQT_SLOT( delayedQuit() )); - TQObject::connect( run, TQT_SIGNAL( error() ), &app, TQT_SLOT( delayedQuit() )); - app.exec(); - return !krun_has_error; - } - else if ( argc == 3 ) - { - KURL::List urls; - urls.append( args->url(1) ); - const TDETrader::OfferList offers = TDETrader::self()->query( TQString::fromLocal8Bit( args->arg( 2 ) ), TQString::fromLatin1( "Application" ), TQString::null, TQString::null ); - if (offers.isEmpty()) return 1; - KService::Ptr serv = offers.first(); - return KRun::run( *serv, urls ); - } - } - else if ( command == "openBrowser" ) - { - KRun * run = new KRun( "http://default.browser", 0, 0, false, false /* no progress window */ ); - TQObject::connect( run, TQT_SIGNAL( finished() ), &app, TQT_SLOT( delayedQuit() )); - TQObject::connect( run, TQT_SIGNAL( error() ), &app, TQT_SLOT( delayedQuit() )); - app.exec(); - return !krun_has_error; - } - else if ( command == "move" ) - { - checkArgumentCount(argc, 2, 0); - KURL::List srcLst; - for ( int i = 1; i <= argc - 2; i++ ) - srcLst.append( args->url(i) ); - - TDEIO::Job * job = TDEIO::move( srcLst, args->url(argc - 1) ); - if ( !s_interactive ) - job->setInteractive( false ); - connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ), &app, TQT_SLOT( slotResult( TDEIO::Job * ) ) ); - app.exec(); - return m_ok; - } - else if ( command == "download" ) - { - checkArgumentCount(argc, 0, 0); - KURL::List srcLst; - if (argc == 1) { - while(true) { - KURL src = KURLRequesterDlg::getURL(); - if (!src.isEmpty()) { - if (!src.isValid()) { - KMessageBox::error(0, i18n("Unable to download from an invalid URL.")); - continue; - } - srcLst.append(src); - } - break; - } - } else { - for ( int i = 1; i <= argc - 1; i++ ) - srcLst.append( args->url(i) ); - } - if (srcLst.count() == 0) - return m_ok; - TQString dst = - KFileDialog::getSaveFileName( (argc<2) ? (TQString::null) : (args->url(1).filename()) ); - if (dst.isEmpty()) // cancelled - return m_ok; // AK - really okay? - KURL dsturl; - dsturl.setPath( dst ); - TDEIO::Job * job = TDEIO::copy( srcLst, dsturl ); - if ( !s_interactive ) - job->setInteractive( false ); - connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ), &app, TQT_SLOT( slotResult( TDEIO::Job * ) ) ); - app.exec(); - return m_ok; - } - else if ( command == "copy" ) - { - checkArgumentCount(argc, 2, 0); - KURL::List srcLst; - for ( int i = 1; i <= argc - 2; i++ ) - srcLst.append( args->url(i) ); - - TDEIO::Job * job = TDEIO::copy( srcLst, args->url(argc - 1) ); - if ( !s_interactive ) - job->setInteractive( false ); - connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ), &app, TQT_SLOT( slotResult( TDEIO::Job * ) ) ); - app.exec(); - return m_ok; - } - else if ( command == "sortDesktop" ) - { - checkArgumentCount(argc, 1, 1); - - KDesktopIface_stub kdesky( "kdesktop", "KDesktopIface" ); - kdesky.rearrangeIcons( (int)false ); - - return true; - } - else if ( command == "configure" ) - { - checkArgumentCount(argc, 1, 1); - TQByteArray data; - kapp->dcopClient()->send( "*", "KonqMainViewIface", "reparseConfiguration()", data ); - // Warning. In case something is added/changed here, keep kcontrol/konq/main.cpp in sync. - } - else if ( command == "configureDesktop" ) - { - checkArgumentCount(argc, 1, 1); - KDesktopIface_stub kdesky( "kdesktop", "KDesktopIface" ); - kdesky.configure(); - } - else - { - fprintf( stderr, "%s", i18n("Syntax Error: Unknown command '%1'\n").arg(TQString::fromLocal8Bit(command)).local8Bit().data() ); - return false; - } - return true; -} - -void clientApp::slotResult( TDEIO::Job * job ) -{ - if (job->error() && s_interactive) - job->showErrorDialog(); - m_ok = !job->error(); - quit(); -} - -void clientApp::slotDialogCanceled() -{ - m_ok = false; - quit(); -} - -#include "kfmclient.moc" diff --git a/konqueror/client/kfmclient.cpp b/konqueror/client/kfmclient.cpp new file mode 100644 index 000000000..efc858f61 --- /dev/null +++ b/konqueror/client/kfmclient.cpp @@ -0,0 +1,653 @@ +/* This file is part of the KDE project + Copyright (C) 1999 David Faure + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "kfmclient.h" +#include "KonquerorIface_stub.h" +#include "KDesktopIface_stub.h" +#include "twin.h" + +#include + +static const char appName[] = "kfmclient"; +static const char programName[] = I18N_NOOP("kfmclient"); + +static const char description[] = I18N_NOOP("TDE tool for opening URLs from the command line"); + +static const char version[] = "2.0"; + +TQCString clientApp::startup_id_str; +bool clientApp::m_ok = true; +bool s_interactive = true; + +static const TDECmdLineOptions options[] = +{ + { "noninteractive", I18N_NOOP("Non interactive use: no message boxes"), 0}, + { "commands", I18N_NOOP("Show available commands"), 0}, + { "+command", I18N_NOOP("Command (see --commands)"), 0}, + { "+[URL(s)]", I18N_NOOP("Arguments for command"), 0}, + TDECmdLineLastOption +}; + +extern "C" KDE_EXPORT int kdemain( int argc, char **argv ) +{ + TDECmdLineArgs::init(argc, argv, appName, programName, description, version, false); + + TDECmdLineArgs::addCmdLineOptions( options ); + TDECmdLineArgs::addTempFileOption(); + + TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs(); + + if ( args->isSet("commands") ) + { + TDECmdLineArgs::enable_i18n(); + puts(i18n("\nSyntax:\n").local8Bit()); + puts(i18n(" kfmclient openURL 'url' ['mimetype']\n" + " # Opens a window showing 'url'.\n" + " # 'url' may be a relative path\n" + " # or file name, such as . or subdir/\n" + " # If 'url' is omitted, $HOME is used instead.\n\n").local8Bit()); + puts(i18n(" # If 'mimetype' is specified, it will be used to determine the\n" + " # component that Konqueror should use. For instance, set it to\n" + " # text/html for a web page, to make it appear faster\n\n").local8Bit()); + + puts(i18n(" kfmclient newTab 'url' ['mimetype']\n" + " # Same as above but opens a new tab with 'url' in an existing Konqueror\n" + " # window on the current active desktop if possible.\n\n").local8Bit()); + + puts(i18n(" kfmclient openProfile 'profile' ['url']\n" + " # Opens a window using the given profile.\n" + " # 'profile' is a file under ~/.trinity/share/apps/konqueror/profiles.\n" + " # 'url' is an optional URL to open.\n\n").local8Bit()); + + puts(i18n(" kfmclient openProperties 'url'\n" + " # Opens a properties menu\n\n").local8Bit()); + puts(i18n(" kfmclient exec ['url' ['binding']]\n" + " # Tries to execute 'url'. 'url' may be a usual\n" + " # URL, this URL will be opened. You may omit\n" + " # 'binding'. In this case the default binding\n").local8Bit()); + puts(i18n(" # is tried. Of course URL may be the URL of a\n" + " # document, or it may be a *.desktop file.\n").local8Bit()); + puts(i18n(" # This way you could for example mount a device\n" + " # by passing 'Mount default' as binding to \n" + " # 'cdrom.desktop'\n\n").local8Bit()); + puts(i18n(" kfmclient move 'src' 'dest'\n" + " # Moves the URL 'src' to 'dest'.\n" + " # 'src' may be a list of URLs.\n").local8Bit()); + //puts(i18n(" # 'dest' may be \"trash:/\" to move the files\n" + // " # in the trash bin.\n\n").local8Bit()); + puts(i18n(" kfmclient download ['src']\n" + " # Copies the URL 'src' to a user specified location'.\n" + " # 'src' may be a list of URLs, if not present then\n" + " # a URL will be requested.\n\n").local8Bit()); + puts(i18n(" kfmclient copy 'src' 'dest'\n" + " # Copies the URL 'src' to 'dest'.\n" + " # 'src' may be a list of URLs.\n\n").local8Bit()); + puts(i18n(" kfmclient sortDesktop\n" + " # Rearranges all icons on the desktop.\n\n").local8Bit()); + puts(i18n(" kfmclient openBrowser\n" + " # Opens the system default Web browser.\n\n").local8Bit()); + puts(i18n(" kfmclient configure\n" + " # Re-read Konqueror's configuration.\n\n").local8Bit()); + puts(i18n(" kfmclient configureDesktop\n" + " # Re-read kdesktop's configuration.\n\n").local8Bit()); + + puts(i18n("*** Examples:\n" + " kfmclient exec file:/root/Desktop/cdrom.desktop \"Mount default\"\n" + " // Mounts the CD-ROM\n\n").local8Bit()); + puts(i18n(" kfmclient exec file:/home/weis/data/test.html\n" + " // Opens the file with default binding\n\n").local8Bit()); + puts(i18n(" kfmclient exec file:/home/weis/data/test.html Netscape\n" + " // Opens the file with netscape\n\n").local8Bit()); + puts(i18n(" kfmclient exec ftp://localhost/\n" + " // Opens new window with URL\n\n").local8Bit()); + puts(i18n(" kfmclient exec file:/root/Desktop/emacs.desktop\n" + " // Starts emacs\n\n").local8Bit()); + puts(i18n(" kfmclient exec file:/root/Desktop/cdrom.desktop\n" + " // Opens the CD-ROM's mount directory\n\n").local8Bit()); + puts(i18n(" kfmclient exec .\n" + " // Opens the current directory. Very convenient.\n\n").local8Bit()); + return 0; + } + + return clientApp::doIt() ? 0 /*no error*/ : 1 /*error*/; +} + +/* + Whether to start a new konqueror or reuse an existing process. + + First of all, this concept is actually broken, as the view used to show + the data may change at any time, and therefore Konqy reused to browse + "safe" data may eventually browse something completely different. + Moreover, it's quite difficult to find out when to reuse, and thus this + function is an ugly hack. You've been warned. + + Kfmclient will attempt to find an instance for reusing if either reusing + is configured to reuse always, + or it's not configured to never reuse, and the URL to-be-opened is "safe". + The URL is safe, if the view used to view it is listed in the allowed KPart's. + In order to find out the part, mimetype is needed, and TDETrader is needed. + If mimetype is not known, KMimeType is used (which doesn't work e.g. for remote + URLs, but oh well). Since this function may be running without a TDEApplication + instance, I'm actually quite surprised it works, and it may sooner or later break. + Nice, isn't it? + + If a profile is being used, and no url has been explicitly given, it needs to be + read from the profile. If there's more than one URL listed in the profile, no reusing + will be done (oh well), if there's no URL, no reusing will be done either (also + because the webbrowsing profile doesn't have any URL listed). +*/ +static bool startNewKonqueror( TQString url, TQString mimetype, const TQString& profile ) +{ + TDEConfig cfg( TQString::fromLatin1( "konquerorrc" ), true ); + cfg.setGroup( "Reusing" ); + TQStringList allowed_parts; + // is duplicated in ../KonquerorIface.cpp + allowed_parts << TQString::fromLatin1( "konq_iconview.desktop" ) + << TQString::fromLatin1( "konq_multicolumnview.desktop" ) + << TQString::fromLatin1( "konq_sidebartng.desktop" ) + << TQString::fromLatin1( "konq_infolistview.desktop" ) + << TQString::fromLatin1( "konq_treeview.desktop" ) + << TQString::fromLatin1( "konq_detailedlistview.desktop" ); + if( cfg.hasKey( "SafeParts" ) + && cfg.readEntry( "SafeParts" ) != TQString::fromLatin1( "SAFE" )) + allowed_parts = cfg.readListEntry( "SafeParts" ); + if( allowed_parts.count() == 1 && allowed_parts.first() == TQString::fromLatin1( "ALL" )) + return false; // all parts allowed + if( url.isEmpty()) + { + if( profile.isEmpty()) + return true; + TQString profilepath = locate( "data", TQString::fromLatin1("konqueror/profiles/") + profile ); + if( profilepath.isEmpty()) + return true; + TDEConfig cfg( profilepath, true ); + cfg.setDollarExpansion( true ); + cfg.setGroup( "Profile" ); + TQMap< TQString, TQString > entries = cfg.entryMap( TQString::fromLatin1( "Profile" )); + TQRegExp urlregexp( TQString::fromLatin1( "^View[0-9]*_URL$" )); + TQStringList urls; + for( TQMap< TQString, TQString >::ConstIterator it = entries.begin(); + it != entries.end(); + ++it ) + { + // don't read value from map, dollar expansion is needed + TQString value = cfg.readEntry( it.key()); + if( urlregexp.search( it.key()) >= 0 && !value.isEmpty()) + urls << value; + } + if( urls.count() != 1 ) + return true; + url = urls.first(); + mimetype = TQString::fromLatin1( "" ); + } + if( mimetype.isEmpty()) + mimetype = KMimeType::findByURL( KURL( url ) )->name(); + TDETrader::OfferList offers = TDETrader::self()->query( mimetype, TQString::fromLatin1( "KParts/ReadOnlyPart" ), + TQString::null, TQString::null ); + KService::Ptr serv; + if( offers.count() > 0 ) + serv = offers.first(); + return serv == NULL || !allowed_parts.contains( serv->desktopEntryName() + TQString::fromLatin1(".desktop") ); +} + +static int currentScreen() +{ + if( tqt_xdisplay() != NULL ) + return tqt_xscreen(); + // case when there's no TDEApplication instance + const char* env = getenv( "DISPLAY" ); + if( env == NULL ) + return 0; + const char* dotpos = strrchr( env, '.' ); + const char* colonpos = strrchr( env, ':' ); + if( dotpos != NULL && colonpos != NULL && dotpos > colonpos ) + return atoi( dotpos + 1 ); + return 0; +} + +// when reusing a preloaded konqy, make sure your always use a DCOP call which opens a profile ! +static TQCString getPreloadedKonqy() +{ + TDEConfig cfg( TQString::fromLatin1( "konquerorrc" ), true ); + cfg.setGroup( "Reusing" ); + if( cfg.readNumEntry( "MaxPreloadCount", 1 ) == 0 ) + return ""; + DCOPRef ref( "kded", "konqy_preloader" ); + TQCString ret; + if( ref.callExt( "getPreloadedKonqy", DCOPRef::NoEventLoop, 3000, currentScreen()).get( ret )) + return ret; + return TQCString(); +} + + +static TQCString konqyToReuse( const TQString& url, const TQString& mimetype, const TQString& profile ) +{ // prefer(?) preloaded ones + TQCString ret = getPreloadedKonqy(); + if( !ret.isEmpty()) + return ret; + if( startNewKonqueror( url, mimetype, profile )) + return ""; + TQCString appObj; + TQByteArray data; + TQDataStream str( data, IO_WriteOnly ); + str << currentScreen(); + if( !TDEApplication::dcopClient()->findObject( "konqueror*", "KonquerorIface", + "processCanBeReused( int )", data, ret, appObj, false, 3000 ) ) + return ""; + return ret; +} + +static bool krun_has_error = false; + +void clientApp::sendASNChange() +{ + TDEStartupInfoId id; + id.initId( startup_id_str ); + TDEStartupInfoData data; + data.addPid( 0 ); // say there's another process for this ASN with unknown PID + data.setHostname(); // ( no need to bother to get this konqy's PID ) + Display* dpy = tqt_xdisplay(); + if( dpy == NULL ) // we may be running without TQApplication here + dpy = XOpenDisplay( NULL ); + if( dpy != NULL ) + TDEStartupInfo::sendChangeX( dpy, id, data ); + if( dpy != NULL && dpy != tqt_xdisplay()) + XCloseDisplay( dpy ); +} + +bool clientApp::createNewWindow(const KURL & url, bool newTab, bool tempFile, const TQString & mimetype) +{ + kdDebug( 1202 ) << "clientApp::createNewWindow " << url.url() << " mimetype=" << mimetype << endl; + // check if user wants to use external browser + // ###### this option seems to have no GUI and to be redundant with BrowserApplication now. + // ###### KDE4: remove + TDEConfig config( TQString::fromLatin1("kfmclientrc")); + config.setGroup( TQString::fromLatin1("Settings")); + TQString strBrowser = config.readPathEntry("ExternalBrowser"); + if (!strBrowser.isEmpty()) + { + if ( tempFile ) + kdWarning() << "kfmclient used with --tempfile but is passing to an external browser! Tempfile will never be deleted" << endl; + TDEProcess proc; + proc << strBrowser << url.url(); + proc.start( TDEProcess::DontCare ); + return true; + } + + if (url.protocol().startsWith(TQString::fromLatin1("http"))) + { + config.setGroup("General"); + if (!config.readEntry("BrowserApplication").isEmpty()) + { + clientApp app; + TDEStartupInfo::appStarted(); + + KRun * run = new KRun( url, 0, 0, false, false /* no progress window */ ); // TODO pass tempFile [needs support in the KRun ctor] + TQObject::connect( run, TQT_SIGNAL( finished() ), &app, TQT_SLOT( delayedQuit() )); + TQObject::connect( run, TQT_SIGNAL( error() ), &app, TQT_SLOT( delayedQuit() )); + app.exec(); + return !krun_has_error; + } + } + + TDEConfig cfg( TQString::fromLatin1( "konquerorrc" ), true ); + cfg.setGroup( "FMSettings" ); + if ( newTab || cfg.readBoolEntry( "KonquerorTabforExternalURL", false ) ) + { + TQCString foundApp, foundObj; + TQByteArray data; + TQDataStream str( data, IO_WriteOnly ); + if( TDEApplication::dcopClient()->findObject( "konqueror*", "konqueror-mainwindow*", + "windowCanBeUsedForTab()", data, foundApp, foundObj, false, 3000 ) ) + { + DCOPRef ref( foundApp, foundObj ); + DCOPReply reply = ref.call( "newTabASN", url.url(), startup_id_str, tempFile ); + if ( reply.isValid() ) { + sendASNChange(); + return true; + } + } + } + + TQCString appId = konqyToReuse( url.url(), mimetype, TQString::null ); + if( !appId.isEmpty()) + { + kdDebug( 1202 ) << "clientApp::createNewWindow using existing konqueror" << endl; + KonquerorIface_stub konqy( appId, "KonquerorIface" ); + konqy.createNewWindowASN( url.url(), mimetype, startup_id_str, tempFile ); + sendASNChange(); + } + else + { + TQString error; + /* Well, we can't pass a mimetype through startServiceByDesktopPath ! + if ( TDEApplication::startServiceByDesktopPath( TQString::fromLatin1("konqueror.desktop"), + url.url(), &error ) > 0 ) + { + kdError() << "Couldn't start konqueror from konqueror.desktop: " << error << endl; + */ + // pass kfmclient's startup id to konqueror using kshell + TDEStartupInfoId id; + id.initId( startup_id_str ); + id.setupStartupEnv(); + TDEProcess proc; + proc << "kshell" << "konqueror"; + if ( !mimetype.isEmpty() ) + proc << "-mimetype" << mimetype; + if ( tempFile ) + proc << "-tempfile"; + proc << url.url(); + proc.start( TDEProcess::DontCare ); + TDEStartupInfo::resetStartupEnv(); + kdDebug( 1202 ) << "clientApp::createNewWindow TDEProcess started" << endl; + //} + } + return true; +} + +bool clientApp::openProfile( const TQString & profileName, const TQString & url, const TQString & mimetype ) +{ + TQCString appId = konqyToReuse( url, mimetype, profileName ); + if( appId.isEmpty()) + { + TQString error; + if ( TDEApplication::startServiceByDesktopPath( TQString::fromLatin1("konqueror.desktop"), + TQString::fromLatin1("--silent"), &error, &appId, NULL, startup_id_str ) > 0 ) + { + kdError() << "Couldn't start konqueror from konqueror.desktop: " << error << endl; + return false; + } + // startServiceByDesktopPath waits for the app to register with DCOP + // so when we arrive here, konq is up and running already, and appId contains the identification + } + + TQString profile = locate( "data", TQString::fromLatin1("konqueror/profiles/") + profileName ); + if ( profile.isEmpty() ) + { + fprintf( stderr, "%s", i18n("Profile %1 not found\n").arg(profileName).local8Bit().data() ); + ::exit( 0 ); + } + KonquerorIface_stub konqy( appId, "KonquerorIface" ); + if ( url.isEmpty() ) + konqy.createBrowserWindowFromProfileASN( profile, profileName, startup_id_str ); + else if ( mimetype.isEmpty() ) + konqy.createBrowserWindowFromProfileAndURLASN( profile, profileName, url, startup_id_str ); + else + konqy.createBrowserWindowFromProfileAndURLASN( profile, profileName, url, mimetype, startup_id_str ); + sleep(2); // Martin Schenk says this is necessary to let the server read from the socket + sendASNChange(); + return true; +} + +void clientApp::delayedQuit() +{ + // Quit in 2 seconds. This leaves time for KRun to pop up + // "app not found" in TDEProcessRunner, if that was the case. + TQTimer::singleShot( 2000, this, TQT_SLOT(deref()) ); + // don't access the KRun instance later, it will be deleted after calling slots + if( static_cast< const KRun* >( sender())->hasError()) + krun_has_error = true; +} + +static void checkArgumentCount(int count, int min, int max) +{ + if (count < min) + { + fputs( i18n("Syntax Error: Not enough arguments\n").local8Bit(), stderr ); + ::exit(1); + } + if (max && (count > max)) + { + fputs( i18n("Syntax Error: Too many arguments\n").local8Bit(), stderr ); + ::exit(1); + } +} + +bool clientApp::doIt() +{ + TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs(); + int argc = args->count(); + checkArgumentCount(argc, 1, 0); + + if ( !args->isSet( "ninteractive" ) ) { + s_interactive = false; + } + TQCString command = args->arg(0); + + // read ASN env. variable for non-KApp cases + startup_id_str = TDEStartupInfo::currentStartupIdEnv().id(); + + if ( command == "openURL" || command == "newTab" ) + { + TDEInstance inst(appName); + if( !TDEApplication::dcopClient()->attach()) + { + TDEApplication::startKdeinit(); + TDEApplication::dcopClient()->attach(); + } + checkArgumentCount(argc, 1, 3); + bool tempFile = TDECmdLineArgs::isTempFileSet(); + if ( argc == 1 ) + { + KURL url; + url.setPath(TQDir::homeDirPath()); + return createNewWindow( url, command == "newTab", tempFile ); + } + if ( argc == 2 ) + { + return createNewWindow( args->url(1), command == "newTab", tempFile ); + } + if ( argc == 3 ) + { + return createNewWindow( args->url(1), command == "newTab", tempFile, TQString::fromLatin1(args->arg(2)) ); + } + } + else if ( command == "openProfile" ) + { + TDEInstance inst(appName); + if( !TDEApplication::dcopClient()->attach()) + { + TDEApplication::startKdeinit(); + TDEApplication::dcopClient()->attach(); + } + checkArgumentCount(argc, 2, 3); + TQString url; + if ( argc == 3 ) + url = args->url(2).url(); + return openProfile( TQString::fromLocal8Bit(args->arg(1)), url ); + } + + // the following commands need TDEApplication + clientApp app; + + if ( command == "openProperties" ) + { + checkArgumentCount(argc, 2, 2); + KPropertiesDialog * p = new KPropertiesDialog( args->url(1) ); + TQObject::connect( p, TQT_SIGNAL( destroyed() ), &app, TQT_SLOT( quit() )); + TQObject::connect( p, TQT_SIGNAL( canceled() ), &app, TQT_SLOT( slotDialogCanceled() )); + app.exec(); + return m_ok; + } + else if ( command == "exec" ) + { + checkArgumentCount(argc, 1, 3); + if ( argc == 1 ) + { + KDesktopIface_stub kdesky( "kdesktop", "KDesktopIface" ); + kdesky.popupExecuteCommand(); + } + else if ( argc == 2 ) + { + KRun * run = new KRun( args->url(1), 0, 0, false, false /* no progress window */ ); + TQObject::connect( run, TQT_SIGNAL( finished() ), &app, TQT_SLOT( delayedQuit() )); + TQObject::connect( run, TQT_SIGNAL( error() ), &app, TQT_SLOT( delayedQuit() )); + app.exec(); + return !krun_has_error; + } + else if ( argc == 3 ) + { + KURL::List urls; + urls.append( args->url(1) ); + const TDETrader::OfferList offers = TDETrader::self()->query( TQString::fromLocal8Bit( args->arg( 2 ) ), TQString::fromLatin1( "Application" ), TQString::null, TQString::null ); + if (offers.isEmpty()) return 1; + KService::Ptr serv = offers.first(); + return KRun::run( *serv, urls ); + } + } + else if ( command == "openBrowser" ) + { + KRun * run = new KRun( "http://default.browser", 0, 0, false, false /* no progress window */ ); + TQObject::connect( run, TQT_SIGNAL( finished() ), &app, TQT_SLOT( delayedQuit() )); + TQObject::connect( run, TQT_SIGNAL( error() ), &app, TQT_SLOT( delayedQuit() )); + app.exec(); + return !krun_has_error; + } + else if ( command == "move" ) + { + checkArgumentCount(argc, 2, 0); + KURL::List srcLst; + for ( int i = 1; i <= argc - 2; i++ ) + srcLst.append( args->url(i) ); + + TDEIO::Job * job = TDEIO::move( srcLst, args->url(argc - 1) ); + if ( !s_interactive ) + job->setInteractive( false ); + connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ), &app, TQT_SLOT( slotResult( TDEIO::Job * ) ) ); + app.exec(); + return m_ok; + } + else if ( command == "download" ) + { + checkArgumentCount(argc, 0, 0); + KURL::List srcLst; + if (argc == 1) { + while(true) { + KURL src = KURLRequesterDlg::getURL(); + if (!src.isEmpty()) { + if (!src.isValid()) { + KMessageBox::error(0, i18n("Unable to download from an invalid URL.")); + continue; + } + srcLst.append(src); + } + break; + } + } else { + for ( int i = 1; i <= argc - 1; i++ ) + srcLst.append( args->url(i) ); + } + if (srcLst.count() == 0) + return m_ok; + TQString dst = + KFileDialog::getSaveFileName( (argc<2) ? (TQString::null) : (args->url(1).filename()) ); + if (dst.isEmpty()) // cancelled + return m_ok; // AK - really okay? + KURL dsturl; + dsturl.setPath( dst ); + TDEIO::Job * job = TDEIO::copy( srcLst, dsturl ); + if ( !s_interactive ) + job->setInteractive( false ); + connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ), &app, TQT_SLOT( slotResult( TDEIO::Job * ) ) ); + app.exec(); + return m_ok; + } + else if ( command == "copy" ) + { + checkArgumentCount(argc, 2, 0); + KURL::List srcLst; + for ( int i = 1; i <= argc - 2; i++ ) + srcLst.append( args->url(i) ); + + TDEIO::Job * job = TDEIO::copy( srcLst, args->url(argc - 1) ); + if ( !s_interactive ) + job->setInteractive( false ); + connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ), &app, TQT_SLOT( slotResult( TDEIO::Job * ) ) ); + app.exec(); + return m_ok; + } + else if ( command == "sortDesktop" ) + { + checkArgumentCount(argc, 1, 1); + + KDesktopIface_stub kdesky( "kdesktop", "KDesktopIface" ); + kdesky.rearrangeIcons( (int)false ); + + return true; + } + else if ( command == "configure" ) + { + checkArgumentCount(argc, 1, 1); + TQByteArray data; + kapp->dcopClient()->send( "*", "KonqMainViewIface", "reparseConfiguration()", data ); + // Warning. In case something is added/changed here, keep kcontrol/konq/main.cpp in sync. + } + else if ( command == "configureDesktop" ) + { + checkArgumentCount(argc, 1, 1); + KDesktopIface_stub kdesky( "kdesktop", "KDesktopIface" ); + kdesky.configure(); + } + else + { + fprintf( stderr, "%s", i18n("Syntax Error: Unknown command '%1'\n").arg(TQString::fromLocal8Bit(command)).local8Bit().data() ); + return false; + } + return true; +} + +void clientApp::slotResult( TDEIO::Job * job ) +{ + if (job->error() && s_interactive) + job->showErrorDialog(); + m_ok = !job->error(); + quit(); +} + +void clientApp::slotDialogCanceled() +{ + m_ok = false; + quit(); +} + +#include "kfmclient.moc" diff --git a/konqueror/delayedinitializer.cc b/konqueror/delayedinitializer.cc deleted file mode 100644 index e30db3d21..000000000 --- a/konqueror/delayedinitializer.cc +++ /dev/null @@ -1,52 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2003 Simon Hausmann - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - - -#include "delayedinitializer.h" -#include - -DelayedInitializer::DelayedInitializer( int eventType, TQObject *parent, const char *name ) - : TQObject( parent, name ), m_eventType( eventType ), m_signalEmitted( false ) -{ - parent->installEventFilter( this ); -} - -bool DelayedInitializer::eventFilter( TQObject *receiver, TQEvent *event ) -{ - if ( m_signalEmitted || event->type() != m_eventType ) - return false; - - m_signalEmitted = true; - receiver->removeEventFilter( this ); - - // Move the emitting of the event to the end of the eventQueue - // so we are absolutely sure the event we get here is handled before - // the initialize is fired. - TQTimer::singleShot( 0, this, TQT_SLOT( slotInitialize() ) ); - - return false; -} - -void DelayedInitializer::slotInitialize() -{ - emit initialize(); - deleteLater(); -} - -#include "delayedinitializer.moc" diff --git a/konqueror/delayedinitializer.cpp b/konqueror/delayedinitializer.cpp new file mode 100644 index 000000000..e30db3d21 --- /dev/null +++ b/konqueror/delayedinitializer.cpp @@ -0,0 +1,52 @@ +/* This file is part of the KDE project + Copyright (C) 2003 Simon Hausmann + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + + +#include "delayedinitializer.h" +#include + +DelayedInitializer::DelayedInitializer( int eventType, TQObject *parent, const char *name ) + : TQObject( parent, name ), m_eventType( eventType ), m_signalEmitted( false ) +{ + parent->installEventFilter( this ); +} + +bool DelayedInitializer::eventFilter( TQObject *receiver, TQEvent *event ) +{ + if ( m_signalEmitted || event->type() != m_eventType ) + return false; + + m_signalEmitted = true; + receiver->removeEventFilter( this ); + + // Move the emitting of the event to the end of the eventQueue + // so we are absolutely sure the event we get here is handled before + // the initialize is fired. + TQTimer::singleShot( 0, this, TQT_SLOT( slotInitialize() ) ); + + return false; +} + +void DelayedInitializer::slotInitialize() +{ + emit initialize(); + deleteLater(); +} + +#include "delayedinitializer.moc" diff --git a/konqueror/iconview/CMakeLists.txt b/konqueror/iconview/CMakeLists.txt index e88884b47..f308f226a 100644 --- a/konqueror/iconview/CMakeLists.txt +++ b/konqueror/iconview/CMakeLists.txt @@ -39,7 +39,7 @@ install( FILES konq_iconview.rc konq_multicolumnview.rc DESTINATION ${DATA_INSTA set( target konq_iconview ) tde_add_kpart( ${target} AUTOMOC - SOURCES konq_iconview.cc + SOURCES konq_iconview.cpp LINK konq-shared DESTINATION ${PLUGIN_INSTALL_DIR} ) diff --git a/konqueror/iconview/Makefile.am b/konqueror/iconview/Makefile.am index bc685d997..34b4f31a8 100644 --- a/konqueror/iconview/Makefile.am +++ b/konqueror/iconview/Makefile.am @@ -5,7 +5,7 @@ kde_module_LTLIBRARIES = konq_iconview.la METASOURCES = AUTO -konq_iconview_la_SOURCES = konq_iconview.cc +konq_iconview_la_SOURCES = konq_iconview.cpp konq_iconview_la_LDFLAGS = $(all_libraries) $(KDE_PLUGIN) -module konq_iconview_la_LIBADD = $(top_builddir)/libkonq/libkonq.la diff --git a/konqueror/iconview/konq_iconview.cc b/konqueror/iconview/konq_iconview.cc deleted file mode 100644 index 5efc1e751..000000000 --- a/konqueror/iconview/konq_iconview.cc +++ /dev/null @@ -1,1660 +0,0 @@ -/* This file is part of the KDE projects - Copyright (C) 1998, 1999 Torben Weis - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "konq_iconview.h" -#include "konq_propsview.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include - -template class TQPtrList; -//template class TQValueList; - -class KonqIconViewFactory : public KParts::Factory -{ -public: - KonqIconViewFactory() - { - s_defaultViewProps = 0; - s_instance = 0; - } - - virtual ~KonqIconViewFactory() - { - if ( s_instance ) - delete s_instance; - - if ( s_defaultViewProps ) - delete s_defaultViewProps; - - s_instance = 0; - s_defaultViewProps = 0; - } - - virtual KParts::Part* createPartObject( TQWidget *parentWidget, const char *, - TQObject *parent, const char *name, const char*, const TQStringList &args ) - { - if( args.count() < 1 ) - kdWarning() << "KonqKfmIconView: Missing Parameter" << endl; - - KonqKfmIconView *obj = new KonqKfmIconView( parentWidget, parent, name,args.first() ); - return obj; - } - - static TDEInstance *instance() - { - if ( !s_instance ) - s_instance = new TDEInstance( "konqiconview" ); - return s_instance; - } - - static KonqPropsView *defaultViewProps() - { - if ( !s_defaultViewProps ) - s_defaultViewProps = new KonqPropsView( instance(), 0L ); - - return s_defaultViewProps; - } - - private: - static TDEInstance *s_instance; - static KonqPropsView *s_defaultViewProps; -}; - -TDEInstance *KonqIconViewFactory::s_instance = 0; -KonqPropsView *KonqIconViewFactory::s_defaultViewProps = 0; - - -K_EXPORT_COMPONENT_FACTORY( konq_iconview, KonqIconViewFactory ) - - -IconViewBrowserExtension::IconViewBrowserExtension( KonqKfmIconView *iconView ) - : KonqDirPartBrowserExtension( iconView ) -{ - m_iconView = iconView; - m_bSaveViewPropertiesLocally = false; -} - -int IconViewBrowserExtension::xOffset() -{ - return m_iconView->iconViewWidget()->contentsX(); -} - -int IconViewBrowserExtension::yOffset() -{ - return m_iconView->iconViewWidget()->contentsY(); -} - -void IconViewBrowserExtension::reparseConfiguration() -{ - KonqFMSettings::reparseConfiguration(); - // m_pProps is a problem here (what is local, what is global ?) - // but settings is easy : - if ( m_iconView->iconViewWidget()->initConfig( false ) ) - m_iconView->iconViewWidget()->arrangeItemsInGrid(); // called if the font changed. -} - -void IconViewBrowserExtension::trash() -{ - KonqOperations::del(m_iconView->iconViewWidget(), - KonqOperations::TRASH, - m_iconView->iconViewWidget()->selectedUrls( KonqIconViewWidget::MostLocalUrls )); -} - -void IconViewBrowserExtension::properties() -{ - (void) new KPropertiesDialog( m_iconView->iconViewWidget()->selectedFileItems() ); -} - -void IconViewBrowserExtension::editMimeType() -{ - KFileItem * item = m_iconView->iconViewWidget()->selectedFileItems().first(); - KonqOperations::editMimeType( item->mimetype() ); -} - -void IconViewBrowserExtension::setSaveViewPropertiesLocally( bool value ) -{ - m_iconView->m_pProps->setSaveViewPropertiesLocally( value ); -} - -void IconViewBrowserExtension::setNameFilter( const TQString &nameFilter ) -{ - //kdDebug(1202) << "IconViewBrowserExtension::setNameFilter " << nameFilter << endl; - m_iconView->m_nameFilter = nameFilter; -} - -KonqKfmIconView::KonqKfmIconView( TQWidget *parentWidget, TQObject *parent, const char *name, const TQString& mode ) - : KonqDirPart( parent, name ) - , m_bNeedSetCurrentItem( false ) - , m_pEnsureVisible( 0 ) - , m_paOutstandingOverlaysTimer( 0 ) - , m_paOutstandingFreeSpaceOverlaysTimer( 0 ) - , m_pTimeoutRefreshTimer( 0 ) - , m_itemDict( 43 ) -{ - kdDebug(1202) << "+KonqKfmIconView" << endl; - - setBrowserExtension( new IconViewBrowserExtension( this ) ); - - // Create a properties instance for this view - m_pProps = new KonqPropsView( KonqIconViewFactory::instance(), KonqIconViewFactory::defaultViewProps() ); - - m_pIconView = new KonqIconViewWidget( parentWidget, "qiconview" ); - m_pIconView->initConfig( true ); - - connect( m_pIconView, TQT_SIGNAL(imagePreviewFinished()), - this, TQT_SLOT(slotRenderingFinished())); - - // connect up the icon inc/dec signals - connect( m_pIconView, TQT_SIGNAL(incIconSize()), - this, TQT_SLOT(slotIncIconSize())); - connect( m_pIconView, TQT_SIGNAL(decIconSize()), - this, TQT_SLOT(slotDecIconSize())); - - // pass signals to the extension - connect( m_pIconView, TQT_SIGNAL( enableAction( const char *, bool ) ), - m_extension, TQT_SIGNAL( enableAction( const char *, bool ) ) ); - - // signals from konqdirpart (for BC reasons) - connect( this, TQT_SIGNAL( findOpened( KonqDirPart * ) ), TQT_SLOT( slotKFindOpened() ) ); - connect( this, TQT_SIGNAL( findClosed( KonqDirPart * ) ), TQT_SLOT( slotKFindClosed() ) ); - - setWidget( m_pIconView ); - m_mimeTypeResolver = new KMimeTypeResolver(this); - - setInstance( KonqIconViewFactory::instance() ); - - setXMLFile( "konq_iconview.rc" ); - - // Don't repaint on configuration changes during construction - m_bInit = true; - - m_paDotFiles = new TDEToggleAction( i18n( "Show &Hidden Files" ), 0, this, TQT_SLOT( slotShowDot() ), - actionCollection(), "show_dot" ); -// m_paDotFiles->setCheckedState(i18n("Hide &Hidden Files")); - m_paDotFiles->setToolTip( i18n( "Toggle displaying of hidden dot files" ) ); - - m_paDirectoryOverlays = new TDEToggleAction( i18n( "&Folder Icons Reflect Contents" ), 0, this, TQT_SLOT( slotShowDirectoryOverlays() ), - actionCollection(), "show_directory_overlays" ); - - m_paFreeSpaceOverlays = new TDEToggleAction( i18n( "&Media Icons Reflect Free Space" ), 0, this, TQT_SLOT( slotShowFreeSpaceOverlays() ), - actionCollection(), "show_free_space_overlays" ); - - m_pamPreview = new TDEActionMenu( i18n( "&Preview" ), actionCollection(), "iconview_preview" ); - - m_paEnablePreviews = new TDEToggleAction( i18n("Enable Previews"), 0, actionCollection(), "iconview_preview_all" ); - m_paEnablePreviews->setCheckedState( i18n("Disable Previews") ); - connect( m_paEnablePreviews, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotPreview( bool ) ) ); - m_paEnablePreviews->setIcon("thumbnail"); - m_pamPreview->insert( m_paEnablePreviews ); - m_pamPreview->insert( new TDEActionSeparator(this) ); - - TDETrader::OfferList plugins = TDETrader::self()->query( "ThumbCreator" ); - TQMap< TQString, TDEToggleAction* > previewActions; - for ( TDETrader::OfferList::ConstIterator it = plugins.begin(); it != plugins.end(); ++it ) - { - if ( TDEToggleAction*& preview = previewActions[ ( *it )->name() ] ) - preview->setName( TQCString( preview->name() ) + ',' + ( *it )->desktopEntryName().latin1() ); - else - { - preview = new TDEToggleAction( (*it)->name(), 0, actionCollection(), (*it)->desktopEntryName().latin1() ); - connect( preview, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotPreview( bool ) ) ); - m_pamPreview->insert( preview ); - m_paPreviewPlugins.append( preview ); - } - } - TDEToggleAction *soundPreview = new TDEToggleAction( i18n("Sound Files"), 0, actionCollection(), "audio/" ); - connect( soundPreview, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotPreview( bool ) ) ); - m_pamPreview->insert( soundPreview ); - m_paPreviewPlugins.append( soundPreview ); - - // m_pamSort = new TDEActionMenu( i18n( "Sort..." ), actionCollection(), "sort" ); - - TDEToggleAction *aSortByNameCS = new TDERadioAction( i18n( "By Name (Case Sensitive)" ), 0, actionCollection(), "sort_nc" ); - TDEToggleAction *aSortByNameCI = new TDERadioAction( i18n( "By Name (Case Insensitive)" ), 0, actionCollection(), "sort_nci" ); - TDEToggleAction *aSortBySize = new TDERadioAction( i18n( "By Size" ), 0, actionCollection(), "sort_size" ); - TDEToggleAction *aSortByType = new TDERadioAction( i18n( "By Type" ), 0, actionCollection(), "sort_type" ); - TDEToggleAction *aSortByDate = new TDERadioAction( i18n( "By Date" ), 0, actionCollection(), "sort_date" ); - - aSortByNameCS->setExclusiveGroup( "sorting" ); - aSortByNameCI->setExclusiveGroup( "sorting" ); - aSortBySize->setExclusiveGroup( "sorting" ); - aSortByType->setExclusiveGroup( "sorting" ); - aSortByDate->setExclusiveGroup( "sorting" ); - - aSortByNameCS->setChecked( false ); - aSortByNameCI->setChecked( false ); - aSortBySize->setChecked( false ); - aSortByType->setChecked( false ); - aSortByDate->setChecked( false ); - - connect( aSortByNameCS, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotSortByNameCaseSensitive( bool ) ) ); - connect( aSortByNameCI, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotSortByNameCaseInsensitive( bool ) ) ); - connect( aSortBySize, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotSortBySize( bool ) ) ); - connect( aSortByType, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotSortByType( bool ) ) ); - connect( aSortByDate, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotSortByDate( bool ) ) ); - - //enable menu item representing the saved sorting criterion - TQString sortcrit = KonqIconViewFactory::defaultViewProps()->sortCriterion(); - TDERadioAction *sort_action = tqt_dynamic_cast(actionCollection()->action(sortcrit.latin1())); - if(sort_action!=NULL) sort_action->activate(); - - m_paSortDirsFirst = new TDEToggleAction( i18n( "Folders First" ), 0, actionCollection(), "sort_directoriesfirst" ); - TDEToggleAction *aSortDescending = new TDEToggleAction( i18n( "Descending" ), 0, actionCollection(), "sort_descend" ); - - m_paSortDirsFirst->setChecked( KonqIconViewFactory::defaultViewProps()->isDirsFirst() ); - - connect( aSortDescending, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotSortDescending() ) ); - connect( m_paSortDirsFirst, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotSortDirsFirst() ) ); - - //enable stored settings - slotSortDirsFirst(); - if (KonqIconViewFactory::defaultViewProps()->isDescending()) - { - aSortDescending->setChecked(true); - m_pIconView->setSorting(true,true);//enable sort ascending in QIconview - slotSortDescending();//invert sorting (now descending) and actually resort items - } - - /* - m_pamSort->insert( aSortByNameCS ); - m_pamSort->insert( aSortByNameCI ); - m_pamSort->insert( aSortBySize ); - - m_pamSort->popupMenu()->insertSeparator(); - - m_pamSort->insert( aSortDescending ); - */ - m_paSelect = new TDEAction( i18n( "Se&lect..." ), CTRL+Key_Plus, this, TQT_SLOT( slotSelect() ), - actionCollection(), "select" ); - m_paUnselect = new TDEAction( i18n( "Unselect..." ), CTRL+Key_Minus, this, TQT_SLOT( slotUnselect() ), - actionCollection(), "unselect" ); - m_paSelectAll = KStdAction::selectAll( this, TQT_SLOT( slotSelectAll() ), actionCollection(), "selectall" ); - m_paUnselectAll = new TDEAction( i18n( "Unselect All" ), CTRL+Key_U, this, TQT_SLOT( slotUnselectAll() ), - actionCollection(), "unselectall" ); - m_paInvertSelection = new TDEAction( i18n( "&Invert Selection" ), CTRL+Key_Asterisk, - this, TQT_SLOT( slotInvertSelection() ), - actionCollection(), "invertselection" ); - - m_paSelect->setToolTip( i18n( "Allows selecting of file or folder items based on a given mask" ) ); - m_paUnselect->setToolTip( i18n( "Allows unselecting of file or folder items based on a given mask" ) ); - m_paSelectAll->setToolTip( i18n( "Selects all items" ) ); - m_paUnselectAll->setToolTip( i18n( "Unselects all selected items" ) ); - m_paInvertSelection->setToolTip( i18n( "Inverts the current selection of items" ) ); - - //m_paBottomText = new TDEToggleAction( i18n( "Text at &Bottom" ), 0, actionCollection(), "textbottom" ); - //m_paRightText = new TDEToggleAction( i18n( "Text at &Right" ), 0, actionCollection(), "textright" ); - //m_paBottomText->setExclusiveGroup( "TextPos" ); - //m_paRightText->setExclusiveGroup( "TextPos" ); - //connect( m_paBottomText, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotTextBottom( bool ) ) ); - //connect( m_paRightText, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotTextRight( bool ) ) ); - - connect( m_pIconView, TQT_SIGNAL( executed( TQIconViewItem * ) ), - this, TQT_SLOT( slotReturnPressed( TQIconViewItem * ) ) ); - connect( m_pIconView, TQT_SIGNAL( returnPressed( TQIconViewItem * ) ), - this, TQT_SLOT( slotReturnPressed( TQIconViewItem * ) ) ); - - connect( m_pIconView, TQT_SIGNAL( onItem( TQIconViewItem * ) ), - this, TQT_SLOT( slotOnItem( TQIconViewItem * ) ) ); - - connect( m_pIconView, TQT_SIGNAL( onViewport() ), - this, TQT_SLOT( slotOnViewport() ) ); - - connect( m_pIconView, TQT_SIGNAL( mouseButtonPressed(int, TQIconViewItem*, const TQPoint&)), - this, TQT_SLOT( slotMouseButtonPressed(int, TQIconViewItem*, const TQPoint&)) ); - connect( m_pIconView, TQT_SIGNAL( mouseButtonClicked(int, TQIconViewItem*, const TQPoint&)), - this, TQT_SLOT( slotMouseButtonClicked(int, TQIconViewItem*, const TQPoint&)) ); - connect( m_pIconView, TQT_SIGNAL( contextMenuRequested(TQIconViewItem*, const TQPoint&)), - this, TQT_SLOT( slotContextMenuRequested(TQIconViewItem*, const TQPoint&)) ); - connect( m_pIconView, TQT_SIGNAL( mouseDoubleClicked(TQIconViewItem*)), - this, TQT_SLOT( slotDoubleClicked(TQIconViewItem*)) ); - - // Signals needed to implement the spring loading folders behavior - connect( m_pIconView, TQT_SIGNAL( held( TQIconViewItem * ) ), - this, TQT_SLOT( slotDragHeld( TQIconViewItem * ) ) ); - connect( m_pIconView, TQT_SIGNAL( dragEntered( bool ) ), - this, TQT_SLOT( slotDragEntered( bool ) ) ); - connect( m_pIconView, TQT_SIGNAL( dragLeft() ), - this, TQT_SLOT( slotDragLeft() ) ); - connect( m_pIconView, TQT_SIGNAL( dragMove( bool ) ), - this, TQT_SLOT( slotDragMove( bool ) ) ); - connect( m_pIconView, TQT_SIGNAL( dragFinished() ), - this, TQT_SLOT( slotDragFinished() ) ); - - // Create the directory lister - m_dirLister = new KDirLister( true ); - setDirLister( m_dirLister ); - m_dirLister->setMainWindow(m_pIconView->topLevelWidget()); - - connect( m_dirLister, TQT_SIGNAL( started( const KURL & ) ), - this, TQT_SLOT( slotStarted() ) ); - connect( m_dirLister, TQT_SIGNAL( completed() ), this, TQT_SLOT( slotCompleted() ) ); - connect( m_dirLister, TQT_SIGNAL( canceled( const KURL& ) ), this, TQT_SLOT( slotCanceled( const KURL& ) ) ); - connect( m_dirLister, TQT_SIGNAL( clear() ), this, TQT_SLOT( slotClear() ) ); - connect( m_dirLister, TQT_SIGNAL( newItems( const KFileItemList& ) ), - this, TQT_SLOT( slotNewItems( const KFileItemList& ) ) ); - connect( m_dirLister, TQT_SIGNAL( deleteItem( KFileItem * ) ), - this, TQT_SLOT( slotDeleteItem( KFileItem * ) ) ); - connect( m_dirLister, TQT_SIGNAL( refreshItems( const KFileItemList& ) ), - this, TQT_SLOT( slotRefreshItems( const KFileItemList& ) ) ); - connect( m_dirLister, TQT_SIGNAL( redirection( const KURL & ) ), - this, TQT_SLOT( slotRedirection( const KURL & ) ) ); - connect( m_dirLister, TQT_SIGNAL( itemsFilteredByMime(const KFileItemList& ) ), - TQT_SIGNAL( itemsFilteredByMime(const KFileItemList& ) ) ); - connect( m_dirLister, TQT_SIGNAL( infoMessage( const TQString& ) ), - extension(), TQT_SIGNAL( infoMessage( const TQString& ) ) ); - connect( m_dirLister, TQT_SIGNAL( percent( int ) ), - extension(), TQT_SIGNAL( loadingProgress( int ) ) ); - connect( m_dirLister, TQT_SIGNAL( speed( int ) ), - extension(), TQT_SIGNAL( speedProgress( int ) ) ); - - // Now we may react to configuration changes - m_bInit = false; - - m_bLoading = true; - m_bNeedAlign = false; - m_bNeedEmitCompleted = false; - m_bUpdateContentsPosAfterListing = false; - m_bDirPropertiesChanged = true; - m_bPreviewRunningBeforeCloseURL = false; - m_pIconView->setResizeMode( TQIconView::Adjust ); - - connect( m_pIconView, TQT_SIGNAL( selectionChanged() ), - this, TQT_SLOT( slotSelectionChanged() ) ); - - // Respect kcmkonq's configuration for word-wrap icon text. - // If we want something else, we have to adapt the configuration or remove it... - m_pIconView->setIconTextHeight(KonqFMSettings::settings()->iconTextHeight()); - - // Finally, determine initial grid size again, with those parameters - // m_pIconView->calculateGridX(); - - setViewMode( mode ); -} - -KonqKfmIconView::~KonqKfmIconView() -{ - // Before anything else, stop the image preview. It might use our fileitems, - // and it will only be destroyed togetierh with our widget - m_pIconView->stopImagePreview(); - - kdDebug(1202) << "-KonqKfmIconView" << endl; - m_dirLister->disconnect( this ); - delete m_dirLister; - delete m_mimeTypeResolver; - delete m_pProps; - //no need for that, KParts deletes our widget already ;-) - // delete m_pIconView; -} - -const KFileItem * KonqKfmIconView::currentItem() -{ - return m_pIconView->currentItem() ? static_cast(m_pIconView->currentItem())->item() : 0L; -} - -void KonqKfmIconView::slotPreview( bool toggle ) -{ - TQCString name = TQT_TQOBJECT_CONST(sender())->name(); // e.g. clipartthumbnail (or audio/, special case) - if (name == "iconview_preview_all") - { - m_pProps->setShowingPreview( toggle ); - m_pIconView->setPreviewSettings( m_pProps->previewSettings() ); - if ( !toggle ) - { - kdDebug() << "KonqKfmIconView::slotPreview stopping all previews for " << name << endl; - m_pIconView->disableSoundPreviews(); - - bool previewRunning = m_pIconView->isPreviewRunning(); - if ( previewRunning ) - m_pIconView->stopImagePreview(); - m_pIconView->setIcons( m_pIconView->iconSize(), "*" ); - } - else - { - m_pIconView->startImagePreview( m_pProps->previewSettings(), true ); - } - for ( m_paPreviewPlugins.first(); m_paPreviewPlugins.current(); m_paPreviewPlugins.next() ) - m_paPreviewPlugins.current()->setEnabled( toggle ); - } - else - { - TQStringList types = TQStringList::split( ',', name ); - for ( TQStringList::ConstIterator it = types.begin(); it != types.end(); ++it ) - { - m_pProps->setShowingPreview( *it, toggle ); - m_pIconView->setPreviewSettings( m_pProps->previewSettings() ); - if ( !toggle ) - { - kdDebug() << "KonqKfmIconView::slotPreview stopping image preview for " << *it << endl; - if ( *it == "audio/" ) - m_pIconView->disableSoundPreviews(); - else - { - KService::Ptr serv = KService::serviceByDesktopName( *it ); - Q_ASSERT( serv != 0L ); - if ( serv ) { - bool previewRunning = m_pIconView->isPreviewRunning(); - if ( previewRunning ) - m_pIconView->stopImagePreview(); - TQStringList mimeTypes = serv->property("MimeTypes").toStringList(); - m_pIconView->setIcons( m_pIconView->iconSize(), mimeTypes ); - if ( previewRunning ) - m_pIconView->startImagePreview( m_pProps->previewSettings(), false ); - } - } - } - else - { - m_pIconView->startImagePreview( m_pProps->previewSettings(), true ); - } - } - } -} - -void KonqKfmIconView::slotShowDot() -{ - m_pProps->setShowingDotFiles( !m_pProps->isShowingDotFiles() ); - m_dirLister->setShowingDotFiles( m_pProps->isShowingDotFiles() ); - m_dirLister->emitChanges(); - //we don't want the non-dot files to remain where they are - m_bNeedAlign = true; - slotCompleted(); -} - -void KonqKfmIconView::slotShowDirectoryOverlays() -{ - bool show = !m_pProps->isShowingDirectoryOverlays(); - - m_pProps->setShowingDirectoryOverlays( show ); - - for ( TQIconViewItem *item = m_pIconView->firstItem(); item; item = item->nextItem() ) - { - KFileIVI* kItem = static_cast(item); - if ( !kItem->item()->isDir() ) continue; - - if (show) { - showDirectoryOverlay(kItem); - } else { - kItem -> setShowDirectoryOverlay(false); - } - } - - m_pIconView->updateContents(); -} - -void KonqKfmIconView::slotShowFreeSpaceOverlays() -{ - bool show = !m_pProps->isShowingFreeSpaceOverlays(); - - m_pProps->setShowingFreeSpaceOverlays( show ); - - for ( TQIconViewItem *item = m_pIconView->firstItem(); item; item = item->nextItem() ) - { - KFileIVI* kItem = static_cast(item); - if ( !kItem->item()->isDir() ) continue; - - if (show) { - showFreeSpaceOverlay(kItem); - } else { - kItem -> setShowFreeSpaceOverlay(false); - } - } - - m_pIconView->updateContents(); -} - -void KonqKfmIconView::slotSelect() -{ - bool ok; - TQString pattern = KInputDialog::getText( TQString::null, - i18n( "Select files:" ), "*", &ok, m_pIconView ); - if ( ok ) - { - TQRegExp re( pattern, true, true ); - - m_pIconView->blockSignals( true ); - - TQIconViewItem *it = m_pIconView->firstItem(); - while ( it ) { - if ( it->isVisible() ) { - if ( re.exactMatch( it->text() ) ) { - it->setSelected( true, true ); - } - } - else { - it->setSelected( false, true ); - } - it = it->nextItem(); - } - - m_pIconView->blockSignals( false ); - - // do this once, not for each item - m_pIconView->slotSelectionChanged(); - slotSelectionChanged(); - } -} - -void KonqKfmIconView::slotUnselect() -{ - bool ok; - TQString pattern = KInputDialog::getText( TQString::null, - i18n( "Unselect files:" ), "*", &ok, m_pIconView ); - if ( ok ) - { - TQRegExp re( pattern, true, true ); - - m_pIconView->blockSignals( true ); - - TQIconViewItem *it = m_pIconView->firstItem(); - while ( it ) { - if ( it->isVisible() ) { - if ( re.exactMatch( it->text() ) ) { - it->setSelected( false, true ); - } - } - else { - it->setSelected( false, true ); - } - it = it->nextItem(); - } - - m_pIconView->blockSignals( false ); - - // do this once, not for each item - m_pIconView->slotSelectionChanged(); - slotSelectionChanged(); - } -} - -void KonqKfmIconView::slotSelectAll() -{ - m_pIconView->selectAll( true ); -} - -void KonqKfmIconView::slotUnselectAll() -{ - m_pIconView->selectAll( false ); -} - -void KonqKfmIconView::slotInvertSelection() -{ - m_pIconView->invertSelection( ); -} - -void KonqKfmIconView::slotSortByNameCaseSensitive( bool toggle ) -{ - if ( !toggle ) - return; - - KonqIconViewFactory::defaultViewProps()->setSortCriterion("sort_nc"); - setupSorting( NameCaseSensitive ); -} - -void KonqKfmIconView::slotSortByNameCaseInsensitive( bool toggle ) -{ - if ( !toggle ) - return; - - KonqIconViewFactory::defaultViewProps()->setSortCriterion("sort_nci"); - setupSorting( NameCaseInsensitive ); -} - -void KonqKfmIconView::slotSortBySize( bool toggle ) -{ - if ( !toggle ) - return; - - KonqIconViewFactory::defaultViewProps()->setSortCriterion("sort_size"); - setupSorting( Size ); -} - -void KonqKfmIconView::slotSortByType( bool toggle ) -{ - if ( !toggle ) - return; - - KonqIconViewFactory::defaultViewProps()->setSortCriterion("sort_type"); - setupSorting( Type ); -} - -void KonqKfmIconView::slotSortByDate( bool toggle ) -{ - if( !toggle) - return; - - KonqIconViewFactory::defaultViewProps()->setSortCriterion("sort_date"); - setupSorting( Date ); -} - -void KonqKfmIconView::setupSorting( SortCriterion criterion ) -{ - m_eSortCriterion = criterion; - - setupSortKeys(); - - m_pIconView->sort( m_pIconView->sortDirection() ); -} - -void KonqKfmIconView::slotSortDescending() -{ - if ( m_pIconView->sortDirection() ) - m_pIconView->setSorting( true, false ); - else - m_pIconView->setSorting( true, true ); - - setupSortKeys(); // keys have to change, for directories - - m_pIconView->sort( m_pIconView->sortDirection() ); - - KonqIconViewFactory::defaultViewProps()->setDescending( !m_pIconView->sortDirection() ); -} - -void KonqKfmIconView::slotSortDirsFirst() -{ - m_pIconView->setSortDirectoriesFirst( m_paSortDirsFirst->isChecked() ); - - setupSortKeys(); - - m_pIconView->sort( m_pIconView->sortDirection() ); - - KonqIconViewFactory::defaultViewProps()->setDirsFirst( m_paSortDirsFirst->isChecked() ); -} - -void KonqKfmIconView::newIconSize( int size ) -{ - //Either of the sizes can be 0 to indicate the default (Desktop) size icons. - //check for that when checking whether the size changed - int effSize = size; - if (effSize == 0) - effSize = IconSize(TDEIcon::Desktop); - - int oldEffSize = m_pIconView->iconSize(); - if (oldEffSize == 0) - oldEffSize = IconSize(TDEIcon::Desktop); - - // Make sure all actions are initialized. - KonqDirPart::newIconSize( size ); - - if ( effSize == oldEffSize ) - return; - - // Stop a preview job that might be running - m_pIconView->stopImagePreview(); - - // Set icons size, arrage items in grid and repaint the whole view - m_pIconView->setIcons( size ); - - // If previews are enabled start a new job - if ( m_pProps->isShowingPreview() ) - m_pIconView->startImagePreview( m_pProps->previewSettings(), true ); -} - -bool KonqKfmIconView::doCloseURL() -{ - m_dirLister->stop(); - - m_mimeTypeResolver->m_lstPendingMimeIconItems.clear(); - - m_bPreviewRunningBeforeCloseURL = m_pIconView->isPreviewRunning(); - m_pIconView->stopImagePreview(); - return true; -} - -void KonqKfmIconView::slotReturnPressed( TQIconViewItem *item ) -{ - if ( !item ) - return; - - item->setSelected( false, true ); - m_pIconView->visualActivate(item); - - KFileItem *fileItem = (static_cast(item))->item(); - if ( !fileItem ) - return; - lmbClicked( fileItem ); -} - -void KonqKfmIconView::slotDragHeld( TQIconViewItem *item ) -{ - kdDebug() << "KonqKfmIconView::slotDragHeld()" << endl; - - // This feature is not usable if the user wants one window per folder - if ( KonqFMSettings::settings()->alwaysNewWin() ) - return; - - if ( !item ) - return; - - KFileItem *fileItem = (static_cast(item))->item(); - - SpringLoadingManager::self().springLoadTrigger(this, fileItem, item); -} - -void KonqKfmIconView::slotDragEntered( bool ) -{ - if ( SpringLoadingManager::exists() ) - SpringLoadingManager::self().dragEntered(this); -} - -void KonqKfmIconView::slotDragLeft() -{ - kdDebug() << "KonqKfmIconView::slotDragLeft()" << endl; - - if ( SpringLoadingManager::exists() ) - SpringLoadingManager::self().dragLeft(this); -} - -void KonqKfmIconView::slotDragMove( bool accepted ) -{ - if ( !accepted ) - emit setStatusBarText( i18n( "You cannot drop any items in a directory in which you do not have write permission" ) ); -} - -void KonqKfmIconView::slotDragFinished() -{ - kdDebug() << "KonqKfmIconView::slotDragFinished()" << endl; - - if ( SpringLoadingManager::exists() ) - SpringLoadingManager::self().dragFinished(this); -} - - -void KonqKfmIconView::slotContextMenuRequested(TQIconViewItem* _item, const TQPoint& _global) -{ - const KFileItemList items = m_pIconView->selectedFileItems(); - if ( items.isEmpty() ) - return; - - KParts::BrowserExtension::PopupFlags popupFlags = KParts::BrowserExtension::DefaultPopupItems; - - KFileIVI* i = static_cast(_item); - if (i) - i->setSelected( true, true /* don't touch other items */ ); - - KFileItem * rootItem = m_dirLister->rootItem(); - if ( rootItem ) { - KURL parentDirURL = rootItem->url(); - // Check if parentDirURL applies to the selected items (usually yes, but not with search results) - TQPtrListIterator kit( items ); - for ( ; kit.current(); ++kit ) - if ( kit.current()->url().directory( 1 ) != rootItem->url().path() ) - parentDirURL = KURL(); - // If rootItem is the parent of the selected items, then we can use isWritable() on it. - if ( !parentDirURL.isEmpty() && !rootItem->isWritable() ) - popupFlags |= KParts::BrowserExtension::NoDeletion; - } - - emit m_extension->popupMenu( 0L, _global, items, KParts::URLArgs(), popupFlags); -} - -void KonqKfmIconView::slotMouseButtonPressed(int _button, TQIconViewItem* _item, const TQPoint&) -{ - if ( _button == Qt::RightButton && !_item ) - { - // Right click on viewport - KFileItem * item = m_dirLister->rootItem(); - bool delRootItem = false; - if ( ! item ) - { - if ( m_bLoading ) - { - kdDebug(1202) << "slotViewportRightClicked : still loading and no root item -> dismissed" << endl; - return; // too early, '.' not yet listed - } - else - { - // We didn't get a root item (e.g. over FTP) - // We have to create a dummy item. I tried using KonqOperations::statURL, - // but this was leading to a huge delay between the RMB and the popup. Bad. - // But KonqPopupMenu now takes care of stating before opening properties. - item = new KFileItem( S_IFDIR, (mode_t)-1, url() ); - delRootItem = true; - } - } - - KFileItemList items; - items.append( item ); - - KParts::BrowserExtension::PopupFlags popupFlags = KParts::BrowserExtension::ShowNavigationItems | KParts::BrowserExtension::ShowUp; - - emit m_extension->popupMenu( 0L, TQCursor::pos(), items, KParts::URLArgs(), popupFlags ); - - if ( delRootItem ) - delete item; // we just created it - } -} - -void KonqKfmIconView::slotMouseButtonClicked(int _button, TQIconViewItem* _item, const TQPoint& ) -{ - if( _button == Qt::MidButton ) - mmbClicked( _item ? static_cast(_item)->item() : 0L ); -} - -void KonqKfmIconView::slotDoubleClicked(TQIconViewItem *_item) -{ - if (!_item) - { - KParts::URLArgs args; - args.trustedSource = true; - KURL upURL = m_dirLister->url().upURL(); - if (!upURL.isEmpty()) - { - m_extension->openURLRequest(upURL, args); - } - } -} - -void KonqKfmIconView::slotStarted() -{ - // Only emit started if this comes after openURL, i.e. it's not for an update. - // We don't want to start a spinning wheel during updates. - if ( m_bLoading ) - emit started( 0 ); - - // An update may come in while we are still processing icons... - // So don't clear the list. - //m_mimeTypeResolver->m_lstPendingMimeIconItems.clear(); -} - -void KonqKfmIconView::slotCanceled() -{ - // Called by kfindpart. Not by kdirlister. - slotCanceled( m_pIconView->url() ); -} - -void KonqKfmIconView::slotCanceled( const KURL& url ) -{ - // Check if this canceled() signal is about the URL we're listing. - // It could be about the URL we were listing, and openURL() aborted it. - if ( m_bLoading && url.equals( m_pIconView->url(), true ) ) - { - emit canceled( TQString::null ); - m_bLoading = false; - } - - // Stop the "refresh if busy too long" timer because a viewport - // update is coming. - if ( m_pTimeoutRefreshTimer && m_pTimeoutRefreshTimer->isActive() ) - m_pTimeoutRefreshTimer->stop(); - - // See slotCompleted(). If a listing gets canceled, it doesn't emit - // the completed() signal, so handle that case. - if ( !m_pIconView->viewport()->isUpdatesEnabled() ) - { - m_pIconView->viewport()->setUpdatesEnabled( true ); - m_pIconView->viewport()->repaint(); - } - if ( m_pEnsureVisible ){ - m_pIconView->ensureItemVisible( m_pEnsureVisible ); - m_pEnsureVisible = 0; - } -} - -void KonqKfmIconView::slotCompleted() -{ - // Stop the "refresh if busy too long" timer because a viewport - // update is coming. - if ( m_pTimeoutRefreshTimer && m_pTimeoutRefreshTimer->isActive() ) { - m_pTimeoutRefreshTimer->stop(); - } - - // If updates to the viewport are still blocked (so slotNewItems() has - // not been called), a viewport repaint is forced. - if ( !m_pIconView->viewport()->isUpdatesEnabled() ) - { - m_pIconView->viewport()->setUpdatesEnabled( true ); - m_pIconView->viewport()->repaint(); - } - - // Root item ? Store root item in konqiconviewwidget (whether 0L or not) - m_pIconView->setRootItem( m_dirLister->rootItem() ); - - // only after initial listing, not after updates - // If we don't set a current item, the iconview has none (one more keypress needed) - // but it appears on focusin... qiconview bug, Reggie acknowledged it LONG ago (07-2000). - if ( m_bNeedSetCurrentItem ) - { - m_pIconView->setCurrentItem( m_pIconView->firstItem() ); - m_bNeedSetCurrentItem = false; - } - - if ( m_bUpdateContentsPosAfterListing ) { - m_pIconView->setContentsPos( extension()->urlArgs().xOffset, - extension()->urlArgs().yOffset ); - } - - if ( m_pEnsureVisible ) { - m_pIconView->ensureItemVisible( m_pEnsureVisible ); - m_pEnsureVisible = 0; - } - - m_bUpdateContentsPosAfterListing = false; - - if ( !m_pIconView->firstItem() ) { - resetCount(); - } - - slotOnViewport(); - - // slotRenderingFinished will do it - m_bNeedEmitCompleted = true; - - if (m_pProps->isShowingPreview()) { - m_mimeTypeResolver->start( 0 ); // We need the mimetypes asap - } - else - { - slotRenderingFinished(); // emit completed, we don't want the wheel... - // to keep turning while we find mimetypes in the background - m_mimeTypeResolver->start( 10 ); - } - - m_bLoading = false; - - // Disable cut icons if any - slotClipboardDataChanged(); -} - -void KonqKfmIconView::slotNewItems( const KFileItemList& entries ) -{ - // Stop the autorefresh timer since data to display has arrived and will - // be drawn in moments - if ( m_pTimeoutRefreshTimer && m_pTimeoutRefreshTimer->isActive() ) { - m_pTimeoutRefreshTimer->stop(); - } - // We need to disable graphics updates on the iconview when - // inserting items, or else a blank paint operation will be - // performed on the top-left corner for each inserted item! - m_pIconView->setUpdatesEnabled( false ); - for (KFileItemListIterator it(entries); it.current(); ++it) - { - //kdDebug(1202) << "KonqKfmIconView::slotNewItem(...)" << _fileitem->url().url() << endl; - KFileIVI* item = new KFileIVI( m_pIconView, *it, m_pIconView->iconSize() ); - item->setRenameEnabled( false ); - - KFileItem* fileItem = item->item(); - - if ( !m_itemsToSelect.isEmpty() ) { - TQStringList::Iterator tsit = m_itemsToSelect.find( fileItem->name() ); - if ( tsit != m_itemsToSelect.end() ) { - m_itemsToSelect.remove( tsit ); - m_pIconView->setSelected( item, true, true ); - if ( m_bNeedSetCurrentItem ){ - m_pIconView->setCurrentItem( item ); - if( !m_pEnsureVisible ) - m_pEnsureVisible = item; - m_bNeedSetCurrentItem = false; - } - } - } - - if ( fileItem->isDir() && m_pProps->isShowingDirectoryOverlays() ) { - showDirectoryOverlay(item); - } - if ( fileItem->mimetypeFast().startsWith("media/") && fileItem->mimetypeFast().contains("_mounted") && m_pProps->isShowingFreeSpaceOverlays() ) { - showFreeSpaceOverlay(item); - } - - TQString key; - - switch ( m_eSortCriterion ) - { - case NameCaseSensitive: key = item->text(); break; - case NameCaseInsensitive: key = item->text().lower(); break; - case Size: key = makeSizeKey( item ); break; - case Type: key = item->item()->mimetype()+ "\008" +item->text().lower(); break; // ### slows down listing :-( - case Date: - { - TQDateTime dayt; - dayt.setTime_t(item->item()->time(TDEIO::UDS_MODIFICATION_TIME )); - key = dayt.toString("yyyyMMddhhmmss"); - break; - } - default: Q_ASSERT(0); - } - - item->setKey( key ); - - //kdDebug() << "KonqKfmIconView::slotNewItems " << (*it)->url().url() << " " << (*it)->mimeTypePtr()->name() << " mimetypeknown:" << (*it)->isMimeTypeKnown() << endl; - if ( !(*it)->isMimeTypeKnown() ) { - m_mimeTypeResolver->m_lstPendingMimeIconItems.append( item ); - } - - m_itemDict.insert( *it, item ); - } - // After filtering out updates-on-insertions we can re-enable updates - m_pIconView->setUpdatesEnabled( true ); - // Locking the viewport has filtered out blanking and now, since we - // have some items to draw, we can restore updating. - if ( !m_pIconView->viewport()->isUpdatesEnabled() ) { - m_pIconView->viewport()->setUpdatesEnabled( true ); - } - KonqDirPart::newItems( entries ); -} - -void KonqKfmIconView::slotDeleteItem( KFileItem * _fileitem ) -{ - KFileItemList list; - list.append( _fileitem ); - emit m_extension->itemsRemoved( list ); - - if ( _fileitem == m_dirLister->rootItem() ) - { - m_pIconView->stopImagePreview(); - m_pIconView->setRootItem( 0L ); - return; - } - - //kdDebug(1202) << "KonqKfmIconView::slotDeleteItem(...)" << endl; - // we need to find out the iconcontainer item containing the fileitem - KFileIVI * ivi = m_itemDict[ _fileitem ]; - // It can be that we know nothing about this item, e.g. because it's filtered out - // (by default: dot files). KDirLister still tells us about it when it's modified, since - // it doesn't know if we showed it before, and maybe its mimetype changed so we - // might have to hide it now. - if (ivi) - { - m_pIconView->stopImagePreview(); - KonqDirPart::deleteItem( _fileitem ); - - m_mimeTypeResolver->m_lstPendingMimeIconItems.remove( ivi ); - m_itemDict.remove( _fileitem ); - if (m_paOutstandingOverlays.first() == ivi) // Being processed? - m_paOutstandingOverlaysTimer->start(20, true); // Restart processing... - m_paOutstandingOverlays.remove(ivi); - if (m_paOutstandingFreeSpaceOverlays.first() == ivi) // Being processed? - m_paOutstandingFreeSpaceOverlaysTimer->start(20, true); // Restart processing... - m_paOutstandingFreeSpaceOverlays.remove(ivi); - - delete ivi; - } -} - -void KonqKfmIconView::showDirectoryOverlay(KFileIVI* item) -{ - KFileItem* fileItem = item->item(); - - if ( TDEGlobalSettings::showFilePreview( fileItem->url() ) ) { - m_paOutstandingOverlays.append(item); - if (m_paOutstandingOverlays.count() == 1) - { - if (!m_paOutstandingOverlaysTimer) - { - m_paOutstandingOverlaysTimer = new TQTimer(this); - connect(m_paOutstandingOverlaysTimer, TQT_SIGNAL(timeout()), - TQT_SLOT(slotDirectoryOverlayStart())); - } - m_paOutstandingOverlaysTimer->start(20, true); - } - } -} - -void KonqKfmIconView::showFreeSpaceOverlay(KFileIVI* item) -{ - m_paOutstandingFreeSpaceOverlays.append(item); - if (m_paOutstandingFreeSpaceOverlays.count() == 1) - { - if (!m_paOutstandingFreeSpaceOverlaysTimer) - { - m_paOutstandingFreeSpaceOverlaysTimer = new TQTimer(this); - connect(m_paOutstandingFreeSpaceOverlaysTimer, TQT_SIGNAL(timeout()), - TQT_SLOT(slotFreeSpaceOverlayStart())); - } - m_paOutstandingFreeSpaceOverlaysTimer->start(20, true); - } -} - -void KonqKfmIconView::slotDirectoryOverlayStart() -{ - do - { - KFileIVI* item = m_paOutstandingOverlays.first(); - if (!item) - return; // Nothing to do - - KIVDirectoryOverlay* overlay = item->setShowDirectoryOverlay( true ); - - if (overlay) - { - connect( overlay, TQT_SIGNAL( finished() ), this, TQT_SLOT( slotDirectoryOverlayFinished() ) ); - overlay->start(); // Watch out, may emit finished() immediately!! - return; // Let it run.... - } - m_paOutstandingOverlays.removeFirst(); - } while (true); -} - -void KonqKfmIconView::slotFreeSpaceOverlayStart() -{ - do - { - KFileIVI* item = m_paOutstandingFreeSpaceOverlays.first(); - if (!item) - return; // Nothing to do - - KIVFreeSpaceOverlay* overlay = item->setShowFreeSpaceOverlay( true ); - - if (overlay) - { - connect( overlay, TQT_SIGNAL( finished() ), this, TQT_SLOT( slotFreeSpaceOverlayFinished() ) ); - overlay->start(); // Watch out, may emit finished() immediately!! - return; // Let it run.... - } - m_paOutstandingFreeSpaceOverlays.removeFirst(); - } while (true); -} - -void KonqKfmIconView::slotDirectoryOverlayFinished() -{ - m_paOutstandingOverlays.removeFirst(); - - if (m_paOutstandingOverlays.count() > 0) - m_paOutstandingOverlaysTimer->start(0, true); // Don't call directly to prevent deep recursion. -} - -void KonqKfmIconView::slotFreeSpaceOverlayFinished() -{ - m_paOutstandingFreeSpaceOverlays.removeFirst(); - - if (m_paOutstandingFreeSpaceOverlays.count() > 0) - m_paOutstandingFreeSpaceOverlaysTimer->start(0, true); // Don't call directly to prevent deep recursion. -} - -// see also KDesktop::slotRefreshItems -void KonqKfmIconView::slotRefreshItems( const KFileItemList& entries ) -{ - bool bNeedRepaint = false; - bool bNeedPreviewJob = false; - KFileItemListIterator rit(entries); - for (; rit.current(); ++rit) - { - KFileIVI * ivi = m_itemDict[ rit.current() ]; - Q_ASSERT(ivi); - kdDebug() << "KonqKfmIconView::slotRefreshItems '" << rit.current()->name() << "' ivi=" << ivi << endl; - if (ivi) - { - TQSize oldSize = ivi->pixmap()->size(); - if ( ivi->isThumbnail() ) { - bNeedPreviewJob = true; - ivi->invalidateThumbnail(); - } - else { - ivi->refreshIcon( true ); - } - ivi->setText( rit.current()->text() ); - if ( rit.current()->isMimeTypeKnown() ) { - ivi->setMouseOverAnimation( rit.current()->iconName() ); - } - if ( !bNeedRepaint && oldSize != ivi->pixmap()->size() ) { - bNeedRepaint = true; - } - if ( (*rit)->mimetypeFast().startsWith("media/") && m_pProps->isShowingFreeSpaceOverlays() ) { - if ((*rit)->mimetypeFast().contains("_mounted")) { - showFreeSpaceOverlay(ivi); - } - else { - // If not mounted, hide free space overlay - ivi->setShowFreeSpaceOverlay(false); - } - } - } - } - - if ( bNeedPreviewJob && m_pProps->isShowingPreview() ) - { - m_pIconView->startImagePreview( m_pProps->previewSettings(), false ); - } - else - { - // In case we replace a big icon with a small one, need to repaint. - if ( bNeedRepaint ) { - m_pIconView->updateContents(); - } - } - KonqDirPart::refreshItems(entries); // Pass refresh command to KonqDirPart too -} - -void KonqKfmIconView::slotClear() -{ - resetCount(); - - // We're now going to update the view with new contents. To avoid - // meaningless paint operations (such as a clear() just before drawing - // fresh contents) we disable updating the viewport until we'll - // receive some data or a timeout timer expires. - m_pIconView->viewport()->setUpdatesEnabled( false ); - if ( !m_pTimeoutRefreshTimer ) - { - m_pTimeoutRefreshTimer = new TQTimer( this ); - connect( m_pTimeoutRefreshTimer, TQT_SIGNAL( timeout() ), - this, TQT_SLOT( slotRefreshViewport() ) ); - } - m_pTimeoutRefreshTimer->start( 700, true ); - - // Clear contents but don't clear graphics as updates are disabled. - m_pIconView->clear(); - // If directory properties are changed, apply pending changes - // changes are: view background or color, iconsize, enabled previews - if ( m_bDirPropertiesChanged ) - { - m_pProps->applyColors( m_pIconView->viewport() ); - newIconSize( m_pProps->iconSize() ); - m_pIconView->setPreviewSettings( m_pProps->previewSettings() ); - } - - m_mimeTypeResolver->m_lstPendingMimeIconItems.clear(); - m_itemDict.clear(); - // Bug in QIconview IMHO - it should emit selectionChanged() - // (bug reported, but code seems to be that way on purpose) - m_pIconView->slotSelectionChanged(); - slotSelectionChanged(); -} - -void KonqKfmIconView::slotRedirection( const KURL & url ) -{ - const TQString prettyURL = url.pathOrURL(); - emit m_extension->setLocationBarURL( prettyURL ); - emit setWindowCaption( prettyURL ); - m_pIconView->setURL( url ); - m_url = url; -} - -void KonqKfmIconView::slotSelectionChanged() -{ - // Display statusbar info, and emit selectionInfo - KFileItemList lst = m_pIconView->selectedFileItems(); - emitCounts( lst, true ); - - bool itemSelected = lst.count()>0; - m_paUnselect->setEnabled( itemSelected ); - m_paUnselectAll->setEnabled( itemSelected ); - m_paInvertSelection->setEnabled( itemSelected ); -} - -void KonqKfmIconView::determineIcon( KFileIVI * item ) -{ - // kdDebug() << "KonqKfmIconView::determineIcon " << item->item()->name() << endl; - //int oldSerial = item->pixmap()->serialNumber(); - - (void) item->item()->determineMimeType(); - - if (item->item()->isMimeTypeKnown()) { - item->mimeTypeAndIconDetermined(); - } - - item->setIcon( iconSize(), item->state(), true, true ); - item->setMouseOverAnimation( item->item()->iconName() ); -} - -void KonqKfmIconView::mimeTypeDeterminationFinished() -{ - if ( m_pProps->isShowingPreview() ) - { - // TODO if ( m_url.isLocalFile() || m_bAutoPreviewRemote ) - { - // We can do this only when the mimetypes are fully determined, - // since we only do image preview... on images :-) - m_pIconView->startImagePreview( m_pProps->previewSettings(), false ); - return; - } - } - slotRenderingFinished(); -} - -void KonqKfmIconView::slotRenderingFinished() -{ - kdDebug(1202) << "KonqKfmIconView::slotRenderingFinished()" << endl; - if ( m_bNeedEmitCompleted ) - { - kdDebug(1202) << "KonqKfmIconView completed() after rendering" << endl; - emit completed(); - m_bNeedEmitCompleted = false; - } - if ( m_bNeedAlign ) - { - m_bNeedAlign = false; - kdDebug(1202) << "arrangeItemsInGrid" << endl; - m_pIconView->arrangeItemsInGrid(); - } -} - -void KonqKfmIconView::slotRefreshViewport() -{ - kdDebug(1202) << "KonqKfmIconView::slotRefreshViewport()" << endl; - TQWidget * vp = m_pIconView->viewport(); - bool prevState = vp->isUpdatesEnabled(); - vp->setUpdatesEnabled( true ); - vp->repaint(); - vp->setUpdatesEnabled( prevState ); -} - -bool KonqKfmIconView::doOpenURL( const KURL & url ) -{ - // Store url in the icon view - m_pIconView->setURL( url ); - - m_bLoading = true; - m_bNeedSetCurrentItem = true; - - // Check for new properties in the new dir - // enterDir returns true the first time, and any time something might - // have changed. - m_bDirPropertiesChanged = m_pProps->enterDir( url ); - - m_dirLister->setNameFilter( m_nameFilter ); - - m_dirLister->setMimeFilter( mimeFilter() ); - - // This *must* happen before m_dirLister->openURL because it emits - // clear() and TQIconView::clear() calls setContentsPos(0,0)! - KParts::URLArgs args = m_extension->urlArgs(); - if ( args.reload ) - { - args.xOffset = m_pIconView->contentsX(); - args.yOffset = m_pIconView->contentsY(); - m_extension->setURLArgs( args ); - - m_filesToSelect.clear(); - KFileItemList fil( selectedFileItems() ); - for (KFileItemListIterator fi_it(fil); fi_it.current(); ++fi_it) - m_filesToSelect += (*fi_it)->name(); - } - - m_itemsToSelect = m_filesToSelect; - - m_dirLister->setShowingDotFiles( m_pProps->isShowingDotFiles() ); - - m_bNeedAlign = false; - m_bUpdateContentsPosAfterListing = true; - - m_paOutstandingOverlays.clear(); - m_paOutstandingFreeSpaceOverlays.clear(); - - // Start the directory lister ! - m_dirLister->openURL( url, false, args.reload ); - - // View properties (icon size, background, ..) will be applied into slotClear() - // if m_bDirPropertiesChanged is set. If so, here we update preview actions. - if ( m_bDirPropertiesChanged ) - { - m_paDotFiles->setChecked( m_pProps->isShowingDotFiles() ); - m_paDirectoryOverlays->setChecked( m_pProps->isShowingDirectoryOverlays() ); - m_paFreeSpaceOverlays->setChecked( m_pProps->isShowingFreeSpaceOverlays() ); - m_paEnablePreviews->setChecked( m_pProps->isShowingPreview() ); - for ( m_paPreviewPlugins.first(); m_paPreviewPlugins.current(); m_paPreviewPlugins.next() ) - { - TQStringList types = TQStringList::split( ',', m_paPreviewPlugins.current()->name() ); - bool enabled = false; - for ( TQStringList::ConstIterator it = types.begin(); it != types.end(); ++it ) - if ( m_pProps->isShowingPreview( *it ) ) - { - enabled = true; - break; - } - m_paPreviewPlugins.current()->setChecked( enabled ); - m_paPreviewPlugins.current()->setEnabled( m_pProps->isShowingPreview() ); - } - } - - const TQString prettyURL = url.pathOrURL(); - emit setWindowCaption( prettyURL ); - - return true; -} - -void KonqKfmIconView::slotKFindOpened() -{ - m_dirLister->setAutoUpdate( false ); -} - -void KonqKfmIconView::slotKFindClosed() -{ - m_dirLister->setAutoUpdate( true ); -} - -void KonqKfmIconView::slotOnItem( TQIconViewItem *item ) -{ - emit setStatusBarText( static_cast(item)->item()->getStatusBarInfo() ); - emitMouseOver( static_cast(item)->item()); -} - -void KonqKfmIconView::slotOnViewport() -{ - KFileItemList lst = m_pIconView->selectedFileItems(); - emitCounts( lst, false ); - emitMouseOver( 0 ); -} - -void KonqKfmIconView::setViewMode( const TQString &mode ) -{ - if ( mode == m_mode ) - return; - // note: this should be moved to KonqIconViewWidget. It would make the code - // more readable :) - - m_mode = mode; - if (mode=="MultiColumnView") - { - m_pIconView->setArrangement(TQIconView::TopToBottom); - m_pIconView->setItemTextPos(TQIconView::Right); - } - else - { - m_pIconView->setArrangement(TQIconView::LeftToRight); - m_pIconView->setItemTextPos(TQIconView::Bottom); - } - - if ( m_bPreviewRunningBeforeCloseURL ) - { - m_bPreviewRunningBeforeCloseURL = false; - // continue (param: false) a preview job interrupted by doCloseURL - m_pIconView->startImagePreview( m_pProps->previewSettings(), false ); - } -} - -void KonqKfmIconView::setupSortKeys() -{ - switch ( m_eSortCriterion ) - { - case NameCaseSensitive: - m_pIconView->setCaseInsensitiveSort( false ); - for ( TQIconViewItem *it = m_pIconView->firstItem(); it; it = it->nextItem() ) - it->setKey( it->text() ); - break; - case NameCaseInsensitive: - m_pIconView->setCaseInsensitiveSort( true ); - for ( TQIconViewItem *it = m_pIconView->firstItem(); it; it = it->nextItem() ) - it->setKey( it->text().lower() ); - break; - case Size: - for ( TQIconViewItem *it = m_pIconView->firstItem(); it; it = it->nextItem() ) - it->setKey( makeSizeKey( (KFileIVI *)it ) ); - break; - case Type: - // Sort by Type + Name (#17014) - for ( TQIconViewItem *it = m_pIconView->firstItem(); it; it = it->nextItem() ) - it->setKey( static_cast( it )->item()->mimetype() + "\008" + it->text().lower() ); - break; - case Date: - { - //Sorts by time of modification (#52750) - TQDateTime dayt; - for ( TQIconViewItem *it = m_pIconView->firstItem(); it; it = it->nextItem() ) - { - dayt.setTime_t(static_cast( it )->item()->time(TDEIO::UDS_MODIFICATION_TIME)); - it->setKey(dayt.toString("yyyyMMddhhmmss")); - } - break; - } - } -} - -TQString KonqKfmIconView::makeSizeKey( KFileIVI *item ) -{ - return TDEIO::number( item->item()->size() ).rightJustify( 20, '0' ); -} - -void KonqKfmIconView::disableIcons( const KURL::List & lst ) -{ - m_pIconView->disableIcons( lst ); -} - - -SpringLoadingManager *SpringLoadingManager::s_self = 0L; -static KStaticDeleter s_springManagerDeleter; - -SpringLoadingManager::SpringLoadingManager() - : m_startPart(0L) -{ - connect( &m_endTimer, TQT_SIGNAL( timeout() ), - this, TQT_SLOT( finished() ) ); - -} - -SpringLoadingManager &SpringLoadingManager::self() -{ - if ( !s_self ) - { - s_springManagerDeleter.setObject(s_self, new SpringLoadingManager()); - } - - return *s_self; -} - -bool SpringLoadingManager::exists() -{ - return s_self!=0L; -} - - -void SpringLoadingManager::springLoadTrigger(KonqKfmIconView *view, - KFileItem *file, - TQIconViewItem *item) -{ - if ( !file || !file->isDir() ) - return; - - // We start a new spring loading chain - if ( m_startPart==0L ) - { - m_startURL = view->url(); - m_startPart = view; - } - - // Only the last part of the chain is allowed to trigger a spring load - // event (if a spring loading chain is in progress) - if ( view!=m_startPart ) - return; - - - item->setSelected( false, true ); - view->iconViewWidget()->visualActivate(item); - - KURL url = file->url(); - - KParts::URLArgs args; - file->determineMimeType(); - if ( file->isMimeTypeKnown() ) - args.serviceType = file->mimetype(); - args.trustedSource = true; - - // Open the folder URL, we don't want to modify the browser - // history, hence the use of openURL and setLocationBarURL - view->openURL(url); - const TQString prettyURL = url.pathOrURL(); - emit view->extension()->setLocationBarURL( prettyURL ); -} - -void SpringLoadingManager::dragLeft(KonqKfmIconView */*view*/) -{ - // We leave a view maybe the user tries to cancel the current spring loading - if ( !m_startURL.isEmpty() ) - { - m_endTimer.start(1000, true); - } -} - -void SpringLoadingManager::dragEntered(KonqKfmIconView *view) -{ - // We enter a view involved in the spring loading chain - if ( !m_startURL.isEmpty() && m_startPart==view ) - { - m_endTimer.stop(); - } -} - -void SpringLoadingManager::dragFinished(KonqKfmIconView */*view*/) -{ - if ( !m_startURL.isEmpty() ) - { - finished(); - } -} - - -void SpringLoadingManager::finished() -{ - kdDebug() << "SpringLoadManager::finished()" << endl; - - KURL url = m_startURL; - m_startURL = KURL(); - - KParts::ReadOnlyPart *part = m_startPart; - m_startPart = 0L; - - KonqKfmIconView *view = static_cast(part); - view->openURL(url); - const TQString prettyURL = url.pathOrURL(); - emit view->extension()->setLocationBarURL( prettyURL ); - - deleteLater(); - s_self = 0L; - s_springManagerDeleter.setObject(s_self, static_cast(0L)); -} - - - -#include "konq_iconview.moc" diff --git a/konqueror/iconview/konq_iconview.cpp b/konqueror/iconview/konq_iconview.cpp new file mode 100644 index 000000000..5efc1e751 --- /dev/null +++ b/konqueror/iconview/konq_iconview.cpp @@ -0,0 +1,1660 @@ +/* This file is part of the KDE projects + Copyright (C) 1998, 1999 Torben Weis + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "konq_iconview.h" +#include "konq_propsview.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +template class TQPtrList; +//template class TQValueList; + +class KonqIconViewFactory : public KParts::Factory +{ +public: + KonqIconViewFactory() + { + s_defaultViewProps = 0; + s_instance = 0; + } + + virtual ~KonqIconViewFactory() + { + if ( s_instance ) + delete s_instance; + + if ( s_defaultViewProps ) + delete s_defaultViewProps; + + s_instance = 0; + s_defaultViewProps = 0; + } + + virtual KParts::Part* createPartObject( TQWidget *parentWidget, const char *, + TQObject *parent, const char *name, const char*, const TQStringList &args ) + { + if( args.count() < 1 ) + kdWarning() << "KonqKfmIconView: Missing Parameter" << endl; + + KonqKfmIconView *obj = new KonqKfmIconView( parentWidget, parent, name,args.first() ); + return obj; + } + + static TDEInstance *instance() + { + if ( !s_instance ) + s_instance = new TDEInstance( "konqiconview" ); + return s_instance; + } + + static KonqPropsView *defaultViewProps() + { + if ( !s_defaultViewProps ) + s_defaultViewProps = new KonqPropsView( instance(), 0L ); + + return s_defaultViewProps; + } + + private: + static TDEInstance *s_instance; + static KonqPropsView *s_defaultViewProps; +}; + +TDEInstance *KonqIconViewFactory::s_instance = 0; +KonqPropsView *KonqIconViewFactory::s_defaultViewProps = 0; + + +K_EXPORT_COMPONENT_FACTORY( konq_iconview, KonqIconViewFactory ) + + +IconViewBrowserExtension::IconViewBrowserExtension( KonqKfmIconView *iconView ) + : KonqDirPartBrowserExtension( iconView ) +{ + m_iconView = iconView; + m_bSaveViewPropertiesLocally = false; +} + +int IconViewBrowserExtension::xOffset() +{ + return m_iconView->iconViewWidget()->contentsX(); +} + +int IconViewBrowserExtension::yOffset() +{ + return m_iconView->iconViewWidget()->contentsY(); +} + +void IconViewBrowserExtension::reparseConfiguration() +{ + KonqFMSettings::reparseConfiguration(); + // m_pProps is a problem here (what is local, what is global ?) + // but settings is easy : + if ( m_iconView->iconViewWidget()->initConfig( false ) ) + m_iconView->iconViewWidget()->arrangeItemsInGrid(); // called if the font changed. +} + +void IconViewBrowserExtension::trash() +{ + KonqOperations::del(m_iconView->iconViewWidget(), + KonqOperations::TRASH, + m_iconView->iconViewWidget()->selectedUrls( KonqIconViewWidget::MostLocalUrls )); +} + +void IconViewBrowserExtension::properties() +{ + (void) new KPropertiesDialog( m_iconView->iconViewWidget()->selectedFileItems() ); +} + +void IconViewBrowserExtension::editMimeType() +{ + KFileItem * item = m_iconView->iconViewWidget()->selectedFileItems().first(); + KonqOperations::editMimeType( item->mimetype() ); +} + +void IconViewBrowserExtension::setSaveViewPropertiesLocally( bool value ) +{ + m_iconView->m_pProps->setSaveViewPropertiesLocally( value ); +} + +void IconViewBrowserExtension::setNameFilter( const TQString &nameFilter ) +{ + //kdDebug(1202) << "IconViewBrowserExtension::setNameFilter " << nameFilter << endl; + m_iconView->m_nameFilter = nameFilter; +} + +KonqKfmIconView::KonqKfmIconView( TQWidget *parentWidget, TQObject *parent, const char *name, const TQString& mode ) + : KonqDirPart( parent, name ) + , m_bNeedSetCurrentItem( false ) + , m_pEnsureVisible( 0 ) + , m_paOutstandingOverlaysTimer( 0 ) + , m_paOutstandingFreeSpaceOverlaysTimer( 0 ) + , m_pTimeoutRefreshTimer( 0 ) + , m_itemDict( 43 ) +{ + kdDebug(1202) << "+KonqKfmIconView" << endl; + + setBrowserExtension( new IconViewBrowserExtension( this ) ); + + // Create a properties instance for this view + m_pProps = new KonqPropsView( KonqIconViewFactory::instance(), KonqIconViewFactory::defaultViewProps() ); + + m_pIconView = new KonqIconViewWidget( parentWidget, "qiconview" ); + m_pIconView->initConfig( true ); + + connect( m_pIconView, TQT_SIGNAL(imagePreviewFinished()), + this, TQT_SLOT(slotRenderingFinished())); + + // connect up the icon inc/dec signals + connect( m_pIconView, TQT_SIGNAL(incIconSize()), + this, TQT_SLOT(slotIncIconSize())); + connect( m_pIconView, TQT_SIGNAL(decIconSize()), + this, TQT_SLOT(slotDecIconSize())); + + // pass signals to the extension + connect( m_pIconView, TQT_SIGNAL( enableAction( const char *, bool ) ), + m_extension, TQT_SIGNAL( enableAction( const char *, bool ) ) ); + + // signals from konqdirpart (for BC reasons) + connect( this, TQT_SIGNAL( findOpened( KonqDirPart * ) ), TQT_SLOT( slotKFindOpened() ) ); + connect( this, TQT_SIGNAL( findClosed( KonqDirPart * ) ), TQT_SLOT( slotKFindClosed() ) ); + + setWidget( m_pIconView ); + m_mimeTypeResolver = new KMimeTypeResolver(this); + + setInstance( KonqIconViewFactory::instance() ); + + setXMLFile( "konq_iconview.rc" ); + + // Don't repaint on configuration changes during construction + m_bInit = true; + + m_paDotFiles = new TDEToggleAction( i18n( "Show &Hidden Files" ), 0, this, TQT_SLOT( slotShowDot() ), + actionCollection(), "show_dot" ); +// m_paDotFiles->setCheckedState(i18n("Hide &Hidden Files")); + m_paDotFiles->setToolTip( i18n( "Toggle displaying of hidden dot files" ) ); + + m_paDirectoryOverlays = new TDEToggleAction( i18n( "&Folder Icons Reflect Contents" ), 0, this, TQT_SLOT( slotShowDirectoryOverlays() ), + actionCollection(), "show_directory_overlays" ); + + m_paFreeSpaceOverlays = new TDEToggleAction( i18n( "&Media Icons Reflect Free Space" ), 0, this, TQT_SLOT( slotShowFreeSpaceOverlays() ), + actionCollection(), "show_free_space_overlays" ); + + m_pamPreview = new TDEActionMenu( i18n( "&Preview" ), actionCollection(), "iconview_preview" ); + + m_paEnablePreviews = new TDEToggleAction( i18n("Enable Previews"), 0, actionCollection(), "iconview_preview_all" ); + m_paEnablePreviews->setCheckedState( i18n("Disable Previews") ); + connect( m_paEnablePreviews, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotPreview( bool ) ) ); + m_paEnablePreviews->setIcon("thumbnail"); + m_pamPreview->insert( m_paEnablePreviews ); + m_pamPreview->insert( new TDEActionSeparator(this) ); + + TDETrader::OfferList plugins = TDETrader::self()->query( "ThumbCreator" ); + TQMap< TQString, TDEToggleAction* > previewActions; + for ( TDETrader::OfferList::ConstIterator it = plugins.begin(); it != plugins.end(); ++it ) + { + if ( TDEToggleAction*& preview = previewActions[ ( *it )->name() ] ) + preview->setName( TQCString( preview->name() ) + ',' + ( *it )->desktopEntryName().latin1() ); + else + { + preview = new TDEToggleAction( (*it)->name(), 0, actionCollection(), (*it)->desktopEntryName().latin1() ); + connect( preview, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotPreview( bool ) ) ); + m_pamPreview->insert( preview ); + m_paPreviewPlugins.append( preview ); + } + } + TDEToggleAction *soundPreview = new TDEToggleAction( i18n("Sound Files"), 0, actionCollection(), "audio/" ); + connect( soundPreview, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotPreview( bool ) ) ); + m_pamPreview->insert( soundPreview ); + m_paPreviewPlugins.append( soundPreview ); + + // m_pamSort = new TDEActionMenu( i18n( "Sort..." ), actionCollection(), "sort" ); + + TDEToggleAction *aSortByNameCS = new TDERadioAction( i18n( "By Name (Case Sensitive)" ), 0, actionCollection(), "sort_nc" ); + TDEToggleAction *aSortByNameCI = new TDERadioAction( i18n( "By Name (Case Insensitive)" ), 0, actionCollection(), "sort_nci" ); + TDEToggleAction *aSortBySize = new TDERadioAction( i18n( "By Size" ), 0, actionCollection(), "sort_size" ); + TDEToggleAction *aSortByType = new TDERadioAction( i18n( "By Type" ), 0, actionCollection(), "sort_type" ); + TDEToggleAction *aSortByDate = new TDERadioAction( i18n( "By Date" ), 0, actionCollection(), "sort_date" ); + + aSortByNameCS->setExclusiveGroup( "sorting" ); + aSortByNameCI->setExclusiveGroup( "sorting" ); + aSortBySize->setExclusiveGroup( "sorting" ); + aSortByType->setExclusiveGroup( "sorting" ); + aSortByDate->setExclusiveGroup( "sorting" ); + + aSortByNameCS->setChecked( false ); + aSortByNameCI->setChecked( false ); + aSortBySize->setChecked( false ); + aSortByType->setChecked( false ); + aSortByDate->setChecked( false ); + + connect( aSortByNameCS, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotSortByNameCaseSensitive( bool ) ) ); + connect( aSortByNameCI, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotSortByNameCaseInsensitive( bool ) ) ); + connect( aSortBySize, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotSortBySize( bool ) ) ); + connect( aSortByType, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotSortByType( bool ) ) ); + connect( aSortByDate, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotSortByDate( bool ) ) ); + + //enable menu item representing the saved sorting criterion + TQString sortcrit = KonqIconViewFactory::defaultViewProps()->sortCriterion(); + TDERadioAction *sort_action = tqt_dynamic_cast(actionCollection()->action(sortcrit.latin1())); + if(sort_action!=NULL) sort_action->activate(); + + m_paSortDirsFirst = new TDEToggleAction( i18n( "Folders First" ), 0, actionCollection(), "sort_directoriesfirst" ); + TDEToggleAction *aSortDescending = new TDEToggleAction( i18n( "Descending" ), 0, actionCollection(), "sort_descend" ); + + m_paSortDirsFirst->setChecked( KonqIconViewFactory::defaultViewProps()->isDirsFirst() ); + + connect( aSortDescending, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotSortDescending() ) ); + connect( m_paSortDirsFirst, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotSortDirsFirst() ) ); + + //enable stored settings + slotSortDirsFirst(); + if (KonqIconViewFactory::defaultViewProps()->isDescending()) + { + aSortDescending->setChecked(true); + m_pIconView->setSorting(true,true);//enable sort ascending in QIconview + slotSortDescending();//invert sorting (now descending) and actually resort items + } + + /* + m_pamSort->insert( aSortByNameCS ); + m_pamSort->insert( aSortByNameCI ); + m_pamSort->insert( aSortBySize ); + + m_pamSort->popupMenu()->insertSeparator(); + + m_pamSort->insert( aSortDescending ); + */ + m_paSelect = new TDEAction( i18n( "Se&lect..." ), CTRL+Key_Plus, this, TQT_SLOT( slotSelect() ), + actionCollection(), "select" ); + m_paUnselect = new TDEAction( i18n( "Unselect..." ), CTRL+Key_Minus, this, TQT_SLOT( slotUnselect() ), + actionCollection(), "unselect" ); + m_paSelectAll = KStdAction::selectAll( this, TQT_SLOT( slotSelectAll() ), actionCollection(), "selectall" ); + m_paUnselectAll = new TDEAction( i18n( "Unselect All" ), CTRL+Key_U, this, TQT_SLOT( slotUnselectAll() ), + actionCollection(), "unselectall" ); + m_paInvertSelection = new TDEAction( i18n( "&Invert Selection" ), CTRL+Key_Asterisk, + this, TQT_SLOT( slotInvertSelection() ), + actionCollection(), "invertselection" ); + + m_paSelect->setToolTip( i18n( "Allows selecting of file or folder items based on a given mask" ) ); + m_paUnselect->setToolTip( i18n( "Allows unselecting of file or folder items based on a given mask" ) ); + m_paSelectAll->setToolTip( i18n( "Selects all items" ) ); + m_paUnselectAll->setToolTip( i18n( "Unselects all selected items" ) ); + m_paInvertSelection->setToolTip( i18n( "Inverts the current selection of items" ) ); + + //m_paBottomText = new TDEToggleAction( i18n( "Text at &Bottom" ), 0, actionCollection(), "textbottom" ); + //m_paRightText = new TDEToggleAction( i18n( "Text at &Right" ), 0, actionCollection(), "textright" ); + //m_paBottomText->setExclusiveGroup( "TextPos" ); + //m_paRightText->setExclusiveGroup( "TextPos" ); + //connect( m_paBottomText, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotTextBottom( bool ) ) ); + //connect( m_paRightText, TQT_SIGNAL( toggled( bool ) ), this, TQT_SLOT( slotTextRight( bool ) ) ); + + connect( m_pIconView, TQT_SIGNAL( executed( TQIconViewItem * ) ), + this, TQT_SLOT( slotReturnPressed( TQIconViewItem * ) ) ); + connect( m_pIconView, TQT_SIGNAL( returnPressed( TQIconViewItem * ) ), + this, TQT_SLOT( slotReturnPressed( TQIconViewItem * ) ) ); + + connect( m_pIconView, TQT_SIGNAL( onItem( TQIconViewItem * ) ), + this, TQT_SLOT( slotOnItem( TQIconViewItem * ) ) ); + + connect( m_pIconView, TQT_SIGNAL( onViewport() ), + this, TQT_SLOT( slotOnViewport() ) ); + + connect( m_pIconView, TQT_SIGNAL( mouseButtonPressed(int, TQIconViewItem*, const TQPoint&)), + this, TQT_SLOT( slotMouseButtonPressed(int, TQIconViewItem*, const TQPoint&)) ); + connect( m_pIconView, TQT_SIGNAL( mouseButtonClicked(int, TQIconViewItem*, const TQPoint&)), + this, TQT_SLOT( slotMouseButtonClicked(int, TQIconViewItem*, const TQPoint&)) ); + connect( m_pIconView, TQT_SIGNAL( contextMenuRequested(TQIconViewItem*, const TQPoint&)), + this, TQT_SLOT( slotContextMenuRequested(TQIconViewItem*, const TQPoint&)) ); + connect( m_pIconView, TQT_SIGNAL( mouseDoubleClicked(TQIconViewItem*)), + this, TQT_SLOT( slotDoubleClicked(TQIconViewItem*)) ); + + // Signals needed to implement the spring loading folders behavior + connect( m_pIconView, TQT_SIGNAL( held( TQIconViewItem * ) ), + this, TQT_SLOT( slotDragHeld( TQIconViewItem * ) ) ); + connect( m_pIconView, TQT_SIGNAL( dragEntered( bool ) ), + this, TQT_SLOT( slotDragEntered( bool ) ) ); + connect( m_pIconView, TQT_SIGNAL( dragLeft() ), + this, TQT_SLOT( slotDragLeft() ) ); + connect( m_pIconView, TQT_SIGNAL( dragMove( bool ) ), + this, TQT_SLOT( slotDragMove( bool ) ) ); + connect( m_pIconView, TQT_SIGNAL( dragFinished() ), + this, TQT_SLOT( slotDragFinished() ) ); + + // Create the directory lister + m_dirLister = new KDirLister( true ); + setDirLister( m_dirLister ); + m_dirLister->setMainWindow(m_pIconView->topLevelWidget()); + + connect( m_dirLister, TQT_SIGNAL( started( const KURL & ) ), + this, TQT_SLOT( slotStarted() ) ); + connect( m_dirLister, TQT_SIGNAL( completed() ), this, TQT_SLOT( slotCompleted() ) ); + connect( m_dirLister, TQT_SIGNAL( canceled( const KURL& ) ), this, TQT_SLOT( slotCanceled( const KURL& ) ) ); + connect( m_dirLister, TQT_SIGNAL( clear() ), this, TQT_SLOT( slotClear() ) ); + connect( m_dirLister, TQT_SIGNAL( newItems( const KFileItemList& ) ), + this, TQT_SLOT( slotNewItems( const KFileItemList& ) ) ); + connect( m_dirLister, TQT_SIGNAL( deleteItem( KFileItem * ) ), + this, TQT_SLOT( slotDeleteItem( KFileItem * ) ) ); + connect( m_dirLister, TQT_SIGNAL( refreshItems( const KFileItemList& ) ), + this, TQT_SLOT( slotRefreshItems( const KFileItemList& ) ) ); + connect( m_dirLister, TQT_SIGNAL( redirection( const KURL & ) ), + this, TQT_SLOT( slotRedirection( const KURL & ) ) ); + connect( m_dirLister, TQT_SIGNAL( itemsFilteredByMime(const KFileItemList& ) ), + TQT_SIGNAL( itemsFilteredByMime(const KFileItemList& ) ) ); + connect( m_dirLister, TQT_SIGNAL( infoMessage( const TQString& ) ), + extension(), TQT_SIGNAL( infoMessage( const TQString& ) ) ); + connect( m_dirLister, TQT_SIGNAL( percent( int ) ), + extension(), TQT_SIGNAL( loadingProgress( int ) ) ); + connect( m_dirLister, TQT_SIGNAL( speed( int ) ), + extension(), TQT_SIGNAL( speedProgress( int ) ) ); + + // Now we may react to configuration changes + m_bInit = false; + + m_bLoading = true; + m_bNeedAlign = false; + m_bNeedEmitCompleted = false; + m_bUpdateContentsPosAfterListing = false; + m_bDirPropertiesChanged = true; + m_bPreviewRunningBeforeCloseURL = false; + m_pIconView->setResizeMode( TQIconView::Adjust ); + + connect( m_pIconView, TQT_SIGNAL( selectionChanged() ), + this, TQT_SLOT( slotSelectionChanged() ) ); + + // Respect kcmkonq's configuration for word-wrap icon text. + // If we want something else, we have to adapt the configuration or remove it... + m_pIconView->setIconTextHeight(KonqFMSettings::settings()->iconTextHeight()); + + // Finally, determine initial grid size again, with those parameters + // m_pIconView->calculateGridX(); + + setViewMode( mode ); +} + +KonqKfmIconView::~KonqKfmIconView() +{ + // Before anything else, stop the image preview. It might use our fileitems, + // and it will only be destroyed togetierh with our widget + m_pIconView->stopImagePreview(); + + kdDebug(1202) << "-KonqKfmIconView" << endl; + m_dirLister->disconnect( this ); + delete m_dirLister; + delete m_mimeTypeResolver; + delete m_pProps; + //no need for that, KParts deletes our widget already ;-) + // delete m_pIconView; +} + +const KFileItem * KonqKfmIconView::currentItem() +{ + return m_pIconView->currentItem() ? static_cast(m_pIconView->currentItem())->item() : 0L; +} + +void KonqKfmIconView::slotPreview( bool toggle ) +{ + TQCString name = TQT_TQOBJECT_CONST(sender())->name(); // e.g. clipartthumbnail (or audio/, special case) + if (name == "iconview_preview_all") + { + m_pProps->setShowingPreview( toggle ); + m_pIconView->setPreviewSettings( m_pProps->previewSettings() ); + if ( !toggle ) + { + kdDebug() << "KonqKfmIconView::slotPreview stopping all previews for " << name << endl; + m_pIconView->disableSoundPreviews(); + + bool previewRunning = m_pIconView->isPreviewRunning(); + if ( previewRunning ) + m_pIconView->stopImagePreview(); + m_pIconView->setIcons( m_pIconView->iconSize(), "*" ); + } + else + { + m_pIconView->startImagePreview( m_pProps->previewSettings(), true ); + } + for ( m_paPreviewPlugins.first(); m_paPreviewPlugins.current(); m_paPreviewPlugins.next() ) + m_paPreviewPlugins.current()->setEnabled( toggle ); + } + else + { + TQStringList types = TQStringList::split( ',', name ); + for ( TQStringList::ConstIterator it = types.begin(); it != types.end(); ++it ) + { + m_pProps->setShowingPreview( *it, toggle ); + m_pIconView->setPreviewSettings( m_pProps->previewSettings() ); + if ( !toggle ) + { + kdDebug() << "KonqKfmIconView::slotPreview stopping image preview for " << *it << endl; + if ( *it == "audio/" ) + m_pIconView->disableSoundPreviews(); + else + { + KService::Ptr serv = KService::serviceByDesktopName( *it ); + Q_ASSERT( serv != 0L ); + if ( serv ) { + bool previewRunning = m_pIconView->isPreviewRunning(); + if ( previewRunning ) + m_pIconView->stopImagePreview(); + TQStringList mimeTypes = serv->property("MimeTypes").toStringList(); + m_pIconView->setIcons( m_pIconView->iconSize(), mimeTypes ); + if ( previewRunning ) + m_pIconView->startImagePreview( m_pProps->previewSettings(), false ); + } + } + } + else + { + m_pIconView->startImagePreview( m_pProps->previewSettings(), true ); + } + } + } +} + +void KonqKfmIconView::slotShowDot() +{ + m_pProps->setShowingDotFiles( !m_pProps->isShowingDotFiles() ); + m_dirLister->setShowingDotFiles( m_pProps->isShowingDotFiles() ); + m_dirLister->emitChanges(); + //we don't want the non-dot files to remain where they are + m_bNeedAlign = true; + slotCompleted(); +} + +void KonqKfmIconView::slotShowDirectoryOverlays() +{ + bool show = !m_pProps->isShowingDirectoryOverlays(); + + m_pProps->setShowingDirectoryOverlays( show ); + + for ( TQIconViewItem *item = m_pIconView->firstItem(); item; item = item->nextItem() ) + { + KFileIVI* kItem = static_cast(item); + if ( !kItem->item()->isDir() ) continue; + + if (show) { + showDirectoryOverlay(kItem); + } else { + kItem -> setShowDirectoryOverlay(false); + } + } + + m_pIconView->updateContents(); +} + +void KonqKfmIconView::slotShowFreeSpaceOverlays() +{ + bool show = !m_pProps->isShowingFreeSpaceOverlays(); + + m_pProps->setShowingFreeSpaceOverlays( show ); + + for ( TQIconViewItem *item = m_pIconView->firstItem(); item; item = item->nextItem() ) + { + KFileIVI* kItem = static_cast(item); + if ( !kItem->item()->isDir() ) continue; + + if (show) { + showFreeSpaceOverlay(kItem); + } else { + kItem -> setShowFreeSpaceOverlay(false); + } + } + + m_pIconView->updateContents(); +} + +void KonqKfmIconView::slotSelect() +{ + bool ok; + TQString pattern = KInputDialog::getText( TQString::null, + i18n( "Select files:" ), "*", &ok, m_pIconView ); + if ( ok ) + { + TQRegExp re( pattern, true, true ); + + m_pIconView->blockSignals( true ); + + TQIconViewItem *it = m_pIconView->firstItem(); + while ( it ) { + if ( it->isVisible() ) { + if ( re.exactMatch( it->text() ) ) { + it->setSelected( true, true ); + } + } + else { + it->setSelected( false, true ); + } + it = it->nextItem(); + } + + m_pIconView->blockSignals( false ); + + // do this once, not for each item + m_pIconView->slotSelectionChanged(); + slotSelectionChanged(); + } +} + +void KonqKfmIconView::slotUnselect() +{ + bool ok; + TQString pattern = KInputDialog::getText( TQString::null, + i18n( "Unselect files:" ), "*", &ok, m_pIconView ); + if ( ok ) + { + TQRegExp re( pattern, true, true ); + + m_pIconView->blockSignals( true ); + + TQIconViewItem *it = m_pIconView->firstItem(); + while ( it ) { + if ( it->isVisible() ) { + if ( re.exactMatch( it->text() ) ) { + it->setSelected( false, true ); + } + } + else { + it->setSelected( false, true ); + } + it = it->nextItem(); + } + + m_pIconView->blockSignals( false ); + + // do this once, not for each item + m_pIconView->slotSelectionChanged(); + slotSelectionChanged(); + } +} + +void KonqKfmIconView::slotSelectAll() +{ + m_pIconView->selectAll( true ); +} + +void KonqKfmIconView::slotUnselectAll() +{ + m_pIconView->selectAll( false ); +} + +void KonqKfmIconView::slotInvertSelection() +{ + m_pIconView->invertSelection( ); +} + +void KonqKfmIconView::slotSortByNameCaseSensitive( bool toggle ) +{ + if ( !toggle ) + return; + + KonqIconViewFactory::defaultViewProps()->setSortCriterion("sort_nc"); + setupSorting( NameCaseSensitive ); +} + +void KonqKfmIconView::slotSortByNameCaseInsensitive( bool toggle ) +{ + if ( !toggle ) + return; + + KonqIconViewFactory::defaultViewProps()->setSortCriterion("sort_nci"); + setupSorting( NameCaseInsensitive ); +} + +void KonqKfmIconView::slotSortBySize( bool toggle ) +{ + if ( !toggle ) + return; + + KonqIconViewFactory::defaultViewProps()->setSortCriterion("sort_size"); + setupSorting( Size ); +} + +void KonqKfmIconView::slotSortByType( bool toggle ) +{ + if ( !toggle ) + return; + + KonqIconViewFactory::defaultViewProps()->setSortCriterion("sort_type"); + setupSorting( Type ); +} + +void KonqKfmIconView::slotSortByDate( bool toggle ) +{ + if( !toggle) + return; + + KonqIconViewFactory::defaultViewProps()->setSortCriterion("sort_date"); + setupSorting( Date ); +} + +void KonqKfmIconView::setupSorting( SortCriterion criterion ) +{ + m_eSortCriterion = criterion; + + setupSortKeys(); + + m_pIconView->sort( m_pIconView->sortDirection() ); +} + +void KonqKfmIconView::slotSortDescending() +{ + if ( m_pIconView->sortDirection() ) + m_pIconView->setSorting( true, false ); + else + m_pIconView->setSorting( true, true ); + + setupSortKeys(); // keys have to change, for directories + + m_pIconView->sort( m_pIconView->sortDirection() ); + + KonqIconViewFactory::defaultViewProps()->setDescending( !m_pIconView->sortDirection() ); +} + +void KonqKfmIconView::slotSortDirsFirst() +{ + m_pIconView->setSortDirectoriesFirst( m_paSortDirsFirst->isChecked() ); + + setupSortKeys(); + + m_pIconView->sort( m_pIconView->sortDirection() ); + + KonqIconViewFactory::defaultViewProps()->setDirsFirst( m_paSortDirsFirst->isChecked() ); +} + +void KonqKfmIconView::newIconSize( int size ) +{ + //Either of the sizes can be 0 to indicate the default (Desktop) size icons. + //check for that when checking whether the size changed + int effSize = size; + if (effSize == 0) + effSize = IconSize(TDEIcon::Desktop); + + int oldEffSize = m_pIconView->iconSize(); + if (oldEffSize == 0) + oldEffSize = IconSize(TDEIcon::Desktop); + + // Make sure all actions are initialized. + KonqDirPart::newIconSize( size ); + + if ( effSize == oldEffSize ) + return; + + // Stop a preview job that might be running + m_pIconView->stopImagePreview(); + + // Set icons size, arrage items in grid and repaint the whole view + m_pIconView->setIcons( size ); + + // If previews are enabled start a new job + if ( m_pProps->isShowingPreview() ) + m_pIconView->startImagePreview( m_pProps->previewSettings(), true ); +} + +bool KonqKfmIconView::doCloseURL() +{ + m_dirLister->stop(); + + m_mimeTypeResolver->m_lstPendingMimeIconItems.clear(); + + m_bPreviewRunningBeforeCloseURL = m_pIconView->isPreviewRunning(); + m_pIconView->stopImagePreview(); + return true; +} + +void KonqKfmIconView::slotReturnPressed( TQIconViewItem *item ) +{ + if ( !item ) + return; + + item->setSelected( false, true ); + m_pIconView->visualActivate(item); + + KFileItem *fileItem = (static_cast(item))->item(); + if ( !fileItem ) + return; + lmbClicked( fileItem ); +} + +void KonqKfmIconView::slotDragHeld( TQIconViewItem *item ) +{ + kdDebug() << "KonqKfmIconView::slotDragHeld()" << endl; + + // This feature is not usable if the user wants one window per folder + if ( KonqFMSettings::settings()->alwaysNewWin() ) + return; + + if ( !item ) + return; + + KFileItem *fileItem = (static_cast(item))->item(); + + SpringLoadingManager::self().springLoadTrigger(this, fileItem, item); +} + +void KonqKfmIconView::slotDragEntered( bool ) +{ + if ( SpringLoadingManager::exists() ) + SpringLoadingManager::self().dragEntered(this); +} + +void KonqKfmIconView::slotDragLeft() +{ + kdDebug() << "KonqKfmIconView::slotDragLeft()" << endl; + + if ( SpringLoadingManager::exists() ) + SpringLoadingManager::self().dragLeft(this); +} + +void KonqKfmIconView::slotDragMove( bool accepted ) +{ + if ( !accepted ) + emit setStatusBarText( i18n( "You cannot drop any items in a directory in which you do not have write permission" ) ); +} + +void KonqKfmIconView::slotDragFinished() +{ + kdDebug() << "KonqKfmIconView::slotDragFinished()" << endl; + + if ( SpringLoadingManager::exists() ) + SpringLoadingManager::self().dragFinished(this); +} + + +void KonqKfmIconView::slotContextMenuRequested(TQIconViewItem* _item, const TQPoint& _global) +{ + const KFileItemList items = m_pIconView->selectedFileItems(); + if ( items.isEmpty() ) + return; + + KParts::BrowserExtension::PopupFlags popupFlags = KParts::BrowserExtension::DefaultPopupItems; + + KFileIVI* i = static_cast(_item); + if (i) + i->setSelected( true, true /* don't touch other items */ ); + + KFileItem * rootItem = m_dirLister->rootItem(); + if ( rootItem ) { + KURL parentDirURL = rootItem->url(); + // Check if parentDirURL applies to the selected items (usually yes, but not with search results) + TQPtrListIterator kit( items ); + for ( ; kit.current(); ++kit ) + if ( kit.current()->url().directory( 1 ) != rootItem->url().path() ) + parentDirURL = KURL(); + // If rootItem is the parent of the selected items, then we can use isWritable() on it. + if ( !parentDirURL.isEmpty() && !rootItem->isWritable() ) + popupFlags |= KParts::BrowserExtension::NoDeletion; + } + + emit m_extension->popupMenu( 0L, _global, items, KParts::URLArgs(), popupFlags); +} + +void KonqKfmIconView::slotMouseButtonPressed(int _button, TQIconViewItem* _item, const TQPoint&) +{ + if ( _button == Qt::RightButton && !_item ) + { + // Right click on viewport + KFileItem * item = m_dirLister->rootItem(); + bool delRootItem = false; + if ( ! item ) + { + if ( m_bLoading ) + { + kdDebug(1202) << "slotViewportRightClicked : still loading and no root item -> dismissed" << endl; + return; // too early, '.' not yet listed + } + else + { + // We didn't get a root item (e.g. over FTP) + // We have to create a dummy item. I tried using KonqOperations::statURL, + // but this was leading to a huge delay between the RMB and the popup. Bad. + // But KonqPopupMenu now takes care of stating before opening properties. + item = new KFileItem( S_IFDIR, (mode_t)-1, url() ); + delRootItem = true; + } + } + + KFileItemList items; + items.append( item ); + + KParts::BrowserExtension::PopupFlags popupFlags = KParts::BrowserExtension::ShowNavigationItems | KParts::BrowserExtension::ShowUp; + + emit m_extension->popupMenu( 0L, TQCursor::pos(), items, KParts::URLArgs(), popupFlags ); + + if ( delRootItem ) + delete item; // we just created it + } +} + +void KonqKfmIconView::slotMouseButtonClicked(int _button, TQIconViewItem* _item, const TQPoint& ) +{ + if( _button == Qt::MidButton ) + mmbClicked( _item ? static_cast(_item)->item() : 0L ); +} + +void KonqKfmIconView::slotDoubleClicked(TQIconViewItem *_item) +{ + if (!_item) + { + KParts::URLArgs args; + args.trustedSource = true; + KURL upURL = m_dirLister->url().upURL(); + if (!upURL.isEmpty()) + { + m_extension->openURLRequest(upURL, args); + } + } +} + +void KonqKfmIconView::slotStarted() +{ + // Only emit started if this comes after openURL, i.e. it's not for an update. + // We don't want to start a spinning wheel during updates. + if ( m_bLoading ) + emit started( 0 ); + + // An update may come in while we are still processing icons... + // So don't clear the list. + //m_mimeTypeResolver->m_lstPendingMimeIconItems.clear(); +} + +void KonqKfmIconView::slotCanceled() +{ + // Called by kfindpart. Not by kdirlister. + slotCanceled( m_pIconView->url() ); +} + +void KonqKfmIconView::slotCanceled( const KURL& url ) +{ + // Check if this canceled() signal is about the URL we're listing. + // It could be about the URL we were listing, and openURL() aborted it. + if ( m_bLoading && url.equals( m_pIconView->url(), true ) ) + { + emit canceled( TQString::null ); + m_bLoading = false; + } + + // Stop the "refresh if busy too long" timer because a viewport + // update is coming. + if ( m_pTimeoutRefreshTimer && m_pTimeoutRefreshTimer->isActive() ) + m_pTimeoutRefreshTimer->stop(); + + // See slotCompleted(). If a listing gets canceled, it doesn't emit + // the completed() signal, so handle that case. + if ( !m_pIconView->viewport()->isUpdatesEnabled() ) + { + m_pIconView->viewport()->setUpdatesEnabled( true ); + m_pIconView->viewport()->repaint(); + } + if ( m_pEnsureVisible ){ + m_pIconView->ensureItemVisible( m_pEnsureVisible ); + m_pEnsureVisible = 0; + } +} + +void KonqKfmIconView::slotCompleted() +{ + // Stop the "refresh if busy too long" timer because a viewport + // update is coming. + if ( m_pTimeoutRefreshTimer && m_pTimeoutRefreshTimer->isActive() ) { + m_pTimeoutRefreshTimer->stop(); + } + + // If updates to the viewport are still blocked (so slotNewItems() has + // not been called), a viewport repaint is forced. + if ( !m_pIconView->viewport()->isUpdatesEnabled() ) + { + m_pIconView->viewport()->setUpdatesEnabled( true ); + m_pIconView->viewport()->repaint(); + } + + // Root item ? Store root item in konqiconviewwidget (whether 0L or not) + m_pIconView->setRootItem( m_dirLister->rootItem() ); + + // only after initial listing, not after updates + // If we don't set a current item, the iconview has none (one more keypress needed) + // but it appears on focusin... qiconview bug, Reggie acknowledged it LONG ago (07-2000). + if ( m_bNeedSetCurrentItem ) + { + m_pIconView->setCurrentItem( m_pIconView->firstItem() ); + m_bNeedSetCurrentItem = false; + } + + if ( m_bUpdateContentsPosAfterListing ) { + m_pIconView->setContentsPos( extension()->urlArgs().xOffset, + extension()->urlArgs().yOffset ); + } + + if ( m_pEnsureVisible ) { + m_pIconView->ensureItemVisible( m_pEnsureVisible ); + m_pEnsureVisible = 0; + } + + m_bUpdateContentsPosAfterListing = false; + + if ( !m_pIconView->firstItem() ) { + resetCount(); + } + + slotOnViewport(); + + // slotRenderingFinished will do it + m_bNeedEmitCompleted = true; + + if (m_pProps->isShowingPreview()) { + m_mimeTypeResolver->start( 0 ); // We need the mimetypes asap + } + else + { + slotRenderingFinished(); // emit completed, we don't want the wheel... + // to keep turning while we find mimetypes in the background + m_mimeTypeResolver->start( 10 ); + } + + m_bLoading = false; + + // Disable cut icons if any + slotClipboardDataChanged(); +} + +void KonqKfmIconView::slotNewItems( const KFileItemList& entries ) +{ + // Stop the autorefresh timer since data to display has arrived and will + // be drawn in moments + if ( m_pTimeoutRefreshTimer && m_pTimeoutRefreshTimer->isActive() ) { + m_pTimeoutRefreshTimer->stop(); + } + // We need to disable graphics updates on the iconview when + // inserting items, or else a blank paint operation will be + // performed on the top-left corner for each inserted item! + m_pIconView->setUpdatesEnabled( false ); + for (KFileItemListIterator it(entries); it.current(); ++it) + { + //kdDebug(1202) << "KonqKfmIconView::slotNewItem(...)" << _fileitem->url().url() << endl; + KFileIVI* item = new KFileIVI( m_pIconView, *it, m_pIconView->iconSize() ); + item->setRenameEnabled( false ); + + KFileItem* fileItem = item->item(); + + if ( !m_itemsToSelect.isEmpty() ) { + TQStringList::Iterator tsit = m_itemsToSelect.find( fileItem->name() ); + if ( tsit != m_itemsToSelect.end() ) { + m_itemsToSelect.remove( tsit ); + m_pIconView->setSelected( item, true, true ); + if ( m_bNeedSetCurrentItem ){ + m_pIconView->setCurrentItem( item ); + if( !m_pEnsureVisible ) + m_pEnsureVisible = item; + m_bNeedSetCurrentItem = false; + } + } + } + + if ( fileItem->isDir() && m_pProps->isShowingDirectoryOverlays() ) { + showDirectoryOverlay(item); + } + if ( fileItem->mimetypeFast().startsWith("media/") && fileItem->mimetypeFast().contains("_mounted") && m_pProps->isShowingFreeSpaceOverlays() ) { + showFreeSpaceOverlay(item); + } + + TQString key; + + switch ( m_eSortCriterion ) + { + case NameCaseSensitive: key = item->text(); break; + case NameCaseInsensitive: key = item->text().lower(); break; + case Size: key = makeSizeKey( item ); break; + case Type: key = item->item()->mimetype()+ "\008" +item->text().lower(); break; // ### slows down listing :-( + case Date: + { + TQDateTime dayt; + dayt.setTime_t(item->item()->time(TDEIO::UDS_MODIFICATION_TIME )); + key = dayt.toString("yyyyMMddhhmmss"); + break; + } + default: Q_ASSERT(0); + } + + item->setKey( key ); + + //kdDebug() << "KonqKfmIconView::slotNewItems " << (*it)->url().url() << " " << (*it)->mimeTypePtr()->name() << " mimetypeknown:" << (*it)->isMimeTypeKnown() << endl; + if ( !(*it)->isMimeTypeKnown() ) { + m_mimeTypeResolver->m_lstPendingMimeIconItems.append( item ); + } + + m_itemDict.insert( *it, item ); + } + // After filtering out updates-on-insertions we can re-enable updates + m_pIconView->setUpdatesEnabled( true ); + // Locking the viewport has filtered out blanking and now, since we + // have some items to draw, we can restore updating. + if ( !m_pIconView->viewport()->isUpdatesEnabled() ) { + m_pIconView->viewport()->setUpdatesEnabled( true ); + } + KonqDirPart::newItems( entries ); +} + +void KonqKfmIconView::slotDeleteItem( KFileItem * _fileitem ) +{ + KFileItemList list; + list.append( _fileitem ); + emit m_extension->itemsRemoved( list ); + + if ( _fileitem == m_dirLister->rootItem() ) + { + m_pIconView->stopImagePreview(); + m_pIconView->setRootItem( 0L ); + return; + } + + //kdDebug(1202) << "KonqKfmIconView::slotDeleteItem(...)" << endl; + // we need to find out the iconcontainer item containing the fileitem + KFileIVI * ivi = m_itemDict[ _fileitem ]; + // It can be that we know nothing about this item, e.g. because it's filtered out + // (by default: dot files). KDirLister still tells us about it when it's modified, since + // it doesn't know if we showed it before, and maybe its mimetype changed so we + // might have to hide it now. + if (ivi) + { + m_pIconView->stopImagePreview(); + KonqDirPart::deleteItem( _fileitem ); + + m_mimeTypeResolver->m_lstPendingMimeIconItems.remove( ivi ); + m_itemDict.remove( _fileitem ); + if (m_paOutstandingOverlays.first() == ivi) // Being processed? + m_paOutstandingOverlaysTimer->start(20, true); // Restart processing... + m_paOutstandingOverlays.remove(ivi); + if (m_paOutstandingFreeSpaceOverlays.first() == ivi) // Being processed? + m_paOutstandingFreeSpaceOverlaysTimer->start(20, true); // Restart processing... + m_paOutstandingFreeSpaceOverlays.remove(ivi); + + delete ivi; + } +} + +void KonqKfmIconView::showDirectoryOverlay(KFileIVI* item) +{ + KFileItem* fileItem = item->item(); + + if ( TDEGlobalSettings::showFilePreview( fileItem->url() ) ) { + m_paOutstandingOverlays.append(item); + if (m_paOutstandingOverlays.count() == 1) + { + if (!m_paOutstandingOverlaysTimer) + { + m_paOutstandingOverlaysTimer = new TQTimer(this); + connect(m_paOutstandingOverlaysTimer, TQT_SIGNAL(timeout()), + TQT_SLOT(slotDirectoryOverlayStart())); + } + m_paOutstandingOverlaysTimer->start(20, true); + } + } +} + +void KonqKfmIconView::showFreeSpaceOverlay(KFileIVI* item) +{ + m_paOutstandingFreeSpaceOverlays.append(item); + if (m_paOutstandingFreeSpaceOverlays.count() == 1) + { + if (!m_paOutstandingFreeSpaceOverlaysTimer) + { + m_paOutstandingFreeSpaceOverlaysTimer = new TQTimer(this); + connect(m_paOutstandingFreeSpaceOverlaysTimer, TQT_SIGNAL(timeout()), + TQT_SLOT(slotFreeSpaceOverlayStart())); + } + m_paOutstandingFreeSpaceOverlaysTimer->start(20, true); + } +} + +void KonqKfmIconView::slotDirectoryOverlayStart() +{ + do + { + KFileIVI* item = m_paOutstandingOverlays.first(); + if (!item) + return; // Nothing to do + + KIVDirectoryOverlay* overlay = item->setShowDirectoryOverlay( true ); + + if (overlay) + { + connect( overlay, TQT_SIGNAL( finished() ), this, TQT_SLOT( slotDirectoryOverlayFinished() ) ); + overlay->start(); // Watch out, may emit finished() immediately!! + return; // Let it run.... + } + m_paOutstandingOverlays.removeFirst(); + } while (true); +} + +void KonqKfmIconView::slotFreeSpaceOverlayStart() +{ + do + { + KFileIVI* item = m_paOutstandingFreeSpaceOverlays.first(); + if (!item) + return; // Nothing to do + + KIVFreeSpaceOverlay* overlay = item->setShowFreeSpaceOverlay( true ); + + if (overlay) + { + connect( overlay, TQT_SIGNAL( finished() ), this, TQT_SLOT( slotFreeSpaceOverlayFinished() ) ); + overlay->start(); // Watch out, may emit finished() immediately!! + return; // Let it run.... + } + m_paOutstandingFreeSpaceOverlays.removeFirst(); + } while (true); +} + +void KonqKfmIconView::slotDirectoryOverlayFinished() +{ + m_paOutstandingOverlays.removeFirst(); + + if (m_paOutstandingOverlays.count() > 0) + m_paOutstandingOverlaysTimer->start(0, true); // Don't call directly to prevent deep recursion. +} + +void KonqKfmIconView::slotFreeSpaceOverlayFinished() +{ + m_paOutstandingFreeSpaceOverlays.removeFirst(); + + if (m_paOutstandingFreeSpaceOverlays.count() > 0) + m_paOutstandingFreeSpaceOverlaysTimer->start(0, true); // Don't call directly to prevent deep recursion. +} + +// see also KDesktop::slotRefreshItems +void KonqKfmIconView::slotRefreshItems( const KFileItemList& entries ) +{ + bool bNeedRepaint = false; + bool bNeedPreviewJob = false; + KFileItemListIterator rit(entries); + for (; rit.current(); ++rit) + { + KFileIVI * ivi = m_itemDict[ rit.current() ]; + Q_ASSERT(ivi); + kdDebug() << "KonqKfmIconView::slotRefreshItems '" << rit.current()->name() << "' ivi=" << ivi << endl; + if (ivi) + { + TQSize oldSize = ivi->pixmap()->size(); + if ( ivi->isThumbnail() ) { + bNeedPreviewJob = true; + ivi->invalidateThumbnail(); + } + else { + ivi->refreshIcon( true ); + } + ivi->setText( rit.current()->text() ); + if ( rit.current()->isMimeTypeKnown() ) { + ivi->setMouseOverAnimation( rit.current()->iconName() ); + } + if ( !bNeedRepaint && oldSize != ivi->pixmap()->size() ) { + bNeedRepaint = true; + } + if ( (*rit)->mimetypeFast().startsWith("media/") && m_pProps->isShowingFreeSpaceOverlays() ) { + if ((*rit)->mimetypeFast().contains("_mounted")) { + showFreeSpaceOverlay(ivi); + } + else { + // If not mounted, hide free space overlay + ivi->setShowFreeSpaceOverlay(false); + } + } + } + } + + if ( bNeedPreviewJob && m_pProps->isShowingPreview() ) + { + m_pIconView->startImagePreview( m_pProps->previewSettings(), false ); + } + else + { + // In case we replace a big icon with a small one, need to repaint. + if ( bNeedRepaint ) { + m_pIconView->updateContents(); + } + } + KonqDirPart::refreshItems(entries); // Pass refresh command to KonqDirPart too +} + +void KonqKfmIconView::slotClear() +{ + resetCount(); + + // We're now going to update the view with new contents. To avoid + // meaningless paint operations (such as a clear() just before drawing + // fresh contents) we disable updating the viewport until we'll + // receive some data or a timeout timer expires. + m_pIconView->viewport()->setUpdatesEnabled( false ); + if ( !m_pTimeoutRefreshTimer ) + { + m_pTimeoutRefreshTimer = new TQTimer( this ); + connect( m_pTimeoutRefreshTimer, TQT_SIGNAL( timeout() ), + this, TQT_SLOT( slotRefreshViewport() ) ); + } + m_pTimeoutRefreshTimer->start( 700, true ); + + // Clear contents but don't clear graphics as updates are disabled. + m_pIconView->clear(); + // If directory properties are changed, apply pending changes + // changes are: view background or color, iconsize, enabled previews + if ( m_bDirPropertiesChanged ) + { + m_pProps->applyColors( m_pIconView->viewport() ); + newIconSize( m_pProps->iconSize() ); + m_pIconView->setPreviewSettings( m_pProps->previewSettings() ); + } + + m_mimeTypeResolver->m_lstPendingMimeIconItems.clear(); + m_itemDict.clear(); + // Bug in QIconview IMHO - it should emit selectionChanged() + // (bug reported, but code seems to be that way on purpose) + m_pIconView->slotSelectionChanged(); + slotSelectionChanged(); +} + +void KonqKfmIconView::slotRedirection( const KURL & url ) +{ + const TQString prettyURL = url.pathOrURL(); + emit m_extension->setLocationBarURL( prettyURL ); + emit setWindowCaption( prettyURL ); + m_pIconView->setURL( url ); + m_url = url; +} + +void KonqKfmIconView::slotSelectionChanged() +{ + // Display statusbar info, and emit selectionInfo + KFileItemList lst = m_pIconView->selectedFileItems(); + emitCounts( lst, true ); + + bool itemSelected = lst.count()>0; + m_paUnselect->setEnabled( itemSelected ); + m_paUnselectAll->setEnabled( itemSelected ); + m_paInvertSelection->setEnabled( itemSelected ); +} + +void KonqKfmIconView::determineIcon( KFileIVI * item ) +{ + // kdDebug() << "KonqKfmIconView::determineIcon " << item->item()->name() << endl; + //int oldSerial = item->pixmap()->serialNumber(); + + (void) item->item()->determineMimeType(); + + if (item->item()->isMimeTypeKnown()) { + item->mimeTypeAndIconDetermined(); + } + + item->setIcon( iconSize(), item->state(), true, true ); + item->setMouseOverAnimation( item->item()->iconName() ); +} + +void KonqKfmIconView::mimeTypeDeterminationFinished() +{ + if ( m_pProps->isShowingPreview() ) + { + // TODO if ( m_url.isLocalFile() || m_bAutoPreviewRemote ) + { + // We can do this only when the mimetypes are fully determined, + // since we only do image preview... on images :-) + m_pIconView->startImagePreview( m_pProps->previewSettings(), false ); + return; + } + } + slotRenderingFinished(); +} + +void KonqKfmIconView::slotRenderingFinished() +{ + kdDebug(1202) << "KonqKfmIconView::slotRenderingFinished()" << endl; + if ( m_bNeedEmitCompleted ) + { + kdDebug(1202) << "KonqKfmIconView completed() after rendering" << endl; + emit completed(); + m_bNeedEmitCompleted = false; + } + if ( m_bNeedAlign ) + { + m_bNeedAlign = false; + kdDebug(1202) << "arrangeItemsInGrid" << endl; + m_pIconView->arrangeItemsInGrid(); + } +} + +void KonqKfmIconView::slotRefreshViewport() +{ + kdDebug(1202) << "KonqKfmIconView::slotRefreshViewport()" << endl; + TQWidget * vp = m_pIconView->viewport(); + bool prevState = vp->isUpdatesEnabled(); + vp->setUpdatesEnabled( true ); + vp->repaint(); + vp->setUpdatesEnabled( prevState ); +} + +bool KonqKfmIconView::doOpenURL( const KURL & url ) +{ + // Store url in the icon view + m_pIconView->setURL( url ); + + m_bLoading = true; + m_bNeedSetCurrentItem = true; + + // Check for new properties in the new dir + // enterDir returns true the first time, and any time something might + // have changed. + m_bDirPropertiesChanged = m_pProps->enterDir( url ); + + m_dirLister->setNameFilter( m_nameFilter ); + + m_dirLister->setMimeFilter( mimeFilter() ); + + // This *must* happen before m_dirLister->openURL because it emits + // clear() and TQIconView::clear() calls setContentsPos(0,0)! + KParts::URLArgs args = m_extension->urlArgs(); + if ( args.reload ) + { + args.xOffset = m_pIconView->contentsX(); + args.yOffset = m_pIconView->contentsY(); + m_extension->setURLArgs( args ); + + m_filesToSelect.clear(); + KFileItemList fil( selectedFileItems() ); + for (KFileItemListIterator fi_it(fil); fi_it.current(); ++fi_it) + m_filesToSelect += (*fi_it)->name(); + } + + m_itemsToSelect = m_filesToSelect; + + m_dirLister->setShowingDotFiles( m_pProps->isShowingDotFiles() ); + + m_bNeedAlign = false; + m_bUpdateContentsPosAfterListing = true; + + m_paOutstandingOverlays.clear(); + m_paOutstandingFreeSpaceOverlays.clear(); + + // Start the directory lister ! + m_dirLister->openURL( url, false, args.reload ); + + // View properties (icon size, background, ..) will be applied into slotClear() + // if m_bDirPropertiesChanged is set. If so, here we update preview actions. + if ( m_bDirPropertiesChanged ) + { + m_paDotFiles->setChecked( m_pProps->isShowingDotFiles() ); + m_paDirectoryOverlays->setChecked( m_pProps->isShowingDirectoryOverlays() ); + m_paFreeSpaceOverlays->setChecked( m_pProps->isShowingFreeSpaceOverlays() ); + m_paEnablePreviews->setChecked( m_pProps->isShowingPreview() ); + for ( m_paPreviewPlugins.first(); m_paPreviewPlugins.current(); m_paPreviewPlugins.next() ) + { + TQStringList types = TQStringList::split( ',', m_paPreviewPlugins.current()->name() ); + bool enabled = false; + for ( TQStringList::ConstIterator it = types.begin(); it != types.end(); ++it ) + if ( m_pProps->isShowingPreview( *it ) ) + { + enabled = true; + break; + } + m_paPreviewPlugins.current()->setChecked( enabled ); + m_paPreviewPlugins.current()->setEnabled( m_pProps->isShowingPreview() ); + } + } + + const TQString prettyURL = url.pathOrURL(); + emit setWindowCaption( prettyURL ); + + return true; +} + +void KonqKfmIconView::slotKFindOpened() +{ + m_dirLister->setAutoUpdate( false ); +} + +void KonqKfmIconView::slotKFindClosed() +{ + m_dirLister->setAutoUpdate( true ); +} + +void KonqKfmIconView::slotOnItem( TQIconViewItem *item ) +{ + emit setStatusBarText( static_cast(item)->item()->getStatusBarInfo() ); + emitMouseOver( static_cast(item)->item()); +} + +void KonqKfmIconView::slotOnViewport() +{ + KFileItemList lst = m_pIconView->selectedFileItems(); + emitCounts( lst, false ); + emitMouseOver( 0 ); +} + +void KonqKfmIconView::setViewMode( const TQString &mode ) +{ + if ( mode == m_mode ) + return; + // note: this should be moved to KonqIconViewWidget. It would make the code + // more readable :) + + m_mode = mode; + if (mode=="MultiColumnView") + { + m_pIconView->setArrangement(TQIconView::TopToBottom); + m_pIconView->setItemTextPos(TQIconView::Right); + } + else + { + m_pIconView->setArrangement(TQIconView::LeftToRight); + m_pIconView->setItemTextPos(TQIconView::Bottom); + } + + if ( m_bPreviewRunningBeforeCloseURL ) + { + m_bPreviewRunningBeforeCloseURL = false; + // continue (param: false) a preview job interrupted by doCloseURL + m_pIconView->startImagePreview( m_pProps->previewSettings(), false ); + } +} + +void KonqKfmIconView::setupSortKeys() +{ + switch ( m_eSortCriterion ) + { + case NameCaseSensitive: + m_pIconView->setCaseInsensitiveSort( false ); + for ( TQIconViewItem *it = m_pIconView->firstItem(); it; it = it->nextItem() ) + it->setKey( it->text() ); + break; + case NameCaseInsensitive: + m_pIconView->setCaseInsensitiveSort( true ); + for ( TQIconViewItem *it = m_pIconView->firstItem(); it; it = it->nextItem() ) + it->setKey( it->text().lower() ); + break; + case Size: + for ( TQIconViewItem *it = m_pIconView->firstItem(); it; it = it->nextItem() ) + it->setKey( makeSizeKey( (KFileIVI *)it ) ); + break; + case Type: + // Sort by Type + Name (#17014) + for ( TQIconViewItem *it = m_pIconView->firstItem(); it; it = it->nextItem() ) + it->setKey( static_cast( it )->item()->mimetype() + "\008" + it->text().lower() ); + break; + case Date: + { + //Sorts by time of modification (#52750) + TQDateTime dayt; + for ( TQIconViewItem *it = m_pIconView->firstItem(); it; it = it->nextItem() ) + { + dayt.setTime_t(static_cast( it )->item()->time(TDEIO::UDS_MODIFICATION_TIME)); + it->setKey(dayt.toString("yyyyMMddhhmmss")); + } + break; + } + } +} + +TQString KonqKfmIconView::makeSizeKey( KFileIVI *item ) +{ + return TDEIO::number( item->item()->size() ).rightJustify( 20, '0' ); +} + +void KonqKfmIconView::disableIcons( const KURL::List & lst ) +{ + m_pIconView->disableIcons( lst ); +} + + +SpringLoadingManager *SpringLoadingManager::s_self = 0L; +static KStaticDeleter s_springManagerDeleter; + +SpringLoadingManager::SpringLoadingManager() + : m_startPart(0L) +{ + connect( &m_endTimer, TQT_SIGNAL( timeout() ), + this, TQT_SLOT( finished() ) ); + +} + +SpringLoadingManager &SpringLoadingManager::self() +{ + if ( !s_self ) + { + s_springManagerDeleter.setObject(s_self, new SpringLoadingManager()); + } + + return *s_self; +} + +bool SpringLoadingManager::exists() +{ + return s_self!=0L; +} + + +void SpringLoadingManager::springLoadTrigger(KonqKfmIconView *view, + KFileItem *file, + TQIconViewItem *item) +{ + if ( !file || !file->isDir() ) + return; + + // We start a new spring loading chain + if ( m_startPart==0L ) + { + m_startURL = view->url(); + m_startPart = view; + } + + // Only the last part of the chain is allowed to trigger a spring load + // event (if a spring loading chain is in progress) + if ( view!=m_startPart ) + return; + + + item->setSelected( false, true ); + view->iconViewWidget()->visualActivate(item); + + KURL url = file->url(); + + KParts::URLArgs args; + file->determineMimeType(); + if ( file->isMimeTypeKnown() ) + args.serviceType = file->mimetype(); + args.trustedSource = true; + + // Open the folder URL, we don't want to modify the browser + // history, hence the use of openURL and setLocationBarURL + view->openURL(url); + const TQString prettyURL = url.pathOrURL(); + emit view->extension()->setLocationBarURL( prettyURL ); +} + +void SpringLoadingManager::dragLeft(KonqKfmIconView */*view*/) +{ + // We leave a view maybe the user tries to cancel the current spring loading + if ( !m_startURL.isEmpty() ) + { + m_endTimer.start(1000, true); + } +} + +void SpringLoadingManager::dragEntered(KonqKfmIconView *view) +{ + // We enter a view involved in the spring loading chain + if ( !m_startURL.isEmpty() && m_startPart==view ) + { + m_endTimer.stop(); + } +} + +void SpringLoadingManager::dragFinished(KonqKfmIconView */*view*/) +{ + if ( !m_startURL.isEmpty() ) + { + finished(); + } +} + + +void SpringLoadingManager::finished() +{ + kdDebug() << "SpringLoadManager::finished()" << endl; + + KURL url = m_startURL; + m_startURL = KURL(); + + KParts::ReadOnlyPart *part = m_startPart; + m_startPart = 0L; + + KonqKfmIconView *view = static_cast(part); + view->openURL(url); + const TQString prettyURL = url.pathOrURL(); + emit view->extension()->setLocationBarURL( prettyURL ); + + deleteLater(); + s_self = 0L; + s_springManagerDeleter.setObject(s_self, static_cast(0L)); +} + + + +#include "konq_iconview.moc" diff --git a/konqueror/konq_actions.cc b/konqueror/konq_actions.cc deleted file mode 100644 index 934c326f7..000000000 --- a/konqueror/konq_actions.cc +++ /dev/null @@ -1,504 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2000 Simon Hausmann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "konq_actions.h" - -#include - -#include -#include -#include -#include - -#include -#include -#include -#include - -#include "konq_view.h" -#include "konq_settingsxt.h" - -template class TQPtrList; - -///////////////// - -//static - used by KonqHistoryAction and KonqBidiHistoryAction -void KonqBidiHistoryAction::fillHistoryPopup( const TQPtrList &history, - TQPopupMenu * popup, - bool onlyBack, - bool onlyForward, - bool checkCurrentItem, - uint startPos ) -{ - assert ( popup ); // kill me if this 0... :/ - - //kdDebug(1202) << "fillHistoryPopup position: " << history.at() << endl; - HistoryEntry * current = history.current(); - TQPtrListIterator it( history ); - if (onlyBack || onlyForward) - { - it += history.at(); // Jump to current item - if ( !onlyForward ) --it; else ++it; // And move off it - } else if ( startPos ) - it += startPos; // Jump to specified start pos - - uint i = 0; - while ( it.current() ) - { - TQString text = it.current()->title; - text = KStringHandler::cEmSqueeze(text, popup->fontMetrics(), 30); //CT: squeeze - text.replace( "&", "&&" ); - if ( checkCurrentItem && it.current() == current ) - { - int id = popup->insertItem( text ); // no pixmap if checked - popup->setItemChecked( id, true ); - } else - popup->insertItem( KonqPixmapProvider::self()->pixmapFor( - it.current()->url.url() ), text ); - if ( ++i > 10 ) - break; - if ( !onlyForward ) --it; else ++it; - } - //kdDebug(1202) << "After fillHistoryPopup position: " << history.at() << endl; -} - -/////////////////////////////// - -KonqBidiHistoryAction::KonqBidiHistoryAction ( const TQString & text, TQObject* parent, const char* name ) - : TDEAction( text, 0, parent, name ) -{ - setShortcutConfigurable(false); - m_firstIndex = 0; - m_goMenu = 0L; -} - -int KonqBidiHistoryAction::plug( TQWidget *widget, int index ) -{ - if (kapp && !kapp->authorizeTDEAction(name())) - return -1; - - // Go menu - if ( widget->inherits(TQPOPUPMENU_OBJECT_NAME_STRING) ) - { - m_goMenu = (TQPopupMenu*)widget; - // Forward signal (to main view) - connect( m_goMenu, TQT_SIGNAL( aboutToShow() ), - this, TQT_SIGNAL( menuAboutToShow() ) ); - connect( m_goMenu, TQT_SIGNAL( activated( int ) ), - this, TQT_SLOT( slotActivated( int ) ) ); - //kdDebug(1202) << "m_goMenu->count()=" << m_goMenu->count() << endl; - // Store how many items the menu already contains. - // This means, the KonqBidiHistoryAction has to be plugged LAST in a menu ! - m_firstIndex = m_goMenu->count(); - return m_goMenu->count(); // hmmm, what should this be ? - } - return TDEAction::plug( widget, index ); -} - -void KonqBidiHistoryAction::fillGoMenu( const TQPtrList & history ) -{ - if (history.isEmpty()) - return; // nothing to do - - //kdDebug(1202) << "fillGoMenu position: " << history.at() << endl; - if ( m_firstIndex == 0 ) // should never happen since done in plug - m_firstIndex = m_goMenu->count(); - else - { // Clean up old history (from the end, to avoid shifts) - for ( uint i = m_goMenu->count()-1 ; i >= m_firstIndex; i-- ) - m_goMenu->removeItemAt( i ); - } - // TODO perhaps smarter algorithm (rename existing items, create new ones only if not enough) ? - - // Ok, we want to show 10 items in all, among which the current url... - - if ( history.count() <= 9 ) - { - // First case: limited history in both directions -> show it all - m_startPos = history.count() - 1; // Start right from the end - } else - // Second case: big history, in one or both directions - { - // Assume both directions first (in this case we place the current URL in the middle) - m_startPos = history.at() + 4; - - // Forward not big enough ? - if ( history.at() > (int)history.count() - 4 ) - m_startPos = history.count() - 1; - } - Q_ASSERT( m_startPos >= 0 && (uint)m_startPos < history.count() ); - if ( m_startPos < 0 || (uint)m_startPos >= history.count() ) - { - kdWarning() << "m_startPos=" << m_startPos << " history.count()=" << history.count() << endl; - return; - } - m_currentPos = history.at(); // for slotActivated - KonqBidiHistoryAction::fillHistoryPopup( history, m_goMenu, false, false, true, m_startPos ); -} - -void KonqBidiHistoryAction::slotActivated( int id ) -{ - // 1 for first item in the list, etc. - int index = m_goMenu->indexOf(id) - m_firstIndex + 1; - if ( index > 0 ) - { - kdDebug(1202) << "Item clicked has index " << index << endl; - // -1 for one step back, 0 for don't move, +1 for one step forward, etc. - int steps = ( m_startPos+1 ) - index - m_currentPos; // make a drawing to understand this :-) - kdDebug(1202) << "Emit activated with steps = " << steps << endl; - emit activated( steps ); - } -} - -/////////////////////////////// - -KonqLogoAction::KonqLogoAction( const TQString& text, int accel, TQObject* parent, const char* name ) - : TDEAction( text, accel, parent, name ) -{ -} - -KonqLogoAction::KonqLogoAction( const TQString& text, int accel, - TQObject* receiver, const char* slot, TQObject* parent, const char* name ) - : TDEAction( text, accel, receiver, slot, parent, name ) -{ -} - -KonqLogoAction::KonqLogoAction( const TQString& text, const TQIconSet& pix, int accel, TQObject* parent, const char* name ) - : TDEAction( text, pix, accel, parent, name ) -{ -} - -KonqLogoAction::KonqLogoAction( const TQString& text, const TQIconSet& pix,int accel, TQObject* receiver, const char* slot, TQObject* parent, const char* name ) - : TDEAction( text, pix, accel, receiver, slot, parent, name ) -{ -} - -KonqLogoAction::KonqLogoAction( const TQStringList& icons, TQObject* receiver, - const char* slot, TQObject* parent, - const char* name ) - : TDEAction( 0L, 0, receiver, slot, parent, name ) // text missing ! -{ - iconList = icons; -} - -void KonqLogoAction::start() -{ - int len = containerCount(); - for ( int i = 0; i < len; i++ ) - { - TQWidget *w = container( i ); - - if ( w->inherits( "TDEToolBar" ) ) - { - KAnimWidget *anim = ((TDEToolBar *)w)->animatedWidget( menuId( i ) ); - anim->start(); - } - } -} - -void KonqLogoAction::stop() -{ - int len = containerCount(); - for ( int i = 0; i < len; i++ ) - { - TQWidget *w = container( i ); - - if ( w->inherits( "TDEToolBar" ) ) - { - KAnimWidget *anim = ((TDEToolBar *)w)->animatedWidget( menuId( i ) ); - anim->stop(); - } - } -} - -void KonqLogoAction::updateIcon(int id) -{ - TQWidget *w = container( id ); - - if ( w->inherits( "TDEToolBar" ) ) - { - KAnimWidget *anim = ((TDEToolBar *)w)->animatedWidget( menuId( id ) ); - anim->setIcons(icon()); - } -} - - - -int KonqLogoAction::plug( TQWidget *widget, int index ) -{ - if (kapp && !kapp->authorizeTDEAction(name())) - return -1; - -/* - if ( widget->inherits( "TDEMainWindow" ) ) - { - ((TDEMainWindow*)widget)->setIndicatorWidget(m_logoLabel); - - addContainer( widget, -1 ); - - return containerCount() - 1; - } -*/ - if ( widget->inherits( "TDEToolBar" ) ) - { - TDEToolBar *bar = (TDEToolBar *)widget; - - int id_ = getToolButtonID(); - - bar->insertAnimatedWidget( id_, this, TQT_SIGNAL(activated()), TQString("trinity"), index ); - bar->alignItemRight( id_ ); - - addContainer( bar, id_ ); - - connect( bar, TQT_SIGNAL( destroyed() ), this, TQT_SLOT( slotDestroyed() ) ); - - return containerCount() - 1; - } - - int containerId = TDEAction::plug( widget, index ); - - return containerId; -} - -/////////// - -KonqViewModeAction::KonqViewModeAction( const TQString &text, const TQString &icon, - TQObject *parent, const char *name ) - : TDERadioAction( text, icon, 0, parent, name ) -{ - m_menu = new TQPopupMenu; - - connect( m_menu, TQT_SIGNAL( aboutToShow() ), - this, TQT_SLOT( slotPopupAboutToShow() ) ); - connect( m_menu, TQT_SIGNAL( activated( int ) ), - this, TQT_SLOT( slotPopupActivated() ) ); - connect( m_menu, TQT_SIGNAL( aboutToHide() ), - this, TQT_SLOT( slotPopupAboutToHide() ) ); -} - -KonqViewModeAction::~KonqViewModeAction() -{ - delete m_menu; -} - -int KonqViewModeAction::plug( TQWidget *widget, int index ) -{ - int res = TDERadioAction::plug( widget, index ); - - if ( widget->inherits( "TDEToolBar" ) && (res != -1) ) - { - TDEToolBar *toolBar = static_cast( widget ); - - TDEToolBarButton *button = toolBar->getButton( itemId( res ) ); - - if ( m_menu->count() > 1 ) - button->setDelayedPopup( m_menu, false ); - } - - return res; -} - -void KonqViewModeAction::slotPopupAboutToShow() -{ - m_popupActivated = false; -} - -void KonqViewModeAction::slotPopupActivated() -{ - m_popupActivated = true; -} - -void KonqViewModeAction::slotPopupAboutToHide() -{ - if ( !m_popupActivated ) - { - int i = 0; - for (; i < containerCount(); ++i ) - { - TQWidget *widget = container( i ); - if ( !widget->inherits( "TDEToolBar" ) ) - continue; - - TDEToolBar *tb = static_cast( widget ); - - TDEToolBarButton *button = tb->getButton( itemId( i ) ); - - button->setDown( isChecked() ); - } - } -} - - -MostOftenList * KonqMostOftenURLSAction::s_mostEntries = 0L; -uint KonqMostOftenURLSAction::s_maxEntries = 0; - -KonqMostOftenURLSAction::KonqMostOftenURLSAction( const TQString& text, - TQObject *parent, - const char *name ) - : TDEActionMenu( text, "goto", parent, name ) -{ - setDelayed( false ); - - connect( popupMenu(), TQT_SIGNAL( aboutToShow() ), TQT_SLOT( slotFillMenu() )); - //connect( popupMenu(), TQT_SIGNAL( aboutToHide() ), TQT_SLOT( slotClearMenu() )); - connect( popupMenu(), TQT_SIGNAL( activated( int ) ), - TQT_SLOT( slotActivated(int) )); - // Need to do all this upfront for a correct initial state - init(); -} - -KonqMostOftenURLSAction::~KonqMostOftenURLSAction() -{ -} - -void KonqMostOftenURLSAction::init() -{ - s_maxEntries = KonqSettings::numberofmostvisitedURLs(); - - KonqHistoryManager *mgr = KonqHistoryManager::kself(); - setEnabled( !mgr->entries().isEmpty() && s_maxEntries > 0 ); -} - -void KonqMostOftenURLSAction::parseHistory() // only ever called once -{ - KonqHistoryManager *mgr = KonqHistoryManager::kself(); - KonqHistoryIterator it( mgr->entries() ); - - connect( mgr, TQT_SIGNAL( entryAdded( const KonqHistoryEntry * )), - TQT_SLOT( slotEntryAdded( const KonqHistoryEntry * ))); - connect( mgr, TQT_SIGNAL( entryRemoved( const KonqHistoryEntry * )), - TQT_SLOT( slotEntryRemoved( const KonqHistoryEntry * ))); - connect( mgr, TQT_SIGNAL( cleared() ), TQT_SLOT( slotHistoryCleared() )); - - s_mostEntries = new MostOftenList; // exit() will clean this up for now - for ( uint i = 0; it.current() && i < s_maxEntries; i++ ) { - s_mostEntries->append( it.current() ); - ++it; - } - s_mostEntries->sort(); - - while ( it.current() ) { - KonqHistoryEntry *leastOften = s_mostEntries->first(); - KonqHistoryEntry *entry = it.current(); - if ( leastOften->numberOfTimesVisited < entry->numberOfTimesVisited ) { - s_mostEntries->removeFirst(); - s_mostEntries->inSort( entry ); - } - - ++it; - } -} - -void KonqMostOftenURLSAction::slotEntryAdded( const KonqHistoryEntry *entry ) -{ - // if it's already present, remove it, and inSort it - s_mostEntries->removeRef( entry ); - - if ( s_mostEntries->count() >= s_maxEntries ) { - KonqHistoryEntry *leastOften = s_mostEntries->first(); - if ( leastOften->numberOfTimesVisited < entry->numberOfTimesVisited ) { - s_mostEntries->removeFirst(); - s_mostEntries->inSort( entry ); - } - } - - else - s_mostEntries->inSort( entry ); - setEnabled( !s_mostEntries->isEmpty() ); -} - -void KonqMostOftenURLSAction::slotEntryRemoved( const KonqHistoryEntry *entry ) -{ - s_mostEntries->removeRef( entry ); - setEnabled( !s_mostEntries->isEmpty() ); -} - -void KonqMostOftenURLSAction::slotHistoryCleared() -{ - s_mostEntries->clear(); - setEnabled( false ); -} - -void KonqMostOftenURLSAction::slotFillMenu() -{ - if ( !s_mostEntries ) // first time - parseHistory(); - - popupMenu()->clear(); - m_popupList.clear(); - - int id = s_mostEntries->count() -1; - KonqHistoryEntry *entry = s_mostEntries->at( id ); - while ( entry ) { - // we take either title, typedURL or URL (in this order) - TQString text = entry->title.isEmpty() ? (entry->typedURL.isEmpty() ? - entry->url.prettyURL() : - entry->typedURL) : - entry->title; - - popupMenu()->insertItem( - KonqPixmapProvider::self()->pixmapFor( entry->url.url() ), - text, id ); - // Keep a copy of the URLs being shown in the menu - // This prevents crashes when another process tells us to remove an entry. - m_popupList.prepend( entry->url ); - - entry = (id > 0) ? s_mostEntries->at( --id ) : 0L; - } - setEnabled( !s_mostEntries->isEmpty() ); - Q_ASSERT( s_mostEntries->count() == m_popupList.count() ); -} - -#if 0 -void KonqMostOftenURLSAction::slotClearMenu() -{ - // Warning this is called _before_ slotActivated, when activating a menu item. - // So e.g. don't clear m_popupList here. -} -#endif - -void KonqMostOftenURLSAction::slotActivated( int id ) -{ - Q_ASSERT( !m_popupList.isEmpty() ); // can not happen - Q_ASSERT( id < (int)m_popupList.count() ); - - KURL url = m_popupList[ id ]; - if ( url.isValid() ) - emit activated( url ); - else - kdWarning() << "Invalid url: " << url.prettyURL() << endl; - m_popupList.clear(); -} - -// sort by numberOfTimesVisited (least often goes first) -int MostOftenList::compareItems( TQPtrCollection::Item item1, - TQPtrCollection::Item item2) -{ - KonqHistoryEntry *entry1 = static_cast( item1 ); - KonqHistoryEntry *entry2 = static_cast( item2 ); - - if ( entry1->numberOfTimesVisited > entry2->numberOfTimesVisited ) - return 1; - else if ( entry1->numberOfTimesVisited < entry2->numberOfTimesVisited ) - return -1; - else - return 0; -} - -#include "konq_actions.moc" diff --git a/konqueror/konq_actions.cpp b/konqueror/konq_actions.cpp new file mode 100644 index 000000000..934c326f7 --- /dev/null +++ b/konqueror/konq_actions.cpp @@ -0,0 +1,504 @@ +/* This file is part of the KDE project + Copyright (C) 2000 Simon Hausmann + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "konq_actions.h" + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "konq_view.h" +#include "konq_settingsxt.h" + +template class TQPtrList; + +///////////////// + +//static - used by KonqHistoryAction and KonqBidiHistoryAction +void KonqBidiHistoryAction::fillHistoryPopup( const TQPtrList &history, + TQPopupMenu * popup, + bool onlyBack, + bool onlyForward, + bool checkCurrentItem, + uint startPos ) +{ + assert ( popup ); // kill me if this 0... :/ + + //kdDebug(1202) << "fillHistoryPopup position: " << history.at() << endl; + HistoryEntry * current = history.current(); + TQPtrListIterator it( history ); + if (onlyBack || onlyForward) + { + it += history.at(); // Jump to current item + if ( !onlyForward ) --it; else ++it; // And move off it + } else if ( startPos ) + it += startPos; // Jump to specified start pos + + uint i = 0; + while ( it.current() ) + { + TQString text = it.current()->title; + text = KStringHandler::cEmSqueeze(text, popup->fontMetrics(), 30); //CT: squeeze + text.replace( "&", "&&" ); + if ( checkCurrentItem && it.current() == current ) + { + int id = popup->insertItem( text ); // no pixmap if checked + popup->setItemChecked( id, true ); + } else + popup->insertItem( KonqPixmapProvider::self()->pixmapFor( + it.current()->url.url() ), text ); + if ( ++i > 10 ) + break; + if ( !onlyForward ) --it; else ++it; + } + //kdDebug(1202) << "After fillHistoryPopup position: " << history.at() << endl; +} + +/////////////////////////////// + +KonqBidiHistoryAction::KonqBidiHistoryAction ( const TQString & text, TQObject* parent, const char* name ) + : TDEAction( text, 0, parent, name ) +{ + setShortcutConfigurable(false); + m_firstIndex = 0; + m_goMenu = 0L; +} + +int KonqBidiHistoryAction::plug( TQWidget *widget, int index ) +{ + if (kapp && !kapp->authorizeTDEAction(name())) + return -1; + + // Go menu + if ( widget->inherits(TQPOPUPMENU_OBJECT_NAME_STRING) ) + { + m_goMenu = (TQPopupMenu*)widget; + // Forward signal (to main view) + connect( m_goMenu, TQT_SIGNAL( aboutToShow() ), + this, TQT_SIGNAL( menuAboutToShow() ) ); + connect( m_goMenu, TQT_SIGNAL( activated( int ) ), + this, TQT_SLOT( slotActivated( int ) ) ); + //kdDebug(1202) << "m_goMenu->count()=" << m_goMenu->count() << endl; + // Store how many items the menu already contains. + // This means, the KonqBidiHistoryAction has to be plugged LAST in a menu ! + m_firstIndex = m_goMenu->count(); + return m_goMenu->count(); // hmmm, what should this be ? + } + return TDEAction::plug( widget, index ); +} + +void KonqBidiHistoryAction::fillGoMenu( const TQPtrList & history ) +{ + if (history.isEmpty()) + return; // nothing to do + + //kdDebug(1202) << "fillGoMenu position: " << history.at() << endl; + if ( m_firstIndex == 0 ) // should never happen since done in plug + m_firstIndex = m_goMenu->count(); + else + { // Clean up old history (from the end, to avoid shifts) + for ( uint i = m_goMenu->count()-1 ; i >= m_firstIndex; i-- ) + m_goMenu->removeItemAt( i ); + } + // TODO perhaps smarter algorithm (rename existing items, create new ones only if not enough) ? + + // Ok, we want to show 10 items in all, among which the current url... + + if ( history.count() <= 9 ) + { + // First case: limited history in both directions -> show it all + m_startPos = history.count() - 1; // Start right from the end + } else + // Second case: big history, in one or both directions + { + // Assume both directions first (in this case we place the current URL in the middle) + m_startPos = history.at() + 4; + + // Forward not big enough ? + if ( history.at() > (int)history.count() - 4 ) + m_startPos = history.count() - 1; + } + Q_ASSERT( m_startPos >= 0 && (uint)m_startPos < history.count() ); + if ( m_startPos < 0 || (uint)m_startPos >= history.count() ) + { + kdWarning() << "m_startPos=" << m_startPos << " history.count()=" << history.count() << endl; + return; + } + m_currentPos = history.at(); // for slotActivated + KonqBidiHistoryAction::fillHistoryPopup( history, m_goMenu, false, false, true, m_startPos ); +} + +void KonqBidiHistoryAction::slotActivated( int id ) +{ + // 1 for first item in the list, etc. + int index = m_goMenu->indexOf(id) - m_firstIndex + 1; + if ( index > 0 ) + { + kdDebug(1202) << "Item clicked has index " << index << endl; + // -1 for one step back, 0 for don't move, +1 for one step forward, etc. + int steps = ( m_startPos+1 ) - index - m_currentPos; // make a drawing to understand this :-) + kdDebug(1202) << "Emit activated with steps = " << steps << endl; + emit activated( steps ); + } +} + +/////////////////////////////// + +KonqLogoAction::KonqLogoAction( const TQString& text, int accel, TQObject* parent, const char* name ) + : TDEAction( text, accel, parent, name ) +{ +} + +KonqLogoAction::KonqLogoAction( const TQString& text, int accel, + TQObject* receiver, const char* slot, TQObject* parent, const char* name ) + : TDEAction( text, accel, receiver, slot, parent, name ) +{ +} + +KonqLogoAction::KonqLogoAction( const TQString& text, const TQIconSet& pix, int accel, TQObject* parent, const char* name ) + : TDEAction( text, pix, accel, parent, name ) +{ +} + +KonqLogoAction::KonqLogoAction( const TQString& text, const TQIconSet& pix,int accel, TQObject* receiver, const char* slot, TQObject* parent, const char* name ) + : TDEAction( text, pix, accel, receiver, slot, parent, name ) +{ +} + +KonqLogoAction::KonqLogoAction( const TQStringList& icons, TQObject* receiver, + const char* slot, TQObject* parent, + const char* name ) + : TDEAction( 0L, 0, receiver, slot, parent, name ) // text missing ! +{ + iconList = icons; +} + +void KonqLogoAction::start() +{ + int len = containerCount(); + for ( int i = 0; i < len; i++ ) + { + TQWidget *w = container( i ); + + if ( w->inherits( "TDEToolBar" ) ) + { + KAnimWidget *anim = ((TDEToolBar *)w)->animatedWidget( menuId( i ) ); + anim->start(); + } + } +} + +void KonqLogoAction::stop() +{ + int len = containerCount(); + for ( int i = 0; i < len; i++ ) + { + TQWidget *w = container( i ); + + if ( w->inherits( "TDEToolBar" ) ) + { + KAnimWidget *anim = ((TDEToolBar *)w)->animatedWidget( menuId( i ) ); + anim->stop(); + } + } +} + +void KonqLogoAction::updateIcon(int id) +{ + TQWidget *w = container( id ); + + if ( w->inherits( "TDEToolBar" ) ) + { + KAnimWidget *anim = ((TDEToolBar *)w)->animatedWidget( menuId( id ) ); + anim->setIcons(icon()); + } +} + + + +int KonqLogoAction::plug( TQWidget *widget, int index ) +{ + if (kapp && !kapp->authorizeTDEAction(name())) + return -1; + +/* + if ( widget->inherits( "TDEMainWindow" ) ) + { + ((TDEMainWindow*)widget)->setIndicatorWidget(m_logoLabel); + + addContainer( widget, -1 ); + + return containerCount() - 1; + } +*/ + if ( widget->inherits( "TDEToolBar" ) ) + { + TDEToolBar *bar = (TDEToolBar *)widget; + + int id_ = getToolButtonID(); + + bar->insertAnimatedWidget( id_, this, TQT_SIGNAL(activated()), TQString("trinity"), index ); + bar->alignItemRight( id_ ); + + addContainer( bar, id_ ); + + connect( bar, TQT_SIGNAL( destroyed() ), this, TQT_SLOT( slotDestroyed() ) ); + + return containerCount() - 1; + } + + int containerId = TDEAction::plug( widget, index ); + + return containerId; +} + +/////////// + +KonqViewModeAction::KonqViewModeAction( const TQString &text, const TQString &icon, + TQObject *parent, const char *name ) + : TDERadioAction( text, icon, 0, parent, name ) +{ + m_menu = new TQPopupMenu; + + connect( m_menu, TQT_SIGNAL( aboutToShow() ), + this, TQT_SLOT( slotPopupAboutToShow() ) ); + connect( m_menu, TQT_SIGNAL( activated( int ) ), + this, TQT_SLOT( slotPopupActivated() ) ); + connect( m_menu, TQT_SIGNAL( aboutToHide() ), + this, TQT_SLOT( slotPopupAboutToHide() ) ); +} + +KonqViewModeAction::~KonqViewModeAction() +{ + delete m_menu; +} + +int KonqViewModeAction::plug( TQWidget *widget, int index ) +{ + int res = TDERadioAction::plug( widget, index ); + + if ( widget->inherits( "TDEToolBar" ) && (res != -1) ) + { + TDEToolBar *toolBar = static_cast( widget ); + + TDEToolBarButton *button = toolBar->getButton( itemId( res ) ); + + if ( m_menu->count() > 1 ) + button->setDelayedPopup( m_menu, false ); + } + + return res; +} + +void KonqViewModeAction::slotPopupAboutToShow() +{ + m_popupActivated = false; +} + +void KonqViewModeAction::slotPopupActivated() +{ + m_popupActivated = true; +} + +void KonqViewModeAction::slotPopupAboutToHide() +{ + if ( !m_popupActivated ) + { + int i = 0; + for (; i < containerCount(); ++i ) + { + TQWidget *widget = container( i ); + if ( !widget->inherits( "TDEToolBar" ) ) + continue; + + TDEToolBar *tb = static_cast( widget ); + + TDEToolBarButton *button = tb->getButton( itemId( i ) ); + + button->setDown( isChecked() ); + } + } +} + + +MostOftenList * KonqMostOftenURLSAction::s_mostEntries = 0L; +uint KonqMostOftenURLSAction::s_maxEntries = 0; + +KonqMostOftenURLSAction::KonqMostOftenURLSAction( const TQString& text, + TQObject *parent, + const char *name ) + : TDEActionMenu( text, "goto", parent, name ) +{ + setDelayed( false ); + + connect( popupMenu(), TQT_SIGNAL( aboutToShow() ), TQT_SLOT( slotFillMenu() )); + //connect( popupMenu(), TQT_SIGNAL( aboutToHide() ), TQT_SLOT( slotClearMenu() )); + connect( popupMenu(), TQT_SIGNAL( activated( int ) ), + TQT_SLOT( slotActivated(int) )); + // Need to do all this upfront for a correct initial state + init(); +} + +KonqMostOftenURLSAction::~KonqMostOftenURLSAction() +{ +} + +void KonqMostOftenURLSAction::init() +{ + s_maxEntries = KonqSettings::numberofmostvisitedURLs(); + + KonqHistoryManager *mgr = KonqHistoryManager::kself(); + setEnabled( !mgr->entries().isEmpty() && s_maxEntries > 0 ); +} + +void KonqMostOftenURLSAction::parseHistory() // only ever called once +{ + KonqHistoryManager *mgr = KonqHistoryManager::kself(); + KonqHistoryIterator it( mgr->entries() ); + + connect( mgr, TQT_SIGNAL( entryAdded( const KonqHistoryEntry * )), + TQT_SLOT( slotEntryAdded( const KonqHistoryEntry * ))); + connect( mgr, TQT_SIGNAL( entryRemoved( const KonqHistoryEntry * )), + TQT_SLOT( slotEntryRemoved( const KonqHistoryEntry * ))); + connect( mgr, TQT_SIGNAL( cleared() ), TQT_SLOT( slotHistoryCleared() )); + + s_mostEntries = new MostOftenList; // exit() will clean this up for now + for ( uint i = 0; it.current() && i < s_maxEntries; i++ ) { + s_mostEntries->append( it.current() ); + ++it; + } + s_mostEntries->sort(); + + while ( it.current() ) { + KonqHistoryEntry *leastOften = s_mostEntries->first(); + KonqHistoryEntry *entry = it.current(); + if ( leastOften->numberOfTimesVisited < entry->numberOfTimesVisited ) { + s_mostEntries->removeFirst(); + s_mostEntries->inSort( entry ); + } + + ++it; + } +} + +void KonqMostOftenURLSAction::slotEntryAdded( const KonqHistoryEntry *entry ) +{ + // if it's already present, remove it, and inSort it + s_mostEntries->removeRef( entry ); + + if ( s_mostEntries->count() >= s_maxEntries ) { + KonqHistoryEntry *leastOften = s_mostEntries->first(); + if ( leastOften->numberOfTimesVisited < entry->numberOfTimesVisited ) { + s_mostEntries->removeFirst(); + s_mostEntries->inSort( entry ); + } + } + + else + s_mostEntries->inSort( entry ); + setEnabled( !s_mostEntries->isEmpty() ); +} + +void KonqMostOftenURLSAction::slotEntryRemoved( const KonqHistoryEntry *entry ) +{ + s_mostEntries->removeRef( entry ); + setEnabled( !s_mostEntries->isEmpty() ); +} + +void KonqMostOftenURLSAction::slotHistoryCleared() +{ + s_mostEntries->clear(); + setEnabled( false ); +} + +void KonqMostOftenURLSAction::slotFillMenu() +{ + if ( !s_mostEntries ) // first time + parseHistory(); + + popupMenu()->clear(); + m_popupList.clear(); + + int id = s_mostEntries->count() -1; + KonqHistoryEntry *entry = s_mostEntries->at( id ); + while ( entry ) { + // we take either title, typedURL or URL (in this order) + TQString text = entry->title.isEmpty() ? (entry->typedURL.isEmpty() ? + entry->url.prettyURL() : + entry->typedURL) : + entry->title; + + popupMenu()->insertItem( + KonqPixmapProvider::self()->pixmapFor( entry->url.url() ), + text, id ); + // Keep a copy of the URLs being shown in the menu + // This prevents crashes when another process tells us to remove an entry. + m_popupList.prepend( entry->url ); + + entry = (id > 0) ? s_mostEntries->at( --id ) : 0L; + } + setEnabled( !s_mostEntries->isEmpty() ); + Q_ASSERT( s_mostEntries->count() == m_popupList.count() ); +} + +#if 0 +void KonqMostOftenURLSAction::slotClearMenu() +{ + // Warning this is called _before_ slotActivated, when activating a menu item. + // So e.g. don't clear m_popupList here. +} +#endif + +void KonqMostOftenURLSAction::slotActivated( int id ) +{ + Q_ASSERT( !m_popupList.isEmpty() ); // can not happen + Q_ASSERT( id < (int)m_popupList.count() ); + + KURL url = m_popupList[ id ]; + if ( url.isValid() ) + emit activated( url ); + else + kdWarning() << "Invalid url: " << url.prettyURL() << endl; + m_popupList.clear(); +} + +// sort by numberOfTimesVisited (least often goes first) +int MostOftenList::compareItems( TQPtrCollection::Item item1, + TQPtrCollection::Item item2) +{ + KonqHistoryEntry *entry1 = static_cast( item1 ); + KonqHistoryEntry *entry2 = static_cast( item2 ); + + if ( entry1->numberOfTimesVisited > entry2->numberOfTimesVisited ) + return 1; + else if ( entry1->numberOfTimesVisited < entry2->numberOfTimesVisited ) + return -1; + else + return 0; +} + +#include "konq_actions.moc" diff --git a/konqueror/konq_browseriface.cc b/konqueror/konq_browseriface.cc deleted file mode 100644 index ebec2ef04..000000000 --- a/konqueror/konq_browseriface.cc +++ /dev/null @@ -1,22 +0,0 @@ - -#include "konq_browseriface.h" -#include "konq_view.h" - -KonqBrowserInterface::KonqBrowserInterface( KonqView *view, const char *name ) - : KParts::BrowserInterface( view, name ) -{ - m_view = view; -} - -uint KonqBrowserInterface::historyLength() const -{ - return m_view->historyLength(); -} - -void KonqBrowserInterface::goHistory( int steps ) -{ - m_view->goHistory( steps ); -} - -#include "konq_browseriface.moc" - diff --git a/konqueror/konq_browseriface.cpp b/konqueror/konq_browseriface.cpp new file mode 100644 index 000000000..ebec2ef04 --- /dev/null +++ b/konqueror/konq_browseriface.cpp @@ -0,0 +1,22 @@ + +#include "konq_browseriface.h" +#include "konq_view.h" + +KonqBrowserInterface::KonqBrowserInterface( KonqView *view, const char *name ) + : KParts::BrowserInterface( view, name ) +{ + m_view = view; +} + +uint KonqBrowserInterface::historyLength() const +{ + return m_view->historyLength(); +} + +void KonqBrowserInterface::goHistory( int steps ) +{ + m_view->goHistory( steps ); +} + +#include "konq_browseriface.moc" + diff --git a/konqueror/konq_combo.cc b/konqueror/konq_combo.cc deleted file mode 100644 index 17075a529..000000000 --- a/konqueror/konq_combo.cc +++ /dev/null @@ -1,905 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2001 Carsten Pfeiffer - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "konq_combo.h" - -TDEConfig * KonqCombo::s_config = 0L; -const int KonqCombo::temporary = 0; - -static TQString titleOfURL( const TQString& urlStr ) -{ - KURL url = KURL::fromPathOrURL( urlStr ); - KonqHistoryList& historylist = const_cast( KonqHistoryManager::kself()->entries() ); - KonqHistoryEntry *historyentry = historylist.findEntry( url ); - if ( !historyentry && !url.url().endsWith( "/" ) ) { - url.setPath( url.path()+'/' ); - historyentry = historylist.findEntry( url ); - } - return ( historyentry ? historyentry->title : TQString() ); -} - -class TQ_EXPORT KonqComboListBoxPixmap : public TQListBoxItem -{ -public: - KonqComboListBoxPixmap( const TQString& text ); - KonqComboListBoxPixmap( const TQPixmap &, const TQString& text, const TQString& title ); - - const TQPixmap *pixmap() const { return ± } - - int height( const TQListBox * ) const; - int width( const TQListBox * ) const; - - int rtti() const; - static int RTTI; - - bool reuse( const TQString& newText ); - -protected: - void paint( TQPainter * ); - -private: - bool lookup_pending; - TQPixmap pm; - TQString title; -}; - -class KonqComboLineEdit : public KLineEdit -{ -public: - KonqComboLineEdit( TQWidget *parent=0, const char *name=0 ); - void setCompletedItems( const TQStringList& items ); -}; - -class KonqComboCompletionBox : public TDECompletionBox -{ -public: - KonqComboCompletionBox( TQWidget *parent, const char *name = 0 ); - void setItems( const TQStringList& items ); - void insertStringList( const TQStringList & list, int index = -1 ); -}; - -KonqCombo::KonqCombo( TQWidget *parent, const char *name ) - : KHistoryCombo( parent, name ), - m_returnPressed( false ), - m_permanent( false ), - m_modifier( Qt::NoButton ), - m_pageSecurity( KonqMainWindow::NotCrypted ) -{ - setInsertionPolicy( NoInsertion ); - setSizePolicy( TQSizePolicy( TQSizePolicy::Expanding, TQSizePolicy::Fixed )); - - Q_ASSERT( s_config ); - - TDEConfigGroupSaver cs( s_config, "Location Bar" ); - setMaxCount( s_config->readNumEntry("Maximum of URLs in combo", 20 )); - - // We should also connect the completionBox' highlighted signal to - // our setEditText() slot, because we're handling the signals ourselves. - // But we're lazy and let TDECompletionBox do this and simply switch off - // handling of signals later. - setHandleSignals( true ); - - KonqComboLineEdit *edit = new KonqComboLineEdit( this, "combo lineedit" ); - edit->setHandleSignals( true ); - edit->setCompletionBox( new KonqComboCompletionBox( edit, "completion box" ) ); - setLineEdit( edit ); - - completionBox()->setTabHandling( true ); - - // Make the lineedit consume the Key_Enter event... - setTrapReturnKey( true ); - - connect( KonqHistoryManager::kself(), TQT_SIGNAL(cleared()), TQT_SLOT(slotCleared()) ); - connect( this, TQT_SIGNAL(cleared() ), TQT_SLOT(slotCleared()) ); - connect( this, TQT_SIGNAL(highlighted( int )), TQT_SLOT(slotSetIcon( int )) ); - connect( this, TQT_SIGNAL(activated( const TQString& )), - TQT_SLOT(slotActivated( const TQString& )) ); - - setHistoryEditorEnabled( true ); - connect( this, TQT_SIGNAL(removed( const TQString&) ), TQT_SLOT(slotRemoved( const TQString& )) ); - - if ( !kapp->dcopClient()->isAttached() ) - kapp->dcopClient()->attach(); -} - -KonqCombo::~KonqCombo() -{ -} - -void KonqCombo::init( TDECompletion *completion ) -{ - setCompletionObject( completion, false ); //KonqMainWindow handles signals - setAutoDeleteCompletionObject( false ); - setCompletionMode( completion->completionMode() ); - - loadItems(); -} - -void KonqCombo::setURL( const TQString& url ) -{ - //kdDebug(1202) << "KonqCombo::setURL: " << url << ", returnPressed ? " << m_returnPressed << endl; - setTemporary( url ); - - if ( m_returnPressed ) { // Really insert... - m_returnPressed = false; - TQByteArray data; - TQDataStream s( data, IO_WriteOnly ); - s << url << kapp->dcopClient()->defaultObject(); - kapp->dcopClient()->send( "konqueror*", "KonquerorIface", - "addToCombo(TQString,TQCString)", data); - } - // important security consideration: always display the beginning - // of the url rather than its end to prevent spoofing attempts. - lineEdit()->setCursorPosition( 0 ); -} - -void KonqCombo::setTemporary( const TQString& text ) -{ - setTemporary( text, KonqPixmapProvider::self()->pixmapFor(text) ); -} - -void KonqCombo::setTemporary( const TQString& url, const TQPixmap& pix ) -{ - //kdDebug(1202) << "KonqCombo::setTemporary: " << url << ", temporary = " << temporary << endl; - - // Insert a temporary item when we don't have one yet - if ( count() == 0 ) - insertItem( pix, url, temporary, titleOfURL( url ) ); - else - { - if (url != temporaryItem()) - applyPermanent(); - - updateItem( pix, url, temporary, titleOfURL( url ) ); - } - - setCurrentItem( temporary ); -} - -void KonqCombo::removeDuplicates( int index ) -{ - //kdDebug(1202) << "KonqCombo::removeDuplicates: Starting index = " << index << endl; - - TQString url (temporaryItem()); - if (url.endsWith("/")) - url.truncate(url.length()-1); - - // Remove all dupes, if available... - for ( int i = index; i < count(); i++ ) - { - TQString item (text(i)); - if (item.endsWith("/")) - item.truncate(item.length()-1); - - if ( item == url ) - removeItem( i ); - } - lineEdit()->setCursorPosition( 0 ); -} - -// called via DCOP in all instances -void KonqCombo::insertPermanent( const TQString& url ) -{ - //kdDebug(1202) << "KonqCombo::insertPermanent: URL = " << url << endl; - saveState(); - setTemporary( url ); - m_permanent = true; - restoreState(); -} - -// called right before a new (different!) temporary item will be set. So we -// insert an item that was marked permanent properly at position 1. -void KonqCombo::applyPermanent() -{ - if ( m_permanent && !temporaryItem().isEmpty() ) { - - // Remove as many items as needed to honour maxCount() - int index = count(); - while ( count() >= maxCount() ) - removeItem( --index ); - - TQString url (temporaryItem()); - insertItem( KonqPixmapProvider::self()->pixmapFor( url ), url, 1, titleOfURL( url ) ); - //kdDebug(1202) << "KonqCombo::applyPermanent: " << url << endl; - - // Remove all duplicates starting from index = 2 - removeDuplicates( 2 ); - m_permanent = false; - } -} - -void KonqCombo::insertItem( const TQString &text, int index, const TQString& title ) -{ - KonqComboListBoxPixmap* item = new KonqComboListBoxPixmap( 0, text, title ); - listBox()->insertItem( item, index ); -} - -void KonqCombo::insertItem( const TQPixmap &pixmap, const TQString& text, int index, const TQString& title ) -{ - KonqComboListBoxPixmap* item = new KonqComboListBoxPixmap( pixmap, text, title ); - listBox()->insertItem( item, index ); -} - -void KonqCombo::updateItem( const TQPixmap& pix, const TQString& t, int index, const TQString& title ) -{ - // No need to flicker - if (text( index ) == t && - (pixmap(index) && pixmap(index)->serialNumber() == pix.serialNumber())) - return; - - // kdDebug(1202) << "KonqCombo::updateItem: item='" << t << "', index='" - // << index << "'" << endl; - - // TQComboBox::changeItem() doesn't honour the pixmap when - // using an editable combobox, so we just remove and insert - // ### use TQComboBox::changeItem(), once that finally works - // Well lets try it now as it seems to work fine for me. We - // can always revert :) - KonqComboListBoxPixmap* item = new KonqComboListBoxPixmap( pix, t, title ); - listBox()->changeItem( item, index ); - - /* - setUpdatesEnabled( false ); - lineEdit()->setUpdatesEnabled( false ); - - removeItem( index ); - insertItem( pix, t, index ); - - setUpdatesEnabled( true ); - lineEdit()->setUpdatesEnabled( true ); - update(); - */ -} - -void KonqCombo::saveState() -{ - m_cursorPos = cursorPosition(); - m_currentText = currentText(); - m_currentIndex = currentItem(); -} - -void KonqCombo::restoreState() -{ - setTemporary( m_currentText ); - lineEdit()->setCursorPosition( m_cursorPos ); -} - -void KonqCombo::updatePixmaps() -{ - saveState(); - - setUpdatesEnabled( false ); - KonqPixmapProvider *prov = KonqPixmapProvider::self(); - for ( int i = 1; i < count(); i++ ) { - updateItem( prov->pixmapFor( text( i ) ), text( i ), i, titleOfURL( text( i ) ) ); - } - setUpdatesEnabled( true ); - repaint(); - - restoreState(); -} - -void KonqCombo::loadItems() -{ - clear(); - int i = 0; - - s_config->setGroup( "History" ); // delete the old 2.0.x completion - s_config->writeEntry( "CompletionItems", "unused" ); - - s_config->setGroup( "Location Bar" ); - TQStringList items = s_config->readPathListEntry( "ComboContents" ); - TQStringList::ConstIterator it = items.begin(); - TQString item; - bool first = true; - while ( it != items.end() ) { - item = *it; - if ( !item.isEmpty() ) { // only insert non-empty items - if( first ) { - insertItem( KonqPixmapProvider::self()->pixmapFor( item, TDEIcon::SizeSmall ), - item, i++, titleOfURL( item ) ); - } - else - // icons will be loaded on-demand - insertItem( item, i++, titleOfURL( item ) ); - first = false; - } - ++it; - } - - if ( count() > 0 ) - m_permanent = true; // we want the first loaded item to stay -} - -void KonqCombo::slotSetIcon( int index ) -{ - if( pixmap( index ) == NULL ) - // on-demand icon loading - updateItem( KonqPixmapProvider::self()->pixmapFor( text( index ), - TDEIcon::SizeSmall ), text( index ), index, - titleOfURL( text( index ) ) ); - update(); -} - -void KonqCombo::popup() -{ - for( int i = 0; i < count(); ++i ) - { - if( pixmap( i ) == NULL || pixmap( i )->isNull() ) - { - // on-demand icon loading - updateItem( KonqPixmapProvider::self()->pixmapFor( text( i ), - TDEIcon::SizeSmall), text( i ), i, titleOfURL( text( i ) ) ); - } - } - KHistoryCombo::popup(); -} - -void KonqCombo::saveItems() -{ - TQStringList items; - int i = m_permanent ? 0 : 1; - - for ( ; i < count(); i++ ) - items.append( text( i ) ); - - s_config->setGroup( "Location Bar" ); - s_config->writePathEntry( "ComboContents", items ); - KonqPixmapProvider::self()->save( s_config, "ComboIconCache", items ); - - s_config->sync(); -} - -void KonqCombo::clearTemporary( bool makeCurrent ) -{ - applyPermanent(); - changeItem( TQString::null, temporary ); // ### default pixmap? - if ( makeCurrent ) - setCurrentItem( temporary ); -} - -bool KonqCombo::eventFilter( TQObject *o, TQEvent *ev ) -{ - // Handle Ctrl+Del/Backspace etc better than the Qt widget, which always - // jumps to the next whitespace. - TQLineEdit *edit = lineEdit(); - if ( TQT_BASE_OBJECT(o) == TQT_BASE_OBJECT(edit) ) { - int type = ev->type(); - if ( type == TQEvent::KeyPress ) { - TQKeyEvent *e = TQT_TQKEYEVENT( ev ); - - if ( e->key() == Key_Return || e->key() == Key_Enter ) { - m_modifier = e->state(); - return false; - } - - if ( KKey( e ) == KKey( int( TDEStdAccel::deleteWordBack() ) ) || - KKey( e ) == KKey( int( TDEStdAccel::deleteWordForward() ) ) || - ((e->state() & ControlButton) && - (e->key() == Key_Left || e->key() == Key_Right) ) ) { - selectWord(e); - e->accept(); - return true; - } - } - - else if ( type == TQEvent::MouseButtonDblClick ) { - edit->selectAll(); - return true; - } - } - return KComboBox::eventFilter( o, ev ); -} - -void KonqCombo::keyPressEvent( TQKeyEvent *e ) -{ - KHistoryCombo::keyPressEvent( e ); - // we have to set it as temporary, otherwise we wouldn't get our nice - // pixmap. Yes, TQComboBox still sucks. - if ( KKey( e ) == KKey( int( TDEStdAccel::rotateUp() ) ) || - KKey( e ) == KKey( int( TDEStdAccel::rotateDown() ) ) ) - setTemporary( currentText() ); -} - -/* - Handle Ctrl+Cursor etc better than the Qt widget, which always - jumps to the next whitespace. This code additionally jumps to - the next [/#?:], which makes more sense for URLs. The list of - chars that will stop the cursor are '/', '.', '?', '#', ':'. -*/ -void KonqCombo::selectWord(TQKeyEvent *e) -{ - TQLineEdit* edit = lineEdit(); - TQString text = edit->text(); - int pos = edit->cursorPosition(); - int pos_old = pos; - int count = 0; - - // TODO: make these a parameter when in tdelibs/tdeui... - TQValueList chars; - chars << TQChar('/') << TQChar('.') << TQChar('?') << TQChar('#') << TQChar(':'); - bool allow_space_break = true; - - if( e->key() == Key_Left || e->key() == Key_Backspace ) { - do { - pos--; - count++; - if( allow_space_break && text[pos].isSpace() && count > 1 ) - break; - } while( pos >= 0 && (chars.findIndex(text[pos]) == -1 || count <= 1) ); - - if( e->state() & ShiftButton ) { - edit->cursorForward(true, 1-count); - } - else if( e->key() == Key_Backspace ) { - edit->cursorForward(false, 1-count); - TQString text = edit->text(); - int pos_to_right = edit->text().length() - pos_old; - TQString cut = text.left(edit->cursorPosition()) + text.right(pos_to_right); - edit->setText(cut); - edit->setCursorPosition(pos_old-count+1); - } - else { - edit->cursorForward(false, 1-count); - } - } - else if( e->key() == Key_Right || e->key() == Key_Delete ){ - do { - pos++; - count++; - if( allow_space_break && text[pos].isSpace() ) - break; - } while( pos < (int) text.length() && chars.findIndex(text[pos]) == -1 ); - - if( e->state() & ShiftButton ) { - edit->cursorForward(true, count+1); - } - else if( e->key() == Key_Delete ) { - edit->cursorForward(false, -count-1); - TQString text = edit->text(); - int pos_to_right = text.length() - pos - 1; - TQString cut = text.left(pos_old) + - (pos_to_right > 0 ? text.right(pos_to_right) : TQString::null ); - edit->setText(cut); - edit->setCursorPosition(pos_old); - } - else { - edit->cursorForward(false, count+1); - } - } -} - -void KonqCombo::slotCleared() -{ - TQByteArray data; - TQDataStream s( data, IO_WriteOnly ); - s << kapp->dcopClient()->defaultObject(); - kapp->dcopClient()->send( "konqueror*", "KonquerorIface", "comboCleared(TQCString)", data); -} - -void KonqCombo::slotRemoved( const TQString& item ) -{ - TQByteArray data; - TQDataStream s( data, IO_WriteOnly ); - s << item << kapp->dcopClient()->defaultObject(); - kapp->dcopClient()->send( "konqueror*", "KonquerorIface", - "removeFromCombo(TQString,TQCString)", data); -} - -void KonqCombo::removeURL( const TQString& url ) -{ - setUpdatesEnabled( false ); - lineEdit()->setUpdatesEnabled( false ); - - removeFromHistory( url ); - applyPermanent(); - setTemporary( currentText() ); - - setUpdatesEnabled( true ); - lineEdit()->setUpdatesEnabled( true ); - update(); -} - -void KonqCombo::mousePressEvent( TQMouseEvent *e ) -{ - m_dragStart = TQPoint(); // null QPoint - - if ( e->button() == Qt::LeftButton && pixmap( currentItem()) ) { - // check if the pixmap was clicked - int x = e->pos().x(); - int x0 = TQStyle::visualRect( style().querySubControlMetrics( TQStyle::CC_ComboBox, this, TQStyle::SC_ComboBoxEditField ), this ).x(); - - if ( x > x0 + 2 && x < lineEdit()->x() ) { - m_dragStart = e->pos(); - return; // don't call KComboBox::mousePressEvent! - } - } - - if ( e->button() == Qt::LeftButton && m_pageSecurity!=KonqMainWindow::NotCrypted ) { - // check if the lock icon was clicked - int x = e->pos().x(); - int x0 = TQStyle::visualRect( style().querySubControlMetrics( TQStyle::CC_ComboBox, this, TQStyle::SC_ComboBoxArrow ), this ).x(); - if ( x < x0 ) - emit showPageSecurity(); - - } - - KComboBox::mousePressEvent( e ); -} - -void KonqCombo::mouseMoveEvent( TQMouseEvent *e ) -{ - KComboBox::mouseMoveEvent( e ); - if ( m_dragStart.isNull() || currentText().isEmpty() ) - return; - - if ( e->state() & Qt::LeftButton && - (e->pos() - m_dragStart).manhattanLength() > - TDEGlobalSettings::dndEventDelay() ) - { - KURL url = KURL::fromPathOrURL( currentText() ); - if ( url.isValid() ) - { - KURL::List list; - list.append( url ); - KURLDrag *drag = new KURLDrag( list, this ); - TQPixmap pix = KonqPixmapProvider::self()->pixmapFor( currentText(), - TDEIcon::SizeMedium ); - if ( !pix.isNull() ) - drag->setPixmap( pix ); - drag->dragCopy(); - } - } -} - -void KonqCombo::slotActivated( const TQString& text ) -{ - //kdDebug(1202) << "KonqCombo::slotActivated: " << text << endl; - applyPermanent(); - m_returnPressed = true; - emit activated( text, m_modifier ); - m_modifier = Qt::NoButton; -} - -void KonqCombo::setConfig( TDEConfig *kc ) -{ - s_config = kc; -} - -void KonqCombo::paintEvent( TQPaintEvent *pe ) -{ - TQComboBox::paintEvent( pe ); - - TQLineEdit *edit = lineEdit(); - TQRect re = style().querySubControlMetrics( TQStyle::CC_ComboBox, this, TQStyle::SC_ComboBoxEditField ); - re = TQStyle::visualRect(re, this); - - if ( m_pageSecurity!=KonqMainWindow::NotCrypted ) { - TQColor color(245, 246, 190); - bool useColor = hasSufficientContrast(color,edit->paletteForegroundColor()); - - TQPainter p( this ); - p.setClipRect( re ); - - TQPixmap pix = KonqPixmapProvider::self()->pixmapFor( currentText() ); - if ( useColor ) { - p.fillRect( re.x(), re.y(), pix.width() + 4, re.height(), TQBrush( color )); - p.drawPixmap( re.x() + 2, re.y() + ( re.height() - pix.height() ) / 2, pix ); - } - - TQRect r = edit->geometry(); - r.setRight( re.right() - pix.width() - 4 ); - if ( r != edit->geometry() ) - edit->setGeometry( r ); - - if ( useColor) - edit->setPaletteBackgroundColor( color ); - - pix = SmallIcon( m_pageSecurity==KonqMainWindow::Encrypted ? "encrypted" : "halfencrypted" ); - p.fillRect( re.right() - pix.width() - 3 , re.y(), pix.width() + 4, re.height(), - TQBrush( useColor ? color : edit->paletteBackgroundColor() )); - p.drawPixmap( re.right() - pix.width() -1 , re.y() + ( re.height() - pix.height() ) / 2, pix ); - p.setClipping( FALSE ); - } - else { - TQRect r = edit->geometry(); - r.setRight( re.right() ); - if ( r != edit->geometry() ) - edit->setGeometry( r ); - edit->setPaletteBackgroundColor( TQApplication::palette( edit ).color( TQPalette::Active, TQColorGroup::Base ) ); - } -} - -void KonqCombo::setPageSecurity( int pageSecurity ) -{ - m_pageSecurity = pageSecurity; - repaint(); -} - -bool KonqCombo::hasSufficientContrast(const TQColor &c1, const TQColor &c2) -{ - // Taken from tdehtml/misc/helper.cc -#define HUE_DISTANCE 40 -#define CONTRAST_DISTANCE 10 - - int h1, s1, v1, h2, s2, v2; - int hdist = -CONTRAST_DISTANCE; - c1.hsv(&h1,&s1,&v1); - c2.hsv(&h2,&s2,&v2); - if(h1!=-1 && h2!=-1) { // grey values have no hue - hdist = kAbs(h1-h2); - if (hdist > 180) hdist = 360-hdist; - if (hdist < HUE_DISTANCE) { - hdist -= HUE_DISTANCE; - // see if they are high key or low key colours - bool hk1 = h1>=45 && h1<=225; - bool hk2 = h2>=45 && h2<=225; - if (hk1 && hk2) - hdist = (5*hdist)/3; - else if (!hk1 && !hk2) - hdist = (7*hdist)/4; - } - hdist = kMin(hdist, HUE_DISTANCE*2); - } - return hdist + (kAbs(s1-s2)*128)/(160+kMin(s1,s2)) + kAbs(v1-v2) > CONTRAST_DISTANCE; -} - -/////////////////////////////////////////////////////////////////////////////// - -KonqComboListBoxPixmap::KonqComboListBoxPixmap( const TQString& text ) - : TQListBoxItem() -{ - setText( text ); - lookup_pending = true; -} - -KonqComboListBoxPixmap::KonqComboListBoxPixmap( const TQPixmap & pix, const TQString& text, const TQString& _title ) - : TQListBoxItem() -{ - pm = pix; - title = _title; - setText( text ); - lookup_pending = false; -} - -void KonqComboListBoxPixmap::paint( TQPainter *painter ) -{ - if ( lookup_pending ) { - title = titleOfURL( text() ); - if ( !title.isEmpty() ) - pm = KonqPixmapProvider::self()->pixmapFor( text(), TDEIcon::SizeSmall ); - else if ( text().find( "://" ) == -1 ) { - title = titleOfURL( "http://"+text() ); - if ( !title.isEmpty() ) - pm = KonqPixmapProvider::self()->pixmapFor( "http://"+text(), TDEIcon::SizeSmall ); - else - pm = KonqPixmapProvider::self()->pixmapFor( text(), TDEIcon::SizeSmall ); - } - else - pm = TQPixmap(); - lookup_pending = false; - } - - int itemHeight = height( listBox() ); - int yPos, pmWidth = 0; - const TQPixmap *pm = pixmap(); - - if ( pm && ! pm->isNull() ) { - yPos = ( itemHeight - pm->height() ) / 2; - painter->drawPixmap( 3, yPos, *pm ); - pmWidth = pm->width() + 5; - } - - int entryWidth = listBox()->width() - listBox()->style().pixelMetric( TQStyle::PM_ScrollBarExtent ) - - 2 * listBox()->style().pixelMetric( TQStyle::PM_DefaultFrameWidth ); - int titleWidth = ( entryWidth / 3 ) - 1; - int urlWidth = entryWidth - titleWidth - pmWidth - 2; - - if ( !text().isEmpty() ) { - TQString squeezedText = KStringHandler::rPixelSqueeze( text(), listBox()->fontMetrics(), urlWidth ); - painter->drawText( pmWidth, 0, urlWidth + pmWidth, itemHeight, - Qt::AlignLeft | Qt::AlignTop, squeezedText ); - - //painter->setPen( TDEGlobalSettings::inactiveTextColor() ); - squeezedText = KStringHandler::rPixelSqueeze( title, listBox()->fontMetrics(), titleWidth ); - TQFont font = painter->font(); - font.setItalic( true ); - painter->setFont( font ); - painter->drawText( entryWidth - titleWidth, 0, titleWidth, - itemHeight, Qt::AlignLeft | Qt::AlignTop, squeezedText ); - } -} - -int KonqComboListBoxPixmap::height( const TQListBox* lb ) const -{ - int h; - if ( text().isEmpty() ) - h = pm.height(); - else - h = TQMAX( pm.height(), lb->fontMetrics().lineSpacing() + 2 ); - return TQMAX( h, TQApplication::globalStrut().height() ); -} - -int KonqComboListBoxPixmap::width( const TQListBox* lb ) const -{ - if ( text().isEmpty() ) - return TQMAX( pm.width() + 6, TQApplication::globalStrut().width() ); - return TQMAX( pm.width() + lb->fontMetrics().width( text() ) + 6, - TQApplication::globalStrut().width() ); -} - -int KonqComboListBoxPixmap::RTTI = 1003; - -int KonqComboListBoxPixmap::rtti() const -{ - return RTTI; -} - -bool KonqComboListBoxPixmap::reuse( const TQString& newText ) -{ - if ( text() == newText ) - return false; - - lookup_pending = true; - setText( newText ); - return true; -} - -/////////////////////////////////////////////////////////////////////////////// - -KonqComboLineEdit::KonqComboLineEdit( TQWidget *parent, const char *name ) - :KLineEdit( parent, name ) {} - -void KonqComboLineEdit::setCompletedItems( const TQStringList& items ) -{ - TQString txt; - KonqComboCompletionBox *completionbox = static_cast( completionBox() ); - - if ( completionbox && completionbox->isVisible() ) - // The popup is visible already - do the matching on the initial string, - // not on the currently selected one. - txt = completionbox->cancelledText(); - else - txt = text(); - - if ( !items.isEmpty() && !(items.count() == 1 && txt == items.first()) ) { - if ( !completionBox( false ) ) - setCompletionBox( new KonqComboCompletionBox( this, "completion box" ) ); - - if ( completionbox->isVisible() ) { - bool wasSelected = completionbox->isSelected( completionbox->currentItem() ); - const TQString currentSelection = completionbox->currentText(); - completionbox->setItems( items ); - TQListBoxItem* item = completionbox->findItem( currentSelection, TQt::ExactMatch ); - if( !item || !wasSelected ) - { - wasSelected = false; - item = completionbox->item( 0 ); - } - if ( item ) { - completionbox->blockSignals( true ); - completionbox->setCurrentItem( item ); - completionbox->setSelected( item, wasSelected ); - completionbox->blockSignals( false ); - } - } - else { // completion box not visible yet -> show it - if ( !txt.isEmpty() ) - completionbox->setCancelledText( txt ); - completionbox->setItems( items ); - completionbox->popup(); - } - - if ( autoSuggest() ) { - int index = items.first().find( txt ); - TQString newText = items.first().mid( index ); - setUserSelection( false ); - setCompletedText( newText, true ); - } - } - else - if ( completionbox && completionbox->isVisible() ) - completionbox->hide(); -} - -/////////////////////////////////////////////////////////////////////////////// - -KonqComboCompletionBox::KonqComboCompletionBox( TQWidget *parent, const char *name ) - :TDECompletionBox( parent, name ) {} - -void KonqComboCompletionBox::setItems( const TQStringList& items ) -{ - bool block = signalsBlocked(); - blockSignals( true ); - - TQListBoxItem* item = firstItem(); - if ( !item ) - insertStringList( items ); - else { - //Keep track of whether we need to change anything, - //so we can avoid a repaint for identical updates, - //to reduce flicker - bool dirty = false; - - TQStringList::ConstIterator it = items.constBegin(); - const TQStringList::ConstIterator itEnd = items.constEnd(); - - for ( ; it != itEnd; ++it) { - if ( item ) { - const bool changed = ((KonqComboListBoxPixmap*)item)->reuse( *it ); - dirty = dirty || changed; - item = item->next(); - } - else { - dirty = true; - //Inserting an item is a way of making this dirty - insertItem( new KonqComboListBoxPixmap( *it ) ); - } - } - - //If there is an unused item, mark as dirty -> less items now - if ( item ) - dirty = true; - - TQListBoxItem* tmp = item; - while ( (item = tmp ) ) { - tmp = item->next(); - delete item; - } - - if ( dirty ) - triggerUpdate( false ); - } - - if ( isVisible() && size().height() != sizeHint().height() ) - sizeAndPosition(); - - blockSignals( block ); - - // Trigger d->down_workaround = true within TDECompletionBox - TQStringList dummy; - TDECompletionBox::insertItems( dummy, 1 ); -} - -void KonqComboCompletionBox::insertStringList( const TQStringList & list, int index ) -{ - if ( index < 0 ) - index = count(); - for ( TQStringList::ConstIterator it = list.begin(); it != list.end(); ++it ) - insertItem( new KonqComboListBoxPixmap( *it ), index++ ); -} - -#include "konq_combo.moc" diff --git a/konqueror/konq_combo.cpp b/konqueror/konq_combo.cpp new file mode 100644 index 000000000..850859b58 --- /dev/null +++ b/konqueror/konq_combo.cpp @@ -0,0 +1,905 @@ +/* This file is part of the KDE project + Copyright (C) 2001 Carsten Pfeiffer + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "konq_combo.h" + +TDEConfig * KonqCombo::s_config = 0L; +const int KonqCombo::temporary = 0; + +static TQString titleOfURL( const TQString& urlStr ) +{ + KURL url = KURL::fromPathOrURL( urlStr ); + KonqHistoryList& historylist = const_cast( KonqHistoryManager::kself()->entries() ); + KonqHistoryEntry *historyentry = historylist.findEntry( url ); + if ( !historyentry && !url.url().endsWith( "/" ) ) { + url.setPath( url.path()+'/' ); + historyentry = historylist.findEntry( url ); + } + return ( historyentry ? historyentry->title : TQString() ); +} + +class TQ_EXPORT KonqComboListBoxPixmap : public TQListBoxItem +{ +public: + KonqComboListBoxPixmap( const TQString& text ); + KonqComboListBoxPixmap( const TQPixmap &, const TQString& text, const TQString& title ); + + const TQPixmap *pixmap() const { return ± } + + int height( const TQListBox * ) const; + int width( const TQListBox * ) const; + + int rtti() const; + static int RTTI; + + bool reuse( const TQString& newText ); + +protected: + void paint( TQPainter * ); + +private: + bool lookup_pending; + TQPixmap pm; + TQString title; +}; + +class KonqComboLineEdit : public KLineEdit +{ +public: + KonqComboLineEdit( TQWidget *parent=0, const char *name=0 ); + void setCompletedItems( const TQStringList& items ); +}; + +class KonqComboCompletionBox : public TDECompletionBox +{ +public: + KonqComboCompletionBox( TQWidget *parent, const char *name = 0 ); + void setItems( const TQStringList& items ); + void insertStringList( const TQStringList & list, int index = -1 ); +}; + +KonqCombo::KonqCombo( TQWidget *parent, const char *name ) + : KHistoryCombo( parent, name ), + m_returnPressed( false ), + m_permanent( false ), + m_modifier( Qt::NoButton ), + m_pageSecurity( KonqMainWindow::NotCrypted ) +{ + setInsertionPolicy( NoInsertion ); + setSizePolicy( TQSizePolicy( TQSizePolicy::Expanding, TQSizePolicy::Fixed )); + + Q_ASSERT( s_config ); + + TDEConfigGroupSaver cs( s_config, "Location Bar" ); + setMaxCount( s_config->readNumEntry("Maximum of URLs in combo", 20 )); + + // We should also connect the completionBox' highlighted signal to + // our setEditText() slot, because we're handling the signals ourselves. + // But we're lazy and let TDECompletionBox do this and simply switch off + // handling of signals later. + setHandleSignals( true ); + + KonqComboLineEdit *edit = new KonqComboLineEdit( this, "combo lineedit" ); + edit->setHandleSignals( true ); + edit->setCompletionBox( new KonqComboCompletionBox( edit, "completion box" ) ); + setLineEdit( edit ); + + completionBox()->setTabHandling( true ); + + // Make the lineedit consume the Key_Enter event... + setTrapReturnKey( true ); + + connect( KonqHistoryManager::kself(), TQT_SIGNAL(cleared()), TQT_SLOT(slotCleared()) ); + connect( this, TQT_SIGNAL(cleared() ), TQT_SLOT(slotCleared()) ); + connect( this, TQT_SIGNAL(highlighted( int )), TQT_SLOT(slotSetIcon( int )) ); + connect( this, TQT_SIGNAL(activated( const TQString& )), + TQT_SLOT(slotActivated( const TQString& )) ); + + setHistoryEditorEnabled( true ); + connect( this, TQT_SIGNAL(removed( const TQString&) ), TQT_SLOT(slotRemoved( const TQString& )) ); + + if ( !kapp->dcopClient()->isAttached() ) + kapp->dcopClient()->attach(); +} + +KonqCombo::~KonqCombo() +{ +} + +void KonqCombo::init( TDECompletion *completion ) +{ + setCompletionObject( completion, false ); //KonqMainWindow handles signals + setAutoDeleteCompletionObject( false ); + setCompletionMode( completion->completionMode() ); + + loadItems(); +} + +void KonqCombo::setURL( const TQString& url ) +{ + //kdDebug(1202) << "KonqCombo::setURL: " << url << ", returnPressed ? " << m_returnPressed << endl; + setTemporary( url ); + + if ( m_returnPressed ) { // Really insert... + m_returnPressed = false; + TQByteArray data; + TQDataStream s( data, IO_WriteOnly ); + s << url << kapp->dcopClient()->defaultObject(); + kapp->dcopClient()->send( "konqueror*", "KonquerorIface", + "addToCombo(TQString,TQCString)", data); + } + // important security consideration: always display the beginning + // of the url rather than its end to prevent spoofing attempts. + lineEdit()->setCursorPosition( 0 ); +} + +void KonqCombo::setTemporary( const TQString& text ) +{ + setTemporary( text, KonqPixmapProvider::self()->pixmapFor(text) ); +} + +void KonqCombo::setTemporary( const TQString& url, const TQPixmap& pix ) +{ + //kdDebug(1202) << "KonqCombo::setTemporary: " << url << ", temporary = " << temporary << endl; + + // Insert a temporary item when we don't have one yet + if ( count() == 0 ) + insertItem( pix, url, temporary, titleOfURL( url ) ); + else + { + if (url != temporaryItem()) + applyPermanent(); + + updateItem( pix, url, temporary, titleOfURL( url ) ); + } + + setCurrentItem( temporary ); +} + +void KonqCombo::removeDuplicates( int index ) +{ + //kdDebug(1202) << "KonqCombo::removeDuplicates: Starting index = " << index << endl; + + TQString url (temporaryItem()); + if (url.endsWith("/")) + url.truncate(url.length()-1); + + // Remove all dupes, if available... + for ( int i = index; i < count(); i++ ) + { + TQString item (text(i)); + if (item.endsWith("/")) + item.truncate(item.length()-1); + + if ( item == url ) + removeItem( i ); + } + lineEdit()->setCursorPosition( 0 ); +} + +// called via DCOP in all instances +void KonqCombo::insertPermanent( const TQString& url ) +{ + //kdDebug(1202) << "KonqCombo::insertPermanent: URL = " << url << endl; + saveState(); + setTemporary( url ); + m_permanent = true; + restoreState(); +} + +// called right before a new (different!) temporary item will be set. So we +// insert an item that was marked permanent properly at position 1. +void KonqCombo::applyPermanent() +{ + if ( m_permanent && !temporaryItem().isEmpty() ) { + + // Remove as many items as needed to honour maxCount() + int index = count(); + while ( count() >= maxCount() ) + removeItem( --index ); + + TQString url (temporaryItem()); + insertItem( KonqPixmapProvider::self()->pixmapFor( url ), url, 1, titleOfURL( url ) ); + //kdDebug(1202) << "KonqCombo::applyPermanent: " << url << endl; + + // Remove all duplicates starting from index = 2 + removeDuplicates( 2 ); + m_permanent = false; + } +} + +void KonqCombo::insertItem( const TQString &text, int index, const TQString& title ) +{ + KonqComboListBoxPixmap* item = new KonqComboListBoxPixmap( 0, text, title ); + listBox()->insertItem( item, index ); +} + +void KonqCombo::insertItem( const TQPixmap &pixmap, const TQString& text, int index, const TQString& title ) +{ + KonqComboListBoxPixmap* item = new KonqComboListBoxPixmap( pixmap, text, title ); + listBox()->insertItem( item, index ); +} + +void KonqCombo::updateItem( const TQPixmap& pix, const TQString& t, int index, const TQString& title ) +{ + // No need to flicker + if (text( index ) == t && + (pixmap(index) && pixmap(index)->serialNumber() == pix.serialNumber())) + return; + + // kdDebug(1202) << "KonqCombo::updateItem: item='" << t << "', index='" + // << index << "'" << endl; + + // TQComboBox::changeItem() doesn't honour the pixmap when + // using an editable combobox, so we just remove and insert + // ### use TQComboBox::changeItem(), once that finally works + // Well lets try it now as it seems to work fine for me. We + // can always revert :) + KonqComboListBoxPixmap* item = new KonqComboListBoxPixmap( pix, t, title ); + listBox()->changeItem( item, index ); + + /* + setUpdatesEnabled( false ); + lineEdit()->setUpdatesEnabled( false ); + + removeItem( index ); + insertItem( pix, t, index ); + + setUpdatesEnabled( true ); + lineEdit()->setUpdatesEnabled( true ); + update(); + */ +} + +void KonqCombo::saveState() +{ + m_cursorPos = cursorPosition(); + m_currentText = currentText(); + m_currentIndex = currentItem(); +} + +void KonqCombo::restoreState() +{ + setTemporary( m_currentText ); + lineEdit()->setCursorPosition( m_cursorPos ); +} + +void KonqCombo::updatePixmaps() +{ + saveState(); + + setUpdatesEnabled( false ); + KonqPixmapProvider *prov = KonqPixmapProvider::self(); + for ( int i = 1; i < count(); i++ ) { + updateItem( prov->pixmapFor( text( i ) ), text( i ), i, titleOfURL( text( i ) ) ); + } + setUpdatesEnabled( true ); + repaint(); + + restoreState(); +} + +void KonqCombo::loadItems() +{ + clear(); + int i = 0; + + s_config->setGroup( "History" ); // delete the old 2.0.x completion + s_config->writeEntry( "CompletionItems", "unused" ); + + s_config->setGroup( "Location Bar" ); + TQStringList items = s_config->readPathListEntry( "ComboContents" ); + TQStringList::ConstIterator it = items.begin(); + TQString item; + bool first = true; + while ( it != items.end() ) { + item = *it; + if ( !item.isEmpty() ) { // only insert non-empty items + if( first ) { + insertItem( KonqPixmapProvider::self()->pixmapFor( item, TDEIcon::SizeSmall ), + item, i++, titleOfURL( item ) ); + } + else + // icons will be loaded on-demand + insertItem( item, i++, titleOfURL( item ) ); + first = false; + } + ++it; + } + + if ( count() > 0 ) + m_permanent = true; // we want the first loaded item to stay +} + +void KonqCombo::slotSetIcon( int index ) +{ + if( pixmap( index ) == NULL ) + // on-demand icon loading + updateItem( KonqPixmapProvider::self()->pixmapFor( text( index ), + TDEIcon::SizeSmall ), text( index ), index, + titleOfURL( text( index ) ) ); + update(); +} + +void KonqCombo::popup() +{ + for( int i = 0; i < count(); ++i ) + { + if( pixmap( i ) == NULL || pixmap( i )->isNull() ) + { + // on-demand icon loading + updateItem( KonqPixmapProvider::self()->pixmapFor( text( i ), + TDEIcon::SizeSmall), text( i ), i, titleOfURL( text( i ) ) ); + } + } + KHistoryCombo::popup(); +} + +void KonqCombo::saveItems() +{ + TQStringList items; + int i = m_permanent ? 0 : 1; + + for ( ; i < count(); i++ ) + items.append( text( i ) ); + + s_config->setGroup( "Location Bar" ); + s_config->writePathEntry( "ComboContents", items ); + KonqPixmapProvider::self()->save( s_config, "ComboIconCache", items ); + + s_config->sync(); +} + +void KonqCombo::clearTemporary( bool makeCurrent ) +{ + applyPermanent(); + changeItem( TQString::null, temporary ); // ### default pixmap? + if ( makeCurrent ) + setCurrentItem( temporary ); +} + +bool KonqCombo::eventFilter( TQObject *o, TQEvent *ev ) +{ + // Handle Ctrl+Del/Backspace etc better than the Qt widget, which always + // jumps to the next whitespace. + TQLineEdit *edit = lineEdit(); + if ( TQT_BASE_OBJECT(o) == TQT_BASE_OBJECT(edit) ) { + int type = ev->type(); + if ( type == TQEvent::KeyPress ) { + TQKeyEvent *e = TQT_TQKEYEVENT( ev ); + + if ( e->key() == Key_Return || e->key() == Key_Enter ) { + m_modifier = e->state(); + return false; + } + + if ( KKey( e ) == KKey( int( TDEStdAccel::deleteWordBack() ) ) || + KKey( e ) == KKey( int( TDEStdAccel::deleteWordForward() ) ) || + ((e->state() & ControlButton) && + (e->key() == Key_Left || e->key() == Key_Right) ) ) { + selectWord(e); + e->accept(); + return true; + } + } + + else if ( type == TQEvent::MouseButtonDblClick ) { + edit->selectAll(); + return true; + } + } + return KComboBox::eventFilter( o, ev ); +} + +void KonqCombo::keyPressEvent( TQKeyEvent *e ) +{ + KHistoryCombo::keyPressEvent( e ); + // we have to set it as temporary, otherwise we wouldn't get our nice + // pixmap. Yes, TQComboBox still sucks. + if ( KKey( e ) == KKey( int( TDEStdAccel::rotateUp() ) ) || + KKey( e ) == KKey( int( TDEStdAccel::rotateDown() ) ) ) + setTemporary( currentText() ); +} + +/* + Handle Ctrl+Cursor etc better than the Qt widget, which always + jumps to the next whitespace. This code additionally jumps to + the next [/#?:], which makes more sense for URLs. The list of + chars that will stop the cursor are '/', '.', '?', '#', ':'. +*/ +void KonqCombo::selectWord(TQKeyEvent *e) +{ + TQLineEdit* edit = lineEdit(); + TQString text = edit->text(); + int pos = edit->cursorPosition(); + int pos_old = pos; + int count = 0; + + // TODO: make these a parameter when in tdelibs/tdeui... + TQValueList chars; + chars << TQChar('/') << TQChar('.') << TQChar('?') << TQChar('#') << TQChar(':'); + bool allow_space_break = true; + + if( e->key() == Key_Left || e->key() == Key_Backspace ) { + do { + pos--; + count++; + if( allow_space_break && text[pos].isSpace() && count > 1 ) + break; + } while( pos >= 0 && (chars.findIndex(text[pos]) == -1 || count <= 1) ); + + if( e->state() & ShiftButton ) { + edit->cursorForward(true, 1-count); + } + else if( e->key() == Key_Backspace ) { + edit->cursorForward(false, 1-count); + TQString text = edit->text(); + int pos_to_right = edit->text().length() - pos_old; + TQString cut = text.left(edit->cursorPosition()) + text.right(pos_to_right); + edit->setText(cut); + edit->setCursorPosition(pos_old-count+1); + } + else { + edit->cursorForward(false, 1-count); + } + } + else if( e->key() == Key_Right || e->key() == Key_Delete ){ + do { + pos++; + count++; + if( allow_space_break && text[pos].isSpace() ) + break; + } while( pos < (int) text.length() && chars.findIndex(text[pos]) == -1 ); + + if( e->state() & ShiftButton ) { + edit->cursorForward(true, count+1); + } + else if( e->key() == Key_Delete ) { + edit->cursorForward(false, -count-1); + TQString text = edit->text(); + int pos_to_right = text.length() - pos - 1; + TQString cut = text.left(pos_old) + + (pos_to_right > 0 ? text.right(pos_to_right) : TQString::null ); + edit->setText(cut); + edit->setCursorPosition(pos_old); + } + else { + edit->cursorForward(false, count+1); + } + } +} + +void KonqCombo::slotCleared() +{ + TQByteArray data; + TQDataStream s( data, IO_WriteOnly ); + s << kapp->dcopClient()->defaultObject(); + kapp->dcopClient()->send( "konqueror*", "KonquerorIface", "comboCleared(TQCString)", data); +} + +void KonqCombo::slotRemoved( const TQString& item ) +{ + TQByteArray data; + TQDataStream s( data, IO_WriteOnly ); + s << item << kapp->dcopClient()->defaultObject(); + kapp->dcopClient()->send( "konqueror*", "KonquerorIface", + "removeFromCombo(TQString,TQCString)", data); +} + +void KonqCombo::removeURL( const TQString& url ) +{ + setUpdatesEnabled( false ); + lineEdit()->setUpdatesEnabled( false ); + + removeFromHistory( url ); + applyPermanent(); + setTemporary( currentText() ); + + setUpdatesEnabled( true ); + lineEdit()->setUpdatesEnabled( true ); + update(); +} + +void KonqCombo::mousePressEvent( TQMouseEvent *e ) +{ + m_dragStart = TQPoint(); // null QPoint + + if ( e->button() == Qt::LeftButton && pixmap( currentItem()) ) { + // check if the pixmap was clicked + int x = e->pos().x(); + int x0 = TQStyle::visualRect( style().querySubControlMetrics( TQStyle::CC_ComboBox, this, TQStyle::SC_ComboBoxEditField ), this ).x(); + + if ( x > x0 + 2 && x < lineEdit()->x() ) { + m_dragStart = e->pos(); + return; // don't call KComboBox::mousePressEvent! + } + } + + if ( e->button() == Qt::LeftButton && m_pageSecurity!=KonqMainWindow::NotCrypted ) { + // check if the lock icon was clicked + int x = e->pos().x(); + int x0 = TQStyle::visualRect( style().querySubControlMetrics( TQStyle::CC_ComboBox, this, TQStyle::SC_ComboBoxArrow ), this ).x(); + if ( x < x0 ) + emit showPageSecurity(); + + } + + KComboBox::mousePressEvent( e ); +} + +void KonqCombo::mouseMoveEvent( TQMouseEvent *e ) +{ + KComboBox::mouseMoveEvent( e ); + if ( m_dragStart.isNull() || currentText().isEmpty() ) + return; + + if ( e->state() & Qt::LeftButton && + (e->pos() - m_dragStart).manhattanLength() > + TDEGlobalSettings::dndEventDelay() ) + { + KURL url = KURL::fromPathOrURL( currentText() ); + if ( url.isValid() ) + { + KURL::List list; + list.append( url ); + KURLDrag *drag = new KURLDrag( list, this ); + TQPixmap pix = KonqPixmapProvider::self()->pixmapFor( currentText(), + TDEIcon::SizeMedium ); + if ( !pix.isNull() ) + drag->setPixmap( pix ); + drag->dragCopy(); + } + } +} + +void KonqCombo::slotActivated( const TQString& text ) +{ + //kdDebug(1202) << "KonqCombo::slotActivated: " << text << endl; + applyPermanent(); + m_returnPressed = true; + emit activated( text, m_modifier ); + m_modifier = Qt::NoButton; +} + +void KonqCombo::setConfig( TDEConfig *kc ) +{ + s_config = kc; +} + +void KonqCombo::paintEvent( TQPaintEvent *pe ) +{ + TQComboBox::paintEvent( pe ); + + TQLineEdit *edit = lineEdit(); + TQRect re = style().querySubControlMetrics( TQStyle::CC_ComboBox, this, TQStyle::SC_ComboBoxEditField ); + re = TQStyle::visualRect(re, this); + + if ( m_pageSecurity!=KonqMainWindow::NotCrypted ) { + TQColor color(245, 246, 190); + bool useColor = hasSufficientContrast(color,edit->paletteForegroundColor()); + + TQPainter p( this ); + p.setClipRect( re ); + + TQPixmap pix = KonqPixmapProvider::self()->pixmapFor( currentText() ); + if ( useColor ) { + p.fillRect( re.x(), re.y(), pix.width() + 4, re.height(), TQBrush( color )); + p.drawPixmap( re.x() + 2, re.y() + ( re.height() - pix.height() ) / 2, pix ); + } + + TQRect r = edit->geometry(); + r.setRight( re.right() - pix.width() - 4 ); + if ( r != edit->geometry() ) + edit->setGeometry( r ); + + if ( useColor) + edit->setPaletteBackgroundColor( color ); + + pix = SmallIcon( m_pageSecurity==KonqMainWindow::Encrypted ? "encrypted" : "halfencrypted" ); + p.fillRect( re.right() - pix.width() - 3 , re.y(), pix.width() + 4, re.height(), + TQBrush( useColor ? color : edit->paletteBackgroundColor() )); + p.drawPixmap( re.right() - pix.width() -1 , re.y() + ( re.height() - pix.height() ) / 2, pix ); + p.setClipping( FALSE ); + } + else { + TQRect r = edit->geometry(); + r.setRight( re.right() ); + if ( r != edit->geometry() ) + edit->setGeometry( r ); + edit->setPaletteBackgroundColor( TQApplication::palette( edit ).color( TQPalette::Active, TQColorGroup::Base ) ); + } +} + +void KonqCombo::setPageSecurity( int pageSecurity ) +{ + m_pageSecurity = pageSecurity; + repaint(); +} + +bool KonqCombo::hasSufficientContrast(const TQColor &c1, const TQColor &c2) +{ + // Taken from tdehtml/misc/helper.cpp +#define HUE_DISTANCE 40 +#define CONTRAST_DISTANCE 10 + + int h1, s1, v1, h2, s2, v2; + int hdist = -CONTRAST_DISTANCE; + c1.hsv(&h1,&s1,&v1); + c2.hsv(&h2,&s2,&v2); + if(h1!=-1 && h2!=-1) { // grey values have no hue + hdist = kAbs(h1-h2); + if (hdist > 180) hdist = 360-hdist; + if (hdist < HUE_DISTANCE) { + hdist -= HUE_DISTANCE; + // see if they are high key or low key colours + bool hk1 = h1>=45 && h1<=225; + bool hk2 = h2>=45 && h2<=225; + if (hk1 && hk2) + hdist = (5*hdist)/3; + else if (!hk1 && !hk2) + hdist = (7*hdist)/4; + } + hdist = kMin(hdist, HUE_DISTANCE*2); + } + return hdist + (kAbs(s1-s2)*128)/(160+kMin(s1,s2)) + kAbs(v1-v2) > CONTRAST_DISTANCE; +} + +/////////////////////////////////////////////////////////////////////////////// + +KonqComboListBoxPixmap::KonqComboListBoxPixmap( const TQString& text ) + : TQListBoxItem() +{ + setText( text ); + lookup_pending = true; +} + +KonqComboListBoxPixmap::KonqComboListBoxPixmap( const TQPixmap & pix, const TQString& text, const TQString& _title ) + : TQListBoxItem() +{ + pm = pix; + title = _title; + setText( text ); + lookup_pending = false; +} + +void KonqComboListBoxPixmap::paint( TQPainter *painter ) +{ + if ( lookup_pending ) { + title = titleOfURL( text() ); + if ( !title.isEmpty() ) + pm = KonqPixmapProvider::self()->pixmapFor( text(), TDEIcon::SizeSmall ); + else if ( text().find( "://" ) == -1 ) { + title = titleOfURL( "http://"+text() ); + if ( !title.isEmpty() ) + pm = KonqPixmapProvider::self()->pixmapFor( "http://"+text(), TDEIcon::SizeSmall ); + else + pm = KonqPixmapProvider::self()->pixmapFor( text(), TDEIcon::SizeSmall ); + } + else + pm = TQPixmap(); + lookup_pending = false; + } + + int itemHeight = height( listBox() ); + int yPos, pmWidth = 0; + const TQPixmap *pm = pixmap(); + + if ( pm && ! pm->isNull() ) { + yPos = ( itemHeight - pm->height() ) / 2; + painter->drawPixmap( 3, yPos, *pm ); + pmWidth = pm->width() + 5; + } + + int entryWidth = listBox()->width() - listBox()->style().pixelMetric( TQStyle::PM_ScrollBarExtent ) - + 2 * listBox()->style().pixelMetric( TQStyle::PM_DefaultFrameWidth ); + int titleWidth = ( entryWidth / 3 ) - 1; + int urlWidth = entryWidth - titleWidth - pmWidth - 2; + + if ( !text().isEmpty() ) { + TQString squeezedText = KStringHandler::rPixelSqueeze( text(), listBox()->fontMetrics(), urlWidth ); + painter->drawText( pmWidth, 0, urlWidth + pmWidth, itemHeight, + Qt::AlignLeft | Qt::AlignTop, squeezedText ); + + //painter->setPen( TDEGlobalSettings::inactiveTextColor() ); + squeezedText = KStringHandler::rPixelSqueeze( title, listBox()->fontMetrics(), titleWidth ); + TQFont font = painter->font(); + font.setItalic( true ); + painter->setFont( font ); + painter->drawText( entryWidth - titleWidth, 0, titleWidth, + itemHeight, Qt::AlignLeft | Qt::AlignTop, squeezedText ); + } +} + +int KonqComboListBoxPixmap::height( const TQListBox* lb ) const +{ + int h; + if ( text().isEmpty() ) + h = pm.height(); + else + h = TQMAX( pm.height(), lb->fontMetrics().lineSpacing() + 2 ); + return TQMAX( h, TQApplication::globalStrut().height() ); +} + +int KonqComboListBoxPixmap::width( const TQListBox* lb ) const +{ + if ( text().isEmpty() ) + return TQMAX( pm.width() + 6, TQApplication::globalStrut().width() ); + return TQMAX( pm.width() + lb->fontMetrics().width( text() ) + 6, + TQApplication::globalStrut().width() ); +} + +int KonqComboListBoxPixmap::RTTI = 1003; + +int KonqComboListBoxPixmap::rtti() const +{ + return RTTI; +} + +bool KonqComboListBoxPixmap::reuse( const TQString& newText ) +{ + if ( text() == newText ) + return false; + + lookup_pending = true; + setText( newText ); + return true; +} + +/////////////////////////////////////////////////////////////////////////////// + +KonqComboLineEdit::KonqComboLineEdit( TQWidget *parent, const char *name ) + :KLineEdit( parent, name ) {} + +void KonqComboLineEdit::setCompletedItems( const TQStringList& items ) +{ + TQString txt; + KonqComboCompletionBox *completionbox = static_cast( completionBox() ); + + if ( completionbox && completionbox->isVisible() ) + // The popup is visible already - do the matching on the initial string, + // not on the currently selected one. + txt = completionbox->cancelledText(); + else + txt = text(); + + if ( !items.isEmpty() && !(items.count() == 1 && txt == items.first()) ) { + if ( !completionBox( false ) ) + setCompletionBox( new KonqComboCompletionBox( this, "completion box" ) ); + + if ( completionbox->isVisible() ) { + bool wasSelected = completionbox->isSelected( completionbox->currentItem() ); + const TQString currentSelection = completionbox->currentText(); + completionbox->setItems( items ); + TQListBoxItem* item = completionbox->findItem( currentSelection, TQt::ExactMatch ); + if( !item || !wasSelected ) + { + wasSelected = false; + item = completionbox->item( 0 ); + } + if ( item ) { + completionbox->blockSignals( true ); + completionbox->setCurrentItem( item ); + completionbox->setSelected( item, wasSelected ); + completionbox->blockSignals( false ); + } + } + else { // completion box not visible yet -> show it + if ( !txt.isEmpty() ) + completionbox->setCancelledText( txt ); + completionbox->setItems( items ); + completionbox->popup(); + } + + if ( autoSuggest() ) { + int index = items.first().find( txt ); + TQString newText = items.first().mid( index ); + setUserSelection( false ); + setCompletedText( newText, true ); + } + } + else + if ( completionbox && completionbox->isVisible() ) + completionbox->hide(); +} + +/////////////////////////////////////////////////////////////////////////////// + +KonqComboCompletionBox::KonqComboCompletionBox( TQWidget *parent, const char *name ) + :TDECompletionBox( parent, name ) {} + +void KonqComboCompletionBox::setItems( const TQStringList& items ) +{ + bool block = signalsBlocked(); + blockSignals( true ); + + TQListBoxItem* item = firstItem(); + if ( !item ) + insertStringList( items ); + else { + //Keep track of whether we need to change anything, + //so we can avoid a repaint for identical updates, + //to reduce flicker + bool dirty = false; + + TQStringList::ConstIterator it = items.constBegin(); + const TQStringList::ConstIterator itEnd = items.constEnd(); + + for ( ; it != itEnd; ++it) { + if ( item ) { + const bool changed = ((KonqComboListBoxPixmap*)item)->reuse( *it ); + dirty = dirty || changed; + item = item->next(); + } + else { + dirty = true; + //Inserting an item is a way of making this dirty + insertItem( new KonqComboListBoxPixmap( *it ) ); + } + } + + //If there is an unused item, mark as dirty -> less items now + if ( item ) + dirty = true; + + TQListBoxItem* tmp = item; + while ( (item = tmp ) ) { + tmp = item->next(); + delete item; + } + + if ( dirty ) + triggerUpdate( false ); + } + + if ( isVisible() && size().height() != sizeHint().height() ) + sizeAndPosition(); + + blockSignals( block ); + + // Trigger d->down_workaround = true within TDECompletionBox + TQStringList dummy; + TDECompletionBox::insertItems( dummy, 1 ); +} + +void KonqComboCompletionBox::insertStringList( const TQStringList & list, int index ) +{ + if ( index < 0 ) + index = count(); + for ( TQStringList::ConstIterator it = list.begin(); it != list.end(); ++it ) + insertItem( new KonqComboListBoxPixmap( *it ), index++ ); +} + +#include "konq_combo.moc" diff --git a/konqueror/konq_extensionmanager.cc b/konqueror/konq_extensionmanager.cc deleted file mode 100644 index 4ddfb8870..000000000 --- a/konqueror/konq_extensionmanager.cc +++ /dev/null @@ -1,147 +0,0 @@ -/* - konq_extensionmanager.cc - Extension Manager for Konqueror - - Copyright (c) 2003 by Martijn Klingens - Copyright (c) 2004 by Arend van Beelen jr. - - ************************************************************************* - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ************************************************************************* -*/ - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "konq_extensionmanager.h" -#include "konq_mainwindow.h" - -class KonqExtensionManagerPrivate -{ -public: - KPluginSelector *pluginSelector; - KonqMainWindow *mainWindow; - KParts::ReadOnlyPart* activePart; - bool isChanged; -}; - -KonqExtensionManager::KonqExtensionManager(TQWidget *parent, KonqMainWindow *mainWindow, KParts::ReadOnlyPart* activePart) : - KDialogBase(Plain, i18n("Configure"), Default | Cancel | Apply | Ok | User1, - Ok, parent, "extensionmanager", false, true, KGuiItem(i18n("&Reset"), "edit-undo")) -{ - d = new KonqExtensionManagerPrivate; - showButton(User1, false); - setChanged(false); - - setInitialSize(TQSize(640, 480)); - - (new TQVBoxLayout(plainPage(), 0, 0))->setAutoAdd(true); - d->pluginSelector = new KPluginSelector(plainPage()); - setMainWidget(d->pluginSelector); - connect(d->pluginSelector, TQT_SIGNAL(changed(bool)), this, TQT_SLOT(setChanged(bool))); - connect(d->pluginSelector, TQT_SIGNAL(configCommitted(const TQCString &)), - KSettings::Dispatcher::self(), TQT_SLOT(reparseConfiguration(const TQCString &))); - - d->mainWindow = mainWindow; - d->activePart = activePart; - - // There's a limitation of KPluginSelector here... It assumes that all plugins in a given widget (as created by addPlugins) - // have their config in the same TDEConfig[Group]. So we can't show konqueror extensions and tdehtml extensions in the same tab. - d->pluginSelector->addPlugins("konqueror", i18n("Extensions"), "Extensions", TDEGlobal::config()); - if ( activePart ) { - TDEInstance* instance = activePart->instance(); - d->pluginSelector->addPlugins(instance->instanceName(), i18n("Tools"), "Tools", instance->config()); - d->pluginSelector->addPlugins(instance->instanceName(), i18n("Statusbar"), "Statusbar", instance->config()); - } -} - -KonqExtensionManager::~KonqExtensionManager() -{ - delete d; -} - -void KonqExtensionManager::setChanged(bool c) -{ - d->isChanged = c; - enableButton(Apply, c); -} - -void KonqExtensionManager::slotDefault() -{ - d->pluginSelector->defaults(); - setChanged(false); -} - -void KonqExtensionManager::slotUser1() -{ - d->pluginSelector->load(); - setChanged(false); -} - -void KonqExtensionManager::apply() -{ - if(d->isChanged) - { - d->pluginSelector->save(); - setChanged(false); - if( d->mainWindow ) - { - KParts::Plugin::loadPlugins(TQT_TQOBJECT(d->mainWindow), d->mainWindow, TDEGlobal::instance()); - TQPtrList plugins = KParts::Plugin::pluginObjects(TQT_TQOBJECT(d->mainWindow)); - TQPtrListIterator it(plugins); - KParts::Plugin *plugin; - while((plugin = it.current()) != 0) - { - ++it; - d->mainWindow->factory()->addClient(plugin); - } - } - if ( d->activePart ) - { - KParts::Plugin::loadPlugins( d->activePart, d->activePart, d->activePart->instance() ); - TQPtrList plugins = KParts::Plugin::pluginObjects( d->activePart ); - TQPtrListIterator it(plugins); - KParts::Plugin *plugin; - while((plugin = it.current()) != 0) - { - ++it; - d->activePart->factory()->addClient(plugin); - } - } - } -} - -void KonqExtensionManager::slotApply() -{ - apply(); -} - -void KonqExtensionManager::slotOk() -{ - emit okClicked(); - apply(); - accept(); -} - -void KonqExtensionManager::show() -{ - d->pluginSelector->load(); - - KDialogBase::show(); -} - -#include "konq_extensionmanager.moc" diff --git a/konqueror/konq_extensionmanager.cpp b/konqueror/konq_extensionmanager.cpp new file mode 100644 index 000000000..b00522252 --- /dev/null +++ b/konqueror/konq_extensionmanager.cpp @@ -0,0 +1,147 @@ +/* + konq_extensionmanager.cpp - Extension Manager for Konqueror + + Copyright (c) 2003 by Martijn Klingens + Copyright (c) 2004 by Arend van Beelen jr. + + ************************************************************************* + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ************************************************************************* +*/ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "konq_extensionmanager.h" +#include "konq_mainwindow.h" + +class KonqExtensionManagerPrivate +{ +public: + KPluginSelector *pluginSelector; + KonqMainWindow *mainWindow; + KParts::ReadOnlyPart* activePart; + bool isChanged; +}; + +KonqExtensionManager::KonqExtensionManager(TQWidget *parent, KonqMainWindow *mainWindow, KParts::ReadOnlyPart* activePart) : + KDialogBase(Plain, i18n("Configure"), Default | Cancel | Apply | Ok | User1, + Ok, parent, "extensionmanager", false, true, KGuiItem(i18n("&Reset"), "edit-undo")) +{ + d = new KonqExtensionManagerPrivate; + showButton(User1, false); + setChanged(false); + + setInitialSize(TQSize(640, 480)); + + (new TQVBoxLayout(plainPage(), 0, 0))->setAutoAdd(true); + d->pluginSelector = new KPluginSelector(plainPage()); + setMainWidget(d->pluginSelector); + connect(d->pluginSelector, TQT_SIGNAL(changed(bool)), this, TQT_SLOT(setChanged(bool))); + connect(d->pluginSelector, TQT_SIGNAL(configCommitted(const TQCString &)), + KSettings::Dispatcher::self(), TQT_SLOT(reparseConfiguration(const TQCString &))); + + d->mainWindow = mainWindow; + d->activePart = activePart; + + // There's a limitation of KPluginSelector here... It assumes that all plugins in a given widget (as created by addPlugins) + // have their config in the same TDEConfig[Group]. So we can't show konqueror extensions and tdehtml extensions in the same tab. + d->pluginSelector->addPlugins("konqueror", i18n("Extensions"), "Extensions", TDEGlobal::config()); + if ( activePart ) { + TDEInstance* instance = activePart->instance(); + d->pluginSelector->addPlugins(instance->instanceName(), i18n("Tools"), "Tools", instance->config()); + d->pluginSelector->addPlugins(instance->instanceName(), i18n("Statusbar"), "Statusbar", instance->config()); + } +} + +KonqExtensionManager::~KonqExtensionManager() +{ + delete d; +} + +void KonqExtensionManager::setChanged(bool c) +{ + d->isChanged = c; + enableButton(Apply, c); +} + +void KonqExtensionManager::slotDefault() +{ + d->pluginSelector->defaults(); + setChanged(false); +} + +void KonqExtensionManager::slotUser1() +{ + d->pluginSelector->load(); + setChanged(false); +} + +void KonqExtensionManager::apply() +{ + if(d->isChanged) + { + d->pluginSelector->save(); + setChanged(false); + if( d->mainWindow ) + { + KParts::Plugin::loadPlugins(TQT_TQOBJECT(d->mainWindow), d->mainWindow, TDEGlobal::instance()); + TQPtrList plugins = KParts::Plugin::pluginObjects(TQT_TQOBJECT(d->mainWindow)); + TQPtrListIterator it(plugins); + KParts::Plugin *plugin; + while((plugin = it.current()) != 0) + { + ++it; + d->mainWindow->factory()->addClient(plugin); + } + } + if ( d->activePart ) + { + KParts::Plugin::loadPlugins( d->activePart, d->activePart, d->activePart->instance() ); + TQPtrList plugins = KParts::Plugin::pluginObjects( d->activePart ); + TQPtrListIterator it(plugins); + KParts::Plugin *plugin; + while((plugin = it.current()) != 0) + { + ++it; + d->activePart->factory()->addClient(plugin); + } + } + } +} + +void KonqExtensionManager::slotApply() +{ + apply(); +} + +void KonqExtensionManager::slotOk() +{ + emit okClicked(); + apply(); + accept(); +} + +void KonqExtensionManager::show() +{ + d->pluginSelector->load(); + + KDialogBase::show(); +} + +#include "konq_extensionmanager.moc" diff --git a/konqueror/konq_factory.cc b/konqueror/konq_factory.cc deleted file mode 100644 index d89cbf9a6..000000000 --- a/konqueror/konq_factory.cc +++ /dev/null @@ -1,264 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 1999 Simon Hausmann - Copyright (C) 1999 David Faure - Copyright (C) 1999 Torben Weis - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - -*/ - -#include -#include "konq_factory.h" -#include "version.h" - -#include -#include -#include -#include -#include -#include - -#include -#include - -#include - -TDEAboutData *KonqFactory::s_aboutData = 0; - -KonqViewFactory::KonqViewFactory( KLibFactory *factory, const TQStringList &args, - bool createBrowser ) - : m_factory( factory ), m_args( args ), m_createBrowser( createBrowser ) -{ - if ( m_createBrowser ) - m_args << TQString::fromLatin1( "Browser/View" ); -} - -KParts::ReadOnlyPart *KonqViewFactory::create( TQWidget *parentWidget, const char *widgetName, - TQObject * parent, const char *name ) -{ - if ( !m_factory ) - return 0L; - - TQObject *obj = 0L; - - if ( m_factory->inherits( "KParts::Factory" ) ) - { - if ( m_createBrowser ) - obj = static_cast(m_factory)->createPart( parentWidget, widgetName, parent, name, "Browser/View", m_args ); - - if ( !obj ) - obj = static_cast(m_factory)->createPart( parentWidget, widgetName, parent, name, "KParts::ReadOnlyPart", m_args ); - } - else - { - if ( m_createBrowser ) - obj = m_factory->create( TQT_TQOBJECT(parentWidget), name, "Browser/View", m_args ); - - if ( !obj ) - obj = m_factory->create( TQT_TQOBJECT(parentWidget), name, "KParts::ReadOnlyPart", m_args ); - } - - if ( !obj->inherits( "KParts::ReadOnlyPart" ) ) - kdError(1202) << "Part " << obj << " (" << obj->className() << ") doesn't inherit KParts::ReadOnlyPart !" << endl; - - KParts::ReadOnlyPart* part = static_cast( obj ); - TQFrame* frame = ::tqqt_cast( part->widget() ); - if (frame) - { - frame->setFrameStyle( TQFrame::NoFrame ); - } - - return part; -} - -KonqViewFactory KonqFactory::createView( const TQString &serviceType, - const TQString &serviceName, - KService::Ptr *serviceImpl, - TDETrader::OfferList *partServiceOffers, - TDETrader::OfferList *appServiceOffers, - bool forceAutoEmbed ) -{ - kdDebug(1202) << "Trying to create view for \"" << serviceType << "\"" << endl; - - // We need to get those in any case - TDETrader::OfferList offers, appOffers; - - // Query the trader - getOffers( serviceType, &offers, &appOffers ); - - if ( partServiceOffers ) - (*partServiceOffers) = offers; - if ( appServiceOffers ) - (*appServiceOffers) = appOffers; - - // We ask ourselves whether to do it or not only if no service was specified. - // If it was (from the View menu or from RMB + Embedding service), just do it. - forceAutoEmbed = forceAutoEmbed || !serviceName.isEmpty(); - // Or if we have no associated app anyway, then embed. - forceAutoEmbed = forceAutoEmbed || ( appOffers.isEmpty() && !offers.isEmpty() ); - // Or if the associated app is konqueror itself, then embed. - if ( !appOffers.isEmpty() ) - forceAutoEmbed = forceAutoEmbed || KonqMainWindow::isMimeTypeAssociatedWithSelf( serviceType, appOffers.first() ); - - if ( ! forceAutoEmbed ) - { - if ( ! KonqFMSettings::settings()->shouldEmbed( serviceType ) ) - { - kdDebug(1202) << "KonqFMSettings says: don't embed this servicetype" << endl; - return KonqViewFactory(); - } - } - - KService::Ptr service = 0L; - - // Look for this service - if ( !serviceName.isEmpty() ) - { - TDETrader::OfferList::Iterator it = offers.begin(); - for ( ; it != offers.end() && !service ; ++it ) - { - if ( (*it)->desktopEntryName() == serviceName ) - { - kdDebug(1202) << "Found requested service " << serviceName << endl; - service = *it; - } - } - } - - KLibFactory *factory = 0L; - - if ( service ) - { - kdDebug(1202) << "Trying to open lib for requested service " << service->desktopEntryName() << endl; - factory = KLibLoader::self()->factory( TQFile::encodeName(service->library()) ); - if ( !factory ) - KMessageBox::error(0, - i18n("There was an error loading the module %1.\nThe diagnostics is:\n%2") - .arg(service->name()).arg(KLibLoader::self()->lastErrorMessage())); - } - - TDETrader::OfferList::Iterator it = offers.begin(); - for ( ; !factory && it != offers.end() ; ++it ) - { - service = (*it); - // Allowed as default ? - TQVariant prop = service->property( "X-TDE-BrowserView-AllowAsDefault" ); - kdDebug(1202) << service->desktopEntryName() << " : X-TDE-BrowserView-AllowAsDefault is valid : " << prop.isValid() << endl; - if ( !prop.isValid() || prop.toBool() ) // defaults to true - { - //kdDebug(1202) << "Trying to open lib for service " << service->name() << endl; - // Try loading factory - factory = KLibLoader::self()->factory( TQFile::encodeName(service->library()) ); - if ( !factory ) - KMessageBox::error(0, - i18n("There was an error loading the module %1.\nThe diagnostics is:\n%2") - .arg(service->name()).arg(KLibLoader::self()->lastErrorMessage())); - // If this works, we exit the loop. - } else - kdDebug(1202) << "Not allowed as default " << service->desktopEntryName() << endl; - } - - if ( serviceImpl ) - (*serviceImpl) = service; - - if ( !factory ) - { - kdWarning(1202) << "KonqFactory::createView : no factory" << endl; - return KonqViewFactory(); - } - - TQStringList args; - - TQVariant prop = service->property( "X-TDE-BrowserView-Args" ); - - if ( prop.isValid() ) - { - TQString argStr = prop.toString(); - args = TQStringList::split( " ", argStr ); - } - - return KonqViewFactory( factory, args, service->serviceTypes().contains( "Browser/View" ) ); -} - -void KonqFactory::getOffers( const TQString & serviceType, - TDETrader::OfferList *partServiceOffers, - TDETrader::OfferList *appServiceOffers ) -{ - if ( appServiceOffers ) - { - *appServiceOffers = TDETrader::self()->query( serviceType, "Application", -"DesktopEntryName != 'kfmclient' and DesktopEntryName != 'kfmclient_dir' and DesktopEntryName != 'kfmclient_html'", - TQString::null ); - } - - if ( partServiceOffers ) - { - *partServiceOffers = TDETrader::self()->query( serviceType, "KParts/ReadOnlyPart", - TQString::null, TQString::null ); - } -} - - -const TDEAboutData *KonqFactory::aboutData() -{ - if (!s_aboutData) - { - s_aboutData = new TDEAboutData( "konqueror", I18N_NOOP("Konqueror"), - KONQUEROR_VERSION, - I18N_NOOP("Web browser, file manager, ..."), - TDEAboutData::License_GPL, - I18N_NOOP("(c) 2011-2014, The Trinity Desktop project\n(c) 1999-2010, The Konqueror developers"), - 0, - I18N_NOOP("https://www.trinitydesktop.org") ); - s_aboutData->addAuthor( "Timothy Pearson", I18N_NOOP("Maintainer, Trinity bugfixes"), "kb9vqf@pearsoncomputing.net" ); - s_aboutData->addAuthor( "David Faure", I18N_NOOP("developer (framework, parts, JavaScript, I/O lib) and maintainer"), "faure@kde.org" ); - s_aboutData->addAuthor( "Simon Hausmann", I18N_NOOP("developer (framework, parts)"), "hausmann@kde.org" ); - s_aboutData->addAuthor( "Michael Reiher", I18N_NOOP("developer (framework)"), "michael.reiher@gmx.de" ); - s_aboutData->addAuthor( "Matthias Welk", I18N_NOOP("developer"), "welk@fokus.gmd.de" ); - s_aboutData->addAuthor( "Alexander Neundorf", I18N_NOOP("developer (List views)"), "neundorf@kde.org" ); - s_aboutData->addAuthor( "Michael Brade", I18N_NOOP("developer (List views, I/O lib)"), "brade@kde.org" ); - s_aboutData->addAuthor( "Lars Knoll", I18N_NOOP("developer (HTML rendering engine)"), "knoll@kde.org" ); - s_aboutData->addAuthor( "Dirk Mueller", I18N_NOOP("developer (HTML rendering engine)"), "mueller@kde.org" ); - s_aboutData->addAuthor( "Peter Kelly", I18N_NOOP("developer (HTML rendering engine)"), "pmk@post.com" ); - s_aboutData->addAuthor( "Waldo Bastian", I18N_NOOP("developer (HTML rendering engine, I/O lib)"), "bastian@kde.org" ); - s_aboutData->addAuthor( "Germain Garand", I18N_NOOP("developer (HTML rendering engine)"), "germain@ebooksfrance.org" ); - s_aboutData->addAuthor( "Leo Savernik", I18N_NOOP("developer (HTML rendering engine)"), "l.savernik@aon.at" ); - s_aboutData->addAuthor( "Stephan Kulow", I18N_NOOP("developer (HTML rendering engine, I/O lib, regression test framework)"), "coolo@kde.org" ); - s_aboutData->addAuthor( "Antti Koivisto", I18N_NOOP("developer (HTML rendering engine)"), "koivisto@kde.org" ); - s_aboutData->addAuthor( "Zack Rusin", I18N_NOOP("developer (HTML rendering engine)"), "zack@kde.org" ); - s_aboutData->addAuthor( "Tobias Anton", I18N_NOOP( "developer (HTML rendering engine)" ), "anton@stud.fbi.fh-darmstadt.de" ); - s_aboutData->addAuthor( "Lubos Lunak", I18N_NOOP( "developer (HTML rendering engine)" ), "l.lunak@kde.org" ); - s_aboutData->addAuthor( "Allan Sandfeld Jensen", I18N_NOOP( "developer (HTML rendering engine)" ), "kde@carewolf.com" ); - s_aboutData->addAuthor( "Apple Safari Developers", I18N_NOOP("developer (HTML rendering engine, JavaScript)"), "" ); - s_aboutData->addAuthor( "Harri Porten", I18N_NOOP("developer (JavaScript)"), "porten@kde.org" ); - s_aboutData->addAuthor( "Koos Vriezen", I18N_NOOP("developer (Java applets and other embedded objects)"), "koos.vriezen@xs4all.nl" ); - s_aboutData->addAuthor( "Matt Koss", I18N_NOOP("developer (I/O lib)"), "koss@miesto.sk" ); - s_aboutData->addAuthor( "Alex Zepeda", I18N_NOOP("developer (I/O lib)"), "zipzippy@sonic.net" ); - s_aboutData->addAuthor( "Richard Moore", I18N_NOOP("developer (Java applet support)"), "rich@kde.org" ); - s_aboutData->addAuthor( "Dima Rogozin", I18N_NOOP("developer (Java applet support)"), "dima@mercury.co.il" ); - s_aboutData->addAuthor( "Wynn Wilkes", I18N_NOOP("developer (Java 2 security manager support,\n and other major improvements to applet support)"), "wynnw@calderasystems.com" ); - s_aboutData->addAuthor( "Stefan Schimanski", I18N_NOOP("developer (Netscape plugin support)"), "schimmi@kde.org" ); - s_aboutData->addAuthor( "George Staikos", I18N_NOOP("developer (SSL, Netscape plugins)"), "staikos@kde.org" ); - s_aboutData->addAuthor( "Dawit Alemayehu",I18N_NOOP("developer (I/O lib, Authentication support)"), "adawit@kde.org" ); - s_aboutData->addAuthor( "Carsten Pfeiffer",I18N_NOOP("developer (framework)"), "pfeiffer@kde.org" ); - s_aboutData->addAuthor( "Torsten Rahn", I18N_NOOP("graphics/icons"), "torsten@kde.org" ); - s_aboutData->addAuthor( "Torben Weis", I18N_NOOP("kfm author"), "weis@kde.org" ); - s_aboutData->addAuthor( "Joseph Wenninger", I18N_NOOP("developer (navigation panel framework)"),"jowenn@kde.org"); - s_aboutData->addAuthor( "Stephan Binner", I18N_NOOP("developer (misc stuff)"),"binner@kde.org"); - s_aboutData->addAuthor( "Ivor Hewitt", I18N_NOOP("developer (AdBlock filter)"),"ivor@ivor.org"); - } - return s_aboutData; -} - diff --git a/konqueror/konq_factory.cpp b/konqueror/konq_factory.cpp new file mode 100644 index 000000000..d89cbf9a6 --- /dev/null +++ b/konqueror/konq_factory.cpp @@ -0,0 +1,264 @@ +/* This file is part of the KDE project + Copyright (C) 1999 Simon Hausmann + Copyright (C) 1999 David Faure + Copyright (C) 1999 Torben Weis + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +*/ + +#include +#include "konq_factory.h" +#include "version.h" + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +TDEAboutData *KonqFactory::s_aboutData = 0; + +KonqViewFactory::KonqViewFactory( KLibFactory *factory, const TQStringList &args, + bool createBrowser ) + : m_factory( factory ), m_args( args ), m_createBrowser( createBrowser ) +{ + if ( m_createBrowser ) + m_args << TQString::fromLatin1( "Browser/View" ); +} + +KParts::ReadOnlyPart *KonqViewFactory::create( TQWidget *parentWidget, const char *widgetName, + TQObject * parent, const char *name ) +{ + if ( !m_factory ) + return 0L; + + TQObject *obj = 0L; + + if ( m_factory->inherits( "KParts::Factory" ) ) + { + if ( m_createBrowser ) + obj = static_cast(m_factory)->createPart( parentWidget, widgetName, parent, name, "Browser/View", m_args ); + + if ( !obj ) + obj = static_cast(m_factory)->createPart( parentWidget, widgetName, parent, name, "KParts::ReadOnlyPart", m_args ); + } + else + { + if ( m_createBrowser ) + obj = m_factory->create( TQT_TQOBJECT(parentWidget), name, "Browser/View", m_args ); + + if ( !obj ) + obj = m_factory->create( TQT_TQOBJECT(parentWidget), name, "KParts::ReadOnlyPart", m_args ); + } + + if ( !obj->inherits( "KParts::ReadOnlyPart" ) ) + kdError(1202) << "Part " << obj << " (" << obj->className() << ") doesn't inherit KParts::ReadOnlyPart !" << endl; + + KParts::ReadOnlyPart* part = static_cast( obj ); + TQFrame* frame = ::tqqt_cast( part->widget() ); + if (frame) + { + frame->setFrameStyle( TQFrame::NoFrame ); + } + + return part; +} + +KonqViewFactory KonqFactory::createView( const TQString &serviceType, + const TQString &serviceName, + KService::Ptr *serviceImpl, + TDETrader::OfferList *partServiceOffers, + TDETrader::OfferList *appServiceOffers, + bool forceAutoEmbed ) +{ + kdDebug(1202) << "Trying to create view for \"" << serviceType << "\"" << endl; + + // We need to get those in any case + TDETrader::OfferList offers, appOffers; + + // Query the trader + getOffers( serviceType, &offers, &appOffers ); + + if ( partServiceOffers ) + (*partServiceOffers) = offers; + if ( appServiceOffers ) + (*appServiceOffers) = appOffers; + + // We ask ourselves whether to do it or not only if no service was specified. + // If it was (from the View menu or from RMB + Embedding service), just do it. + forceAutoEmbed = forceAutoEmbed || !serviceName.isEmpty(); + // Or if we have no associated app anyway, then embed. + forceAutoEmbed = forceAutoEmbed || ( appOffers.isEmpty() && !offers.isEmpty() ); + // Or if the associated app is konqueror itself, then embed. + if ( !appOffers.isEmpty() ) + forceAutoEmbed = forceAutoEmbed || KonqMainWindow::isMimeTypeAssociatedWithSelf( serviceType, appOffers.first() ); + + if ( ! forceAutoEmbed ) + { + if ( ! KonqFMSettings::settings()->shouldEmbed( serviceType ) ) + { + kdDebug(1202) << "KonqFMSettings says: don't embed this servicetype" << endl; + return KonqViewFactory(); + } + } + + KService::Ptr service = 0L; + + // Look for this service + if ( !serviceName.isEmpty() ) + { + TDETrader::OfferList::Iterator it = offers.begin(); + for ( ; it != offers.end() && !service ; ++it ) + { + if ( (*it)->desktopEntryName() == serviceName ) + { + kdDebug(1202) << "Found requested service " << serviceName << endl; + service = *it; + } + } + } + + KLibFactory *factory = 0L; + + if ( service ) + { + kdDebug(1202) << "Trying to open lib for requested service " << service->desktopEntryName() << endl; + factory = KLibLoader::self()->factory( TQFile::encodeName(service->library()) ); + if ( !factory ) + KMessageBox::error(0, + i18n("There was an error loading the module %1.\nThe diagnostics is:\n%2") + .arg(service->name()).arg(KLibLoader::self()->lastErrorMessage())); + } + + TDETrader::OfferList::Iterator it = offers.begin(); + for ( ; !factory && it != offers.end() ; ++it ) + { + service = (*it); + // Allowed as default ? + TQVariant prop = service->property( "X-TDE-BrowserView-AllowAsDefault" ); + kdDebug(1202) << service->desktopEntryName() << " : X-TDE-BrowserView-AllowAsDefault is valid : " << prop.isValid() << endl; + if ( !prop.isValid() || prop.toBool() ) // defaults to true + { + //kdDebug(1202) << "Trying to open lib for service " << service->name() << endl; + // Try loading factory + factory = KLibLoader::self()->factory( TQFile::encodeName(service->library()) ); + if ( !factory ) + KMessageBox::error(0, + i18n("There was an error loading the module %1.\nThe diagnostics is:\n%2") + .arg(service->name()).arg(KLibLoader::self()->lastErrorMessage())); + // If this works, we exit the loop. + } else + kdDebug(1202) << "Not allowed as default " << service->desktopEntryName() << endl; + } + + if ( serviceImpl ) + (*serviceImpl) = service; + + if ( !factory ) + { + kdWarning(1202) << "KonqFactory::createView : no factory" << endl; + return KonqViewFactory(); + } + + TQStringList args; + + TQVariant prop = service->property( "X-TDE-BrowserView-Args" ); + + if ( prop.isValid() ) + { + TQString argStr = prop.toString(); + args = TQStringList::split( " ", argStr ); + } + + return KonqViewFactory( factory, args, service->serviceTypes().contains( "Browser/View" ) ); +} + +void KonqFactory::getOffers( const TQString & serviceType, + TDETrader::OfferList *partServiceOffers, + TDETrader::OfferList *appServiceOffers ) +{ + if ( appServiceOffers ) + { + *appServiceOffers = TDETrader::self()->query( serviceType, "Application", +"DesktopEntryName != 'kfmclient' and DesktopEntryName != 'kfmclient_dir' and DesktopEntryName != 'kfmclient_html'", + TQString::null ); + } + + if ( partServiceOffers ) + { + *partServiceOffers = TDETrader::self()->query( serviceType, "KParts/ReadOnlyPart", + TQString::null, TQString::null ); + } +} + + +const TDEAboutData *KonqFactory::aboutData() +{ + if (!s_aboutData) + { + s_aboutData = new TDEAboutData( "konqueror", I18N_NOOP("Konqueror"), + KONQUEROR_VERSION, + I18N_NOOP("Web browser, file manager, ..."), + TDEAboutData::License_GPL, + I18N_NOOP("(c) 2011-2014, The Trinity Desktop project\n(c) 1999-2010, The Konqueror developers"), + 0, + I18N_NOOP("https://www.trinitydesktop.org") ); + s_aboutData->addAuthor( "Timothy Pearson", I18N_NOOP("Maintainer, Trinity bugfixes"), "kb9vqf@pearsoncomputing.net" ); + s_aboutData->addAuthor( "David Faure", I18N_NOOP("developer (framework, parts, JavaScript, I/O lib) and maintainer"), "faure@kde.org" ); + s_aboutData->addAuthor( "Simon Hausmann", I18N_NOOP("developer (framework, parts)"), "hausmann@kde.org" ); + s_aboutData->addAuthor( "Michael Reiher", I18N_NOOP("developer (framework)"), "michael.reiher@gmx.de" ); + s_aboutData->addAuthor( "Matthias Welk", I18N_NOOP("developer"), "welk@fokus.gmd.de" ); + s_aboutData->addAuthor( "Alexander Neundorf", I18N_NOOP("developer (List views)"), "neundorf@kde.org" ); + s_aboutData->addAuthor( "Michael Brade", I18N_NOOP("developer (List views, I/O lib)"), "brade@kde.org" ); + s_aboutData->addAuthor( "Lars Knoll", I18N_NOOP("developer (HTML rendering engine)"), "knoll@kde.org" ); + s_aboutData->addAuthor( "Dirk Mueller", I18N_NOOP("developer (HTML rendering engine)"), "mueller@kde.org" ); + s_aboutData->addAuthor( "Peter Kelly", I18N_NOOP("developer (HTML rendering engine)"), "pmk@post.com" ); + s_aboutData->addAuthor( "Waldo Bastian", I18N_NOOP("developer (HTML rendering engine, I/O lib)"), "bastian@kde.org" ); + s_aboutData->addAuthor( "Germain Garand", I18N_NOOP("developer (HTML rendering engine)"), "germain@ebooksfrance.org" ); + s_aboutData->addAuthor( "Leo Savernik", I18N_NOOP("developer (HTML rendering engine)"), "l.savernik@aon.at" ); + s_aboutData->addAuthor( "Stephan Kulow", I18N_NOOP("developer (HTML rendering engine, I/O lib, regression test framework)"), "coolo@kde.org" ); + s_aboutData->addAuthor( "Antti Koivisto", I18N_NOOP("developer (HTML rendering engine)"), "koivisto@kde.org" ); + s_aboutData->addAuthor( "Zack Rusin", I18N_NOOP("developer (HTML rendering engine)"), "zack@kde.org" ); + s_aboutData->addAuthor( "Tobias Anton", I18N_NOOP( "developer (HTML rendering engine)" ), "anton@stud.fbi.fh-darmstadt.de" ); + s_aboutData->addAuthor( "Lubos Lunak", I18N_NOOP( "developer (HTML rendering engine)" ), "l.lunak@kde.org" ); + s_aboutData->addAuthor( "Allan Sandfeld Jensen", I18N_NOOP( "developer (HTML rendering engine)" ), "kde@carewolf.com" ); + s_aboutData->addAuthor( "Apple Safari Developers", I18N_NOOP("developer (HTML rendering engine, JavaScript)"), "" ); + s_aboutData->addAuthor( "Harri Porten", I18N_NOOP("developer (JavaScript)"), "porten@kde.org" ); + s_aboutData->addAuthor( "Koos Vriezen", I18N_NOOP("developer (Java applets and other embedded objects)"), "koos.vriezen@xs4all.nl" ); + s_aboutData->addAuthor( "Matt Koss", I18N_NOOP("developer (I/O lib)"), "koss@miesto.sk" ); + s_aboutData->addAuthor( "Alex Zepeda", I18N_NOOP("developer (I/O lib)"), "zipzippy@sonic.net" ); + s_aboutData->addAuthor( "Richard Moore", I18N_NOOP("developer (Java applet support)"), "rich@kde.org" ); + s_aboutData->addAuthor( "Dima Rogozin", I18N_NOOP("developer (Java applet support)"), "dima@mercury.co.il" ); + s_aboutData->addAuthor( "Wynn Wilkes", I18N_NOOP("developer (Java 2 security manager support,\n and other major improvements to applet support)"), "wynnw@calderasystems.com" ); + s_aboutData->addAuthor( "Stefan Schimanski", I18N_NOOP("developer (Netscape plugin support)"), "schimmi@kde.org" ); + s_aboutData->addAuthor( "George Staikos", I18N_NOOP("developer (SSL, Netscape plugins)"), "staikos@kde.org" ); + s_aboutData->addAuthor( "Dawit Alemayehu",I18N_NOOP("developer (I/O lib, Authentication support)"), "adawit@kde.org" ); + s_aboutData->addAuthor( "Carsten Pfeiffer",I18N_NOOP("developer (framework)"), "pfeiffer@kde.org" ); + s_aboutData->addAuthor( "Torsten Rahn", I18N_NOOP("graphics/icons"), "torsten@kde.org" ); + s_aboutData->addAuthor( "Torben Weis", I18N_NOOP("kfm author"), "weis@kde.org" ); + s_aboutData->addAuthor( "Joseph Wenninger", I18N_NOOP("developer (navigation panel framework)"),"jowenn@kde.org"); + s_aboutData->addAuthor( "Stephan Binner", I18N_NOOP("developer (misc stuff)"),"binner@kde.org"); + s_aboutData->addAuthor( "Ivor Hewitt", I18N_NOOP("developer (AdBlock filter)"),"ivor@ivor.org"); + } + return s_aboutData; +} + diff --git a/konqueror/konq_frame.cc b/konqueror/konq_frame.cc deleted file mode 100644 index 0acf39b49..000000000 --- a/konqueror/konq_frame.cc +++ /dev/null @@ -1,680 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 1998, 1999 Michael Reiher - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "konq_events.h" -#include "konq_frame.h" -#include "konq_tabs.h" -#include "konq_view.h" -#include "konq_viewmgr.h" - -#include -#include -#include - - -#define DEFAULT_HEADER_HEIGHT 13 - -void KonqCheckBox::drawButton( TQPainter *p ) -{ - //static TQPixmap indicator_anchor( UserIcon( "indicator_anchor" ) ); - static TQPixmap indicator_connect( UserIcon( "indicator_connect" ) ); - static TQPixmap indicator_noconnect( UserIcon( "indicator_noconnect" ) ); - - if (isOn() || isDown()) - p->drawPixmap(0,0,indicator_connect); - else - p->drawPixmap(0,0,indicator_noconnect); -} - -KonqFrameStatusBar::KonqFrameStatusBar( KonqFrame *_parent, const char *_name ) - : KStatusBar( _parent, _name ), - m_pParentKonqFrame( _parent ) -{ - setSizeGripEnabled( false ); - - m_led = new TQLabel( this ); - m_led->setAlignment( Qt::AlignCenter ); - m_led->setSizePolicy(TQSizePolicy( TQSizePolicy::Fixed, TQSizePolicy::Fixed )); - addWidget( m_led, 0, false ); // led (active view indicator) - m_led->hide(); - - m_pStatusLabel = new KSqueezedTextLabel( this ); - m_pStatusLabel->setMinimumSize( 0, 0 ); - m_pStatusLabel->setSizePolicy(TQSizePolicy( TQSizePolicy::Ignored, TQSizePolicy::Fixed )); - m_pStatusLabel->installEventFilter(this); - addWidget( m_pStatusLabel, 1 /*stretch*/, false ); // status label - - m_pLinkedViewCheckBox = new KonqCheckBox( this, "m_pLinkedViewCheckBox" ); - m_pLinkedViewCheckBox->setFocusPolicy(TQ_NoFocus); - m_pLinkedViewCheckBox->setSizePolicy(TQSizePolicy( TQSizePolicy::Fixed, TQSizePolicy::Fixed )); - TQWhatsThis::add( m_pLinkedViewCheckBox, - i18n("Checking this box on at least two views sets those views as 'linked'. " - "Then, when you change directories in one view, the other views " - "linked with it will automatically update to show the current directory. " - "This is especially useful with different types of views, such as a " - "directory tree with an icon view or detailed view, and possibly a " - "terminal emulator window." ) ); - addWidget( m_pLinkedViewCheckBox, 0, true /*permanent->right align*/ ); - connect( m_pLinkedViewCheckBox, TQT_SIGNAL(toggled(bool)), - this, TQT_SIGNAL(linkedViewClicked(bool)) ); - - m_progressBar = new KProgress( this ); - m_progressBar->setMaximumHeight(fontMetrics().height()); - m_progressBar->hide(); - addWidget( m_progressBar, 0, true /*permanent->right align*/ ); - -// // FIXME: This was added by OpenSUSE; someone needs to figure out what it does and how to fix it! -// StatusBarNetworkStatusIndicator * indicator = new StatusBarNetworkStatusIndicator( this, "networkstatusindicator" ); -// addWidget( indicator, 0, false ); -// indicator->init(); - - fontChange(TQFont()); - installEventFilter( this ); -} - -KonqFrameStatusBar::~KonqFrameStatusBar() -{ -} - -void KonqFrameStatusBar::fontChange(const TQFont & /* oldFont */) -{ - int h = fontMetrics().height(); - if ( h < DEFAULT_HEADER_HEIGHT ) h = DEFAULT_HEADER_HEIGHT; - m_led->setFixedHeight( h + 2 ); - m_progressBar->setFixedHeight( h + 2 ); - // This one is important. Otherwise richtext messages make it grow in height. - m_pStatusLabel->setFixedHeight( h + 2 ); - -} - -void KonqFrameStatusBar::resizeEvent( TQResizeEvent* ev ) -{ - //m_progressBar->setGeometry( width()-160, 0, 140, height() ); - //m_pLinkedViewCheckBox->move( width()-15, m_yOffset ); // right justify - KStatusBar::resizeEvent( ev ); -} - -// I don't think this code _ever_ gets called! -// I don't want to remove it, though. :-) -void KonqFrameStatusBar::mousePressEvent( TQMouseEvent* event ) -{ - TQWidget::mousePressEvent( event ); - if ( !m_pParentKonqFrame->childView()->isPassiveMode() ) - { - emit clicked(); - update(); - } - - //Blocks menu of custom status bar entries - //if (event->button()==RightButton) - // splitFrameMenu(); -} - -void KonqFrameStatusBar::splitFrameMenu() -{ - KonqMainWindow * mw = m_pParentKonqFrame->childView()->mainWindow(); - - // We have to ship the remove view action ourselves, - // since this may not be the active view (passive view) - TDEAction actRemoveView(i18n("Close View"), "view_remove", 0, TQT_TQOBJECT(m_pParentKonqFrame), TQT_SLOT(slotRemoveView()), (TQObject*)0, "removethisview"); - //KonqView * nextView = mw->viewManager()->chooseNextView( m_pParentKonqFrame->childView() ); - actRemoveView.setEnabled( mw->mainViewsCount() > 1 || m_pParentKonqFrame->childView()->isToggleView() || m_pParentKonqFrame->childView()->isPassiveMode() ); - - // For the rest, we borrow them from the main window - // ###### might be not right for passive views ! - TDEActionCollection *actionColl = mw->actionCollection(); - - TQPopupMenu menu; - - actionColl->action( "splitviewh" )->plug( &menu ); - actionColl->action( "splitviewv" )->plug( &menu ); - menu.insertSeparator(); - actionColl->action( "lock" )->plug( &menu ); - - actRemoveView.plug( &menu ); - - menu.exec(TQCursor::pos()); -} - -bool KonqFrameStatusBar::eventFilter(TQObject* o, TQEvent *e) -{ - if (TQT_BASE_OBJECT(o) == TQT_BASE_OBJECT(m_pStatusLabel) && e->type()==TQEvent::MouseButtonPress) - { - emit clicked(); - update(); - if ( TQT_TQMOUSEEVENT(e)->button() == Qt::RightButton) - splitFrameMenu(); - return true; - } - else if ( TQT_BASE_OBJECT(o) == TQT_BASE_OBJECT(this) && e->type() == TQEvent::ApplicationPaletteChange ) - { - unsetPalette(); - updateActiveStatus(); - return true; - } - - return false; -} - -void KonqFrameStatusBar::message( const TQString &msg ) -{ - // We don't use the message()/clear() mechanism of TQStatusBar because - // it really looks ugly (the label border goes away, the active-view indicator - // is hidden...) - TQString saveMsg = m_savedMessage; - slotDisplayStatusText( msg ); - m_savedMessage = saveMsg; -} - -void KonqFrameStatusBar::slotDisplayStatusText(const TQString& text) -{ - //kdDebug(1202)<<"KonqFrameHeader::slotDisplayStatusText("<resize(fontMetrics().width(text),fontMetrics().height()+2); - m_pStatusLabel->setText(text); - m_savedMessage = text; -} - -void KonqFrameStatusBar::slotClear() -{ - slotDisplayStatusText( m_savedMessage ); -} - -void KonqFrameStatusBar::slotLoadingProgress( int percent ) -{ - if ( percent != -1 && percent != 100 ) // hide on 100 too - { - if ( !m_progressBar->isVisible() ) - m_progressBar->show(); - } - else - m_progressBar->hide(); - - m_progressBar->setValue( percent ); -} - -void KonqFrameStatusBar::slotSpeedProgress( int bytesPerSecond ) -{ - TQString sizeStr; - - if ( bytesPerSecond > 0 ) - sizeStr = i18n( "%1/s" ).arg( TDEIO::convertSize( bytesPerSecond ) ); - else - sizeStr = i18n( "Stalled" ); - - slotDisplayStatusText( sizeStr ); // let's share the same label... -} - -void KonqFrameStatusBar::slotConnectToNewView(KonqView *, KParts::ReadOnlyPart *,KParts::ReadOnlyPart *newOne) -{ - if (newOne!=0) - connect(newOne,TQT_SIGNAL(setStatusBarText(const TQString &)),this,TQT_SLOT(slotDisplayStatusText(const TQString&))); - slotDisplayStatusText( TQString::null ); -} - -void KonqFrameStatusBar::showActiveViewIndicator( bool b ) -{ - m_led->setShown( b ); - updateActiveStatus(); -} - -void KonqFrameStatusBar::showLinkedViewIndicator( bool b ) -{ - m_pLinkedViewCheckBox->setShown( b ); -} - -void KonqFrameStatusBar::setLinkedView( bool b ) -{ - m_pLinkedViewCheckBox->blockSignals( true ); - m_pLinkedViewCheckBox->setChecked( b ); - m_pLinkedViewCheckBox->blockSignals( false ); -} - -void KonqFrameStatusBar::updateActiveStatus() -{ - if ( !m_led->isShown() ) - { - unsetPalette(); - return; - } - - bool hasFocus = m_pParentKonqFrame->isActivePart(); - - const TQColorGroup& activeCg = kapp->palette().active(); - setPaletteBackgroundColor( hasFocus ? activeCg.midlight() : activeCg.mid() ); - - static TQPixmap indicator_viewactive( UserIcon( "indicator_viewactive" ) ); - static TQPixmap indicator_empty( UserIcon( "indicator_empty" ) ); - m_led->setPixmap( hasFocus ? indicator_viewactive : indicator_empty ); -} - -//################################################################### - -void KonqFrameBase::printFrameInfo(const TQString& spaces) -{ - kdDebug(1202) << spaces << "KonqFrameBase " << this << " printFrameInfo not implemented in derived class!" << endl; -} - -//################################################################### - -KonqFrame::KonqFrame( TQWidget* parent, KonqFrameContainerBase *parentContainer, const char *name ) -:TQWidget(parent,name) -{ - //kdDebug(1202) << "KonqFrame::KonqFrame()" << endl; - - m_pLayout = 0L; - m_pView = 0L; - - // the frame statusbar - m_pStatusBar = new KonqFrameStatusBar( this, "KonquerorFrameStatusBar"); - m_pStatusBar->setSizePolicy(TQSizePolicy( TQSizePolicy::Expanding, TQSizePolicy::Fixed )); - connect(m_pStatusBar, TQT_SIGNAL(clicked()), this, TQT_SLOT(slotStatusBarClicked())); - connect( m_pStatusBar, TQT_SIGNAL( linkedViewClicked( bool ) ), this, TQT_SLOT( slotLinkedViewClicked( bool ) ) ); - m_separator = 0; - m_pParentContainer = parentContainer; -} - -KonqFrame::~KonqFrame() -{ - //kdDebug(1202) << "KonqFrame::~KonqFrame() " << this << endl; -} - -bool KonqFrame::isActivePart() -{ - return ( m_pView && - static_cast(m_pView) == m_pView->mainWindow()->currentView() ); -} - -void KonqFrame::listViews( ChildViewList *viewList ) -{ - viewList->append( childView() ); -} - -void KonqFrame::saveConfig( TDEConfig* config, const TQString &prefix, bool saveURLs, KonqFrameBase* docContainer, int /*id*/, int /*depth*/ ) -{ - if (saveURLs) - config->writePathEntry( TQString::fromLatin1( "URL" ).prepend( prefix ), - childView()->url().url() ); - config->writeEntry( TQString::fromLatin1( "ServiceType" ).prepend( prefix ), childView()->serviceType() ); - config->writeEntry( TQString::fromLatin1( "ServiceName" ).prepend( prefix ), childView()->service()->desktopEntryName() ); - config->writeEntry( TQString::fromLatin1( "PassiveMode" ).prepend( prefix ), childView()->isPassiveMode() ); - config->writeEntry( TQString::fromLatin1( "LinkedView" ).prepend( prefix ), childView()->isLinkedView() ); - config->writeEntry( TQString::fromLatin1( "ToggleView" ).prepend( prefix ), childView()->isToggleView() ); - config->writeEntry( TQString::fromLatin1( "LockedLocation" ).prepend( prefix ), childView()->isLockedLocation() ); - //config->writeEntry( TQString::fromLatin1( "ShowStatusBar" ).prepend( prefix ), statusbar()->isVisible() ); - if (this == docContainer) config->writeEntry( TQString::fromLatin1( "docContainer" ).prepend( prefix ), true ); - - KonqConfigEvent ev( config, prefix+"_", true/*save*/); - TQApplication::sendEvent( childView()->part(), &ev ); -} - -void KonqFrame::copyHistory( KonqFrameBase *other ) -{ - assert( other->frameType() == "View" ); - childView()->copyHistory( static_cast( other )->childView() ); -} - -void KonqFrame::printFrameInfo( const TQString& spaces ) -{ - TQString className = "NoPart"; - if (part()) className = part()->widget()->className(); - kdDebug(1202) << spaces << "KonqFrame " << this << " visible=" << TQString("%1").arg(isVisible()) << " containing view " - << childView() << " visible=" << TQString("%1").arg(isVisible()) - << " and part " << part() << " whose widget is a " << className << endl; -} - -KParts::ReadOnlyPart *KonqFrame::attach( const KonqViewFactory &viewFactory ) -{ - KonqViewFactory factory( viewFactory ); - - // Note that we set the parent to 0. - // We don't want that deleting the widget deletes the part automatically - // because we already have that taken care of in KParts... - - m_pPart = factory.create( this, "view widget", 0, "" ); - - assert( m_pPart->widget() ); - - attachInternal(); - - m_pStatusBar->slotConnectToNewView(0, 0,m_pPart); - - return m_pPart; -} - -void KonqFrame::attachInternal() -{ - //kdDebug(1202) << "KonqFrame::attachInternal()" << endl; - delete m_pLayout; - - m_pLayout = new TQVBoxLayout( this, 0, -1, "KonqFrame's TQVBoxLayout" ); - - m_pLayout->addWidget( m_pPart->widget(), 1 ); - - m_pLayout->addWidget( m_pStatusBar, 0 ); - m_pPart->widget()->show(); - - m_pLayout->activate(); - - m_pPart->widget()->installEventFilter(this); -} - -bool KonqFrame::eventFilter(TQObject* /*obj*/, TQEvent *ev) -{ - if (ev->type()==TQEvent::KeyPress) - { - TQKeyEvent * keyEv = TQT_TQKEYEVENT(ev); - if ((keyEv->key()==Key_Tab) && (keyEv->state()==ControlButton)) - { - emit ((KonqFrameContainer*)parent())->ctrlTabPressed(); - return true; - } - } - return false; -} - -void KonqFrame::insertTopWidget( TQWidget * widget ) -{ - assert(m_pLayout); - m_pLayout->insertWidget( 0, widget ); - if (widget!=0) - widget->installEventFilter(this); -} - -void KonqFrame::setView( KonqView* child ) -{ - m_pView = child; - if (m_pView) - { - connect(m_pView,TQT_SIGNAL(sigPartChanged(KonqView *, KParts::ReadOnlyPart *,KParts::ReadOnlyPart *)), - m_pStatusBar,TQT_SLOT(slotConnectToNewView(KonqView *, KParts::ReadOnlyPart *,KParts::ReadOnlyPart *))); - } -} - -void KonqFrame::setTitle( const TQString &title , TQWidget* /*sender*/) -{ - //kdDebug(1202) << "KonqFrame::setTitle( " << title << " )" << endl; - m_title = title; - if (m_pParentContainer) m_pParentContainer->setTitle( title , this); -} - -void KonqFrame::setTabIcon( const KURL &url, TQWidget* /*sender*/ ) -{ - //kdDebug(1202) << "KonqFrame::setTabIcon( " << url << " )" << endl; - if (m_pParentContainer) m_pParentContainer->setTabIcon( url, this ); -} - -void KonqFrame::reparentFrame( TQWidget* parent, const TQPoint & p, bool showIt ) -{ - TQWidget::reparent( parent, p, showIt ); -} - -void KonqFrame::slotStatusBarClicked() -{ - if ( !isActivePart() && m_pView && !m_pView->isPassiveMode() ) - m_pView->mainWindow()->viewManager()->setActivePart( part() ); -} - -void KonqFrame::slotLinkedViewClicked( bool mode ) -{ - if ( m_pView->mainWindow()->linkableViewsCount() == 2 ) - m_pView->mainWindow()->slotLinkView(); - else - m_pView->setLinkedView( mode ); -} - -void -KonqFrame::paintEvent( TQPaintEvent* ) -{ -#ifdef USE_QT4 - #warning [INFO] Repaint call disabled in Qt4 to prevent recursive repaint (which otherwise occurs for unknown reasons) -#else // USE_QT4 - m_pStatusBar->repaint(); -#endif // USE_QT4 -} - -void KonqFrame::slotRemoveView() -{ - m_pView->mainWindow()->viewManager()->removeView( m_pView ); -} - -void KonqFrame::activateChild() -{ - if (m_pView && !m_pView->isPassiveMode() ) - m_pView->mainWindow()->viewManager()->setActivePart( part() ); -} - -//################################################################### - -void KonqFrameContainerBase::printFrameInfo(const TQString& spaces) -{ - kdDebug(1202) << spaces << "KonqFrameContainerBase " << this << ", this shouldn't happen!" << endl; -} - -//################################################################### - -KonqFrameContainer::KonqFrameContainer( Orientation o, - TQWidget* parent, - KonqFrameContainerBase* parentContainer, - const char * name) - : TQSplitter( o, parent, name ), m_bAboutToBeDeleted(false) -{ - m_pParentContainer = parentContainer; - m_pFirstChild = 0L; - m_pSecondChild = 0L; - m_pActiveChild = 0L; - setOpaqueResize( TDEGlobalSettings::opaqueResize() ); -} - -KonqFrameContainer::~KonqFrameContainer() -{ - //kdDebug(1202) << "KonqFrameContainer::~KonqFrameContainer() " << this << " - " << className() << endl; - delete m_pFirstChild; - delete m_pSecondChild; -} - -void KonqFrameContainer::listViews( ChildViewList *viewList ) -{ - if( m_pFirstChild ) - m_pFirstChild->listViews( viewList ); - - if( m_pSecondChild ) - m_pSecondChild->listViews( viewList ); -} - -void KonqFrameContainer::saveConfig( TDEConfig* config, const TQString &prefix, bool saveURLs, KonqFrameBase* docContainer, int id, int depth ) -{ - int idSecond = id + (int)pow( 2.0, depth ); - - //write children sizes - config->writeEntry( TQString::fromLatin1( "SplitterSizes" ).prepend( prefix ), sizes() ); - - //write children - TQStringList strlst; - if( firstChild() ) - strlst.append( TQString::fromLatin1( firstChild()->frameType() ) + TQString::number(idSecond - 1) ); - if( secondChild() ) - strlst.append( TQString::fromLatin1( secondChild()->frameType() ) + TQString::number( idSecond ) ); - - config->writeEntry( TQString::fromLatin1( "Children" ).prepend( prefix ), strlst ); - - //write orientation - TQString o; - if( orientation() == Qt::Horizontal ) - o = TQString::fromLatin1("Horizontal"); - else if( orientation() == Qt::Vertical ) - o = TQString::fromLatin1("Vertical"); - config->writeEntry( TQString::fromLatin1( "Orientation" ).prepend( prefix ), o ); - - //write docContainer - if (this == docContainer) config->writeEntry( TQString::fromLatin1( "docContainer" ).prepend( prefix ), true ); - - if (m_pSecondChild == m_pActiveChild) config->writeEntry( TQString::fromLatin1( "activeChildIndex" ).prepend( prefix ), 1 ); - else config->writeEntry( TQString::fromLatin1( "activeChildIndex" ).prepend( prefix ), 0 ); - - //write child configs - if( firstChild() ) { - TQString newPrefix = TQString::fromLatin1( firstChild()->frameType() ) + TQString::number(idSecond - 1); - newPrefix.append( '_' ); - firstChild()->saveConfig( config, newPrefix, saveURLs, docContainer, id, depth + 1 ); - } - - if( secondChild() ) { - TQString newPrefix = TQString::fromLatin1( secondChild()->frameType() ) + TQString::number( idSecond ); - newPrefix.append( '_' ); - secondChild()->saveConfig( config, newPrefix, saveURLs, docContainer, idSecond, depth + 1 ); - } -} - -void KonqFrameContainer::copyHistory( KonqFrameBase *other ) -{ - assert( other->frameType() == "Container" ); - if ( firstChild() ) - firstChild()->copyHistory( static_cast( other )->firstChild() ); - if ( secondChild() ) - secondChild()->copyHistory( static_cast( other )->secondChild() ); -} - -KonqFrameBase* KonqFrameContainer::otherChild( KonqFrameBase* child ) -{ - if( firstChild() == child ) - return secondChild(); - else if( secondChild() == child ) - return firstChild(); - return 0L; -} - -void KonqFrameContainer::printFrameInfo( const TQString& spaces ) -{ - kdDebug(1202) << spaces << "KonqFrameContainer " << this << " visible=" << TQString("%1").arg(isVisible()) - << " activeChild=" << m_pActiveChild << endl; - if (!m_pActiveChild) - kdDebug(1202) << "WARNING: " << this << " has a null active child!" << endl; - KonqFrameBase* child = firstChild(); - if (child != 0L) - child->printFrameInfo(spaces + " "); - else - kdDebug(1202) << spaces << " Null child" << endl; - child = secondChild(); - if (child != 0L) - child->printFrameInfo(spaces + " "); - else - kdDebug(1202) << spaces << " Null child" << endl; -} - -void KonqFrameContainer::reparentFrame( TQWidget* parent, const TQPoint & p, bool showIt ) -{ - TQWidget::reparent( parent, p, showIt ); -} - -void KonqFrameContainer::swapChildren() -{ - KonqFrameBase *firstCh = m_pFirstChild; - m_pFirstChild = m_pSecondChild; - m_pSecondChild = firstCh; -} - -void KonqFrameContainer::setTitle( const TQString &title , TQWidget* sender) -{ - //kdDebug(1202) << "KonqFrameContainer::setTitle( " << title << " , " << sender << " )" << endl; - if (m_pParentContainer && activeChild() && (sender == activeChild()->widget())) - m_pParentContainer->setTitle( title , this); -} - -void KonqFrameContainer::setTabIcon( const KURL &url, TQWidget* sender ) -{ - //kdDebug(1202) << "KonqFrameContainer::setTabIcon( " << url << " , " << sender << " )" << endl; - if (m_pParentContainer && activeChild() && (sender == activeChild()->widget())) - m_pParentContainer->setTabIcon( url, this ); -} - -void KonqFrameContainer::insertChildFrame( KonqFrameBase* frame, int /*index*/ ) -{ - //kdDebug(1202) << "KonqFrameContainer " << this << ": insertChildFrame " << frame << endl; - - if (frame) - { - if( !m_pFirstChild ) - { - m_pFirstChild = frame; - frame->setParentContainer(this); - //kdDebug(1202) << "Setting as first child" << endl; - } - else if( !m_pSecondChild ) - { - m_pSecondChild = frame; - frame->setParentContainer(this); - //kdDebug(1202) << "Setting as second child" << endl; - } - else - kdWarning(1202) << this << " already has two children..." - << m_pFirstChild << " and " << m_pSecondChild << endl; - } else - kdWarning(1202) << "KonqFrameContainer " << this << ": insertChildFrame(0L) !" << endl; -} - -void KonqFrameContainer::removeChildFrame( KonqFrameBase * frame ) -{ - //kdDebug(1202) << "KonqFrameContainer::RemoveChildFrame " << this << ". Child " << frame << " removed" << endl; - - if( m_pFirstChild == frame ) - { - m_pFirstChild = m_pSecondChild; - m_pSecondChild = 0L; - } - else if( m_pSecondChild == frame ) - m_pSecondChild = 0L; - - else - kdWarning(1202) << this << " Can't find this child:" << frame << endl; -} - -void KonqFrameContainer::childEvent( TQChildEvent *c ) -{ - // Child events cause layout changes. These are unnecassery if we are going - // to be deleted anyway. - if (!m_bAboutToBeDeleted) - TQSplitter::childEvent(c); -} - -void KonqFrameContainer::setRubberband( int pos ) -{ - emit setRubberbandCalled(); - TQSplitter::setRubberband( pos ); -} - -#include "konq_frame.moc" diff --git a/konqueror/konq_frame.cpp b/konqueror/konq_frame.cpp new file mode 100644 index 000000000..0acf39b49 --- /dev/null +++ b/konqueror/konq_frame.cpp @@ -0,0 +1,680 @@ +/* This file is part of the KDE project + Copyright (C) 1998, 1999 Michael Reiher + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "konq_events.h" +#include "konq_frame.h" +#include "konq_tabs.h" +#include "konq_view.h" +#include "konq_viewmgr.h" + +#include +#include +#include + + +#define DEFAULT_HEADER_HEIGHT 13 + +void KonqCheckBox::drawButton( TQPainter *p ) +{ + //static TQPixmap indicator_anchor( UserIcon( "indicator_anchor" ) ); + static TQPixmap indicator_connect( UserIcon( "indicator_connect" ) ); + static TQPixmap indicator_noconnect( UserIcon( "indicator_noconnect" ) ); + + if (isOn() || isDown()) + p->drawPixmap(0,0,indicator_connect); + else + p->drawPixmap(0,0,indicator_noconnect); +} + +KonqFrameStatusBar::KonqFrameStatusBar( KonqFrame *_parent, const char *_name ) + : KStatusBar( _parent, _name ), + m_pParentKonqFrame( _parent ) +{ + setSizeGripEnabled( false ); + + m_led = new TQLabel( this ); + m_led->setAlignment( Qt::AlignCenter ); + m_led->setSizePolicy(TQSizePolicy( TQSizePolicy::Fixed, TQSizePolicy::Fixed )); + addWidget( m_led, 0, false ); // led (active view indicator) + m_led->hide(); + + m_pStatusLabel = new KSqueezedTextLabel( this ); + m_pStatusLabel->setMinimumSize( 0, 0 ); + m_pStatusLabel->setSizePolicy(TQSizePolicy( TQSizePolicy::Ignored, TQSizePolicy::Fixed )); + m_pStatusLabel->installEventFilter(this); + addWidget( m_pStatusLabel, 1 /*stretch*/, false ); // status label + + m_pLinkedViewCheckBox = new KonqCheckBox( this, "m_pLinkedViewCheckBox" ); + m_pLinkedViewCheckBox->setFocusPolicy(TQ_NoFocus); + m_pLinkedViewCheckBox->setSizePolicy(TQSizePolicy( TQSizePolicy::Fixed, TQSizePolicy::Fixed )); + TQWhatsThis::add( m_pLinkedViewCheckBox, + i18n("Checking this box on at least two views sets those views as 'linked'. " + "Then, when you change directories in one view, the other views " + "linked with it will automatically update to show the current directory. " + "This is especially useful with different types of views, such as a " + "directory tree with an icon view or detailed view, and possibly a " + "terminal emulator window." ) ); + addWidget( m_pLinkedViewCheckBox, 0, true /*permanent->right align*/ ); + connect( m_pLinkedViewCheckBox, TQT_SIGNAL(toggled(bool)), + this, TQT_SIGNAL(linkedViewClicked(bool)) ); + + m_progressBar = new KProgress( this ); + m_progressBar->setMaximumHeight(fontMetrics().height()); + m_progressBar->hide(); + addWidget( m_progressBar, 0, true /*permanent->right align*/ ); + +// // FIXME: This was added by OpenSUSE; someone needs to figure out what it does and how to fix it! +// StatusBarNetworkStatusIndicator * indicator = new StatusBarNetworkStatusIndicator( this, "networkstatusindicator" ); +// addWidget( indicator, 0, false ); +// indicator->init(); + + fontChange(TQFont()); + installEventFilter( this ); +} + +KonqFrameStatusBar::~KonqFrameStatusBar() +{ +} + +void KonqFrameStatusBar::fontChange(const TQFont & /* oldFont */) +{ + int h = fontMetrics().height(); + if ( h < DEFAULT_HEADER_HEIGHT ) h = DEFAULT_HEADER_HEIGHT; + m_led->setFixedHeight( h + 2 ); + m_progressBar->setFixedHeight( h + 2 ); + // This one is important. Otherwise richtext messages make it grow in height. + m_pStatusLabel->setFixedHeight( h + 2 ); + +} + +void KonqFrameStatusBar::resizeEvent( TQResizeEvent* ev ) +{ + //m_progressBar->setGeometry( width()-160, 0, 140, height() ); + //m_pLinkedViewCheckBox->move( width()-15, m_yOffset ); // right justify + KStatusBar::resizeEvent( ev ); +} + +// I don't think this code _ever_ gets called! +// I don't want to remove it, though. :-) +void KonqFrameStatusBar::mousePressEvent( TQMouseEvent* event ) +{ + TQWidget::mousePressEvent( event ); + if ( !m_pParentKonqFrame->childView()->isPassiveMode() ) + { + emit clicked(); + update(); + } + + //Blocks menu of custom status bar entries + //if (event->button()==RightButton) + // splitFrameMenu(); +} + +void KonqFrameStatusBar::splitFrameMenu() +{ + KonqMainWindow * mw = m_pParentKonqFrame->childView()->mainWindow(); + + // We have to ship the remove view action ourselves, + // since this may not be the active view (passive view) + TDEAction actRemoveView(i18n("Close View"), "view_remove", 0, TQT_TQOBJECT(m_pParentKonqFrame), TQT_SLOT(slotRemoveView()), (TQObject*)0, "removethisview"); + //KonqView * nextView = mw->viewManager()->chooseNextView( m_pParentKonqFrame->childView() ); + actRemoveView.setEnabled( mw->mainViewsCount() > 1 || m_pParentKonqFrame->childView()->isToggleView() || m_pParentKonqFrame->childView()->isPassiveMode() ); + + // For the rest, we borrow them from the main window + // ###### might be not right for passive views ! + TDEActionCollection *actionColl = mw->actionCollection(); + + TQPopupMenu menu; + + actionColl->action( "splitviewh" )->plug( &menu ); + actionColl->action( "splitviewv" )->plug( &menu ); + menu.insertSeparator(); + actionColl->action( "lock" )->plug( &menu ); + + actRemoveView.plug( &menu ); + + menu.exec(TQCursor::pos()); +} + +bool KonqFrameStatusBar::eventFilter(TQObject* o, TQEvent *e) +{ + if (TQT_BASE_OBJECT(o) == TQT_BASE_OBJECT(m_pStatusLabel) && e->type()==TQEvent::MouseButtonPress) + { + emit clicked(); + update(); + if ( TQT_TQMOUSEEVENT(e)->button() == Qt::RightButton) + splitFrameMenu(); + return true; + } + else if ( TQT_BASE_OBJECT(o) == TQT_BASE_OBJECT(this) && e->type() == TQEvent::ApplicationPaletteChange ) + { + unsetPalette(); + updateActiveStatus(); + return true; + } + + return false; +} + +void KonqFrameStatusBar::message( const TQString &msg ) +{ + // We don't use the message()/clear() mechanism of TQStatusBar because + // it really looks ugly (the label border goes away, the active-view indicator + // is hidden...) + TQString saveMsg = m_savedMessage; + slotDisplayStatusText( msg ); + m_savedMessage = saveMsg; +} + +void KonqFrameStatusBar::slotDisplayStatusText(const TQString& text) +{ + //kdDebug(1202)<<"KonqFrameHeader::slotDisplayStatusText("<resize(fontMetrics().width(text),fontMetrics().height()+2); + m_pStatusLabel->setText(text); + m_savedMessage = text; +} + +void KonqFrameStatusBar::slotClear() +{ + slotDisplayStatusText( m_savedMessage ); +} + +void KonqFrameStatusBar::slotLoadingProgress( int percent ) +{ + if ( percent != -1 && percent != 100 ) // hide on 100 too + { + if ( !m_progressBar->isVisible() ) + m_progressBar->show(); + } + else + m_progressBar->hide(); + + m_progressBar->setValue( percent ); +} + +void KonqFrameStatusBar::slotSpeedProgress( int bytesPerSecond ) +{ + TQString sizeStr; + + if ( bytesPerSecond > 0 ) + sizeStr = i18n( "%1/s" ).arg( TDEIO::convertSize( bytesPerSecond ) ); + else + sizeStr = i18n( "Stalled" ); + + slotDisplayStatusText( sizeStr ); // let's share the same label... +} + +void KonqFrameStatusBar::slotConnectToNewView(KonqView *, KParts::ReadOnlyPart *,KParts::ReadOnlyPart *newOne) +{ + if (newOne!=0) + connect(newOne,TQT_SIGNAL(setStatusBarText(const TQString &)),this,TQT_SLOT(slotDisplayStatusText(const TQString&))); + slotDisplayStatusText( TQString::null ); +} + +void KonqFrameStatusBar::showActiveViewIndicator( bool b ) +{ + m_led->setShown( b ); + updateActiveStatus(); +} + +void KonqFrameStatusBar::showLinkedViewIndicator( bool b ) +{ + m_pLinkedViewCheckBox->setShown( b ); +} + +void KonqFrameStatusBar::setLinkedView( bool b ) +{ + m_pLinkedViewCheckBox->blockSignals( true ); + m_pLinkedViewCheckBox->setChecked( b ); + m_pLinkedViewCheckBox->blockSignals( false ); +} + +void KonqFrameStatusBar::updateActiveStatus() +{ + if ( !m_led->isShown() ) + { + unsetPalette(); + return; + } + + bool hasFocus = m_pParentKonqFrame->isActivePart(); + + const TQColorGroup& activeCg = kapp->palette().active(); + setPaletteBackgroundColor( hasFocus ? activeCg.midlight() : activeCg.mid() ); + + static TQPixmap indicator_viewactive( UserIcon( "indicator_viewactive" ) ); + static TQPixmap indicator_empty( UserIcon( "indicator_empty" ) ); + m_led->setPixmap( hasFocus ? indicator_viewactive : indicator_empty ); +} + +//################################################################### + +void KonqFrameBase::printFrameInfo(const TQString& spaces) +{ + kdDebug(1202) << spaces << "KonqFrameBase " << this << " printFrameInfo not implemented in derived class!" << endl; +} + +//################################################################### + +KonqFrame::KonqFrame( TQWidget* parent, KonqFrameContainerBase *parentContainer, const char *name ) +:TQWidget(parent,name) +{ + //kdDebug(1202) << "KonqFrame::KonqFrame()" << endl; + + m_pLayout = 0L; + m_pView = 0L; + + // the frame statusbar + m_pStatusBar = new KonqFrameStatusBar( this, "KonquerorFrameStatusBar"); + m_pStatusBar->setSizePolicy(TQSizePolicy( TQSizePolicy::Expanding, TQSizePolicy::Fixed )); + connect(m_pStatusBar, TQT_SIGNAL(clicked()), this, TQT_SLOT(slotStatusBarClicked())); + connect( m_pStatusBar, TQT_SIGNAL( linkedViewClicked( bool ) ), this, TQT_SLOT( slotLinkedViewClicked( bool ) ) ); + m_separator = 0; + m_pParentContainer = parentContainer; +} + +KonqFrame::~KonqFrame() +{ + //kdDebug(1202) << "KonqFrame::~KonqFrame() " << this << endl; +} + +bool KonqFrame::isActivePart() +{ + return ( m_pView && + static_cast(m_pView) == m_pView->mainWindow()->currentView() ); +} + +void KonqFrame::listViews( ChildViewList *viewList ) +{ + viewList->append( childView() ); +} + +void KonqFrame::saveConfig( TDEConfig* config, const TQString &prefix, bool saveURLs, KonqFrameBase* docContainer, int /*id*/, int /*depth*/ ) +{ + if (saveURLs) + config->writePathEntry( TQString::fromLatin1( "URL" ).prepend( prefix ), + childView()->url().url() ); + config->writeEntry( TQString::fromLatin1( "ServiceType" ).prepend( prefix ), childView()->serviceType() ); + config->writeEntry( TQString::fromLatin1( "ServiceName" ).prepend( prefix ), childView()->service()->desktopEntryName() ); + config->writeEntry( TQString::fromLatin1( "PassiveMode" ).prepend( prefix ), childView()->isPassiveMode() ); + config->writeEntry( TQString::fromLatin1( "LinkedView" ).prepend( prefix ), childView()->isLinkedView() ); + config->writeEntry( TQString::fromLatin1( "ToggleView" ).prepend( prefix ), childView()->isToggleView() ); + config->writeEntry( TQString::fromLatin1( "LockedLocation" ).prepend( prefix ), childView()->isLockedLocation() ); + //config->writeEntry( TQString::fromLatin1( "ShowStatusBar" ).prepend( prefix ), statusbar()->isVisible() ); + if (this == docContainer) config->writeEntry( TQString::fromLatin1( "docContainer" ).prepend( prefix ), true ); + + KonqConfigEvent ev( config, prefix+"_", true/*save*/); + TQApplication::sendEvent( childView()->part(), &ev ); +} + +void KonqFrame::copyHistory( KonqFrameBase *other ) +{ + assert( other->frameType() == "View" ); + childView()->copyHistory( static_cast( other )->childView() ); +} + +void KonqFrame::printFrameInfo( const TQString& spaces ) +{ + TQString className = "NoPart"; + if (part()) className = part()->widget()->className(); + kdDebug(1202) << spaces << "KonqFrame " << this << " visible=" << TQString("%1").arg(isVisible()) << " containing view " + << childView() << " visible=" << TQString("%1").arg(isVisible()) + << " and part " << part() << " whose widget is a " << className << endl; +} + +KParts::ReadOnlyPart *KonqFrame::attach( const KonqViewFactory &viewFactory ) +{ + KonqViewFactory factory( viewFactory ); + + // Note that we set the parent to 0. + // We don't want that deleting the widget deletes the part automatically + // because we already have that taken care of in KParts... + + m_pPart = factory.create( this, "view widget", 0, "" ); + + assert( m_pPart->widget() ); + + attachInternal(); + + m_pStatusBar->slotConnectToNewView(0, 0,m_pPart); + + return m_pPart; +} + +void KonqFrame::attachInternal() +{ + //kdDebug(1202) << "KonqFrame::attachInternal()" << endl; + delete m_pLayout; + + m_pLayout = new TQVBoxLayout( this, 0, -1, "KonqFrame's TQVBoxLayout" ); + + m_pLayout->addWidget( m_pPart->widget(), 1 ); + + m_pLayout->addWidget( m_pStatusBar, 0 ); + m_pPart->widget()->show(); + + m_pLayout->activate(); + + m_pPart->widget()->installEventFilter(this); +} + +bool KonqFrame::eventFilter(TQObject* /*obj*/, TQEvent *ev) +{ + if (ev->type()==TQEvent::KeyPress) + { + TQKeyEvent * keyEv = TQT_TQKEYEVENT(ev); + if ((keyEv->key()==Key_Tab) && (keyEv->state()==ControlButton)) + { + emit ((KonqFrameContainer*)parent())->ctrlTabPressed(); + return true; + } + } + return false; +} + +void KonqFrame::insertTopWidget( TQWidget * widget ) +{ + assert(m_pLayout); + m_pLayout->insertWidget( 0, widget ); + if (widget!=0) + widget->installEventFilter(this); +} + +void KonqFrame::setView( KonqView* child ) +{ + m_pView = child; + if (m_pView) + { + connect(m_pView,TQT_SIGNAL(sigPartChanged(KonqView *, KParts::ReadOnlyPart *,KParts::ReadOnlyPart *)), + m_pStatusBar,TQT_SLOT(slotConnectToNewView(KonqView *, KParts::ReadOnlyPart *,KParts::ReadOnlyPart *))); + } +} + +void KonqFrame::setTitle( const TQString &title , TQWidget* /*sender*/) +{ + //kdDebug(1202) << "KonqFrame::setTitle( " << title << " )" << endl; + m_title = title; + if (m_pParentContainer) m_pParentContainer->setTitle( title , this); +} + +void KonqFrame::setTabIcon( const KURL &url, TQWidget* /*sender*/ ) +{ + //kdDebug(1202) << "KonqFrame::setTabIcon( " << url << " )" << endl; + if (m_pParentContainer) m_pParentContainer->setTabIcon( url, this ); +} + +void KonqFrame::reparentFrame( TQWidget* parent, const TQPoint & p, bool showIt ) +{ + TQWidget::reparent( parent, p, showIt ); +} + +void KonqFrame::slotStatusBarClicked() +{ + if ( !isActivePart() && m_pView && !m_pView->isPassiveMode() ) + m_pView->mainWindow()->viewManager()->setActivePart( part() ); +} + +void KonqFrame::slotLinkedViewClicked( bool mode ) +{ + if ( m_pView->mainWindow()->linkableViewsCount() == 2 ) + m_pView->mainWindow()->slotLinkView(); + else + m_pView->setLinkedView( mode ); +} + +void +KonqFrame::paintEvent( TQPaintEvent* ) +{ +#ifdef USE_QT4 + #warning [INFO] Repaint call disabled in Qt4 to prevent recursive repaint (which otherwise occurs for unknown reasons) +#else // USE_QT4 + m_pStatusBar->repaint(); +#endif // USE_QT4 +} + +void KonqFrame::slotRemoveView() +{ + m_pView->mainWindow()->viewManager()->removeView( m_pView ); +} + +void KonqFrame::activateChild() +{ + if (m_pView && !m_pView->isPassiveMode() ) + m_pView->mainWindow()->viewManager()->setActivePart( part() ); +} + +//################################################################### + +void KonqFrameContainerBase::printFrameInfo(const TQString& spaces) +{ + kdDebug(1202) << spaces << "KonqFrameContainerBase " << this << ", this shouldn't happen!" << endl; +} + +//################################################################### + +KonqFrameContainer::KonqFrameContainer( Orientation o, + TQWidget* parent, + KonqFrameContainerBase* parentContainer, + const char * name) + : TQSplitter( o, parent, name ), m_bAboutToBeDeleted(false) +{ + m_pParentContainer = parentContainer; + m_pFirstChild = 0L; + m_pSecondChild = 0L; + m_pActiveChild = 0L; + setOpaqueResize( TDEGlobalSettings::opaqueResize() ); +} + +KonqFrameContainer::~KonqFrameContainer() +{ + //kdDebug(1202) << "KonqFrameContainer::~KonqFrameContainer() " << this << " - " << className() << endl; + delete m_pFirstChild; + delete m_pSecondChild; +} + +void KonqFrameContainer::listViews( ChildViewList *viewList ) +{ + if( m_pFirstChild ) + m_pFirstChild->listViews( viewList ); + + if( m_pSecondChild ) + m_pSecondChild->listViews( viewList ); +} + +void KonqFrameContainer::saveConfig( TDEConfig* config, const TQString &prefix, bool saveURLs, KonqFrameBase* docContainer, int id, int depth ) +{ + int idSecond = id + (int)pow( 2.0, depth ); + + //write children sizes + config->writeEntry( TQString::fromLatin1( "SplitterSizes" ).prepend( prefix ), sizes() ); + + //write children + TQStringList strlst; + if( firstChild() ) + strlst.append( TQString::fromLatin1( firstChild()->frameType() ) + TQString::number(idSecond - 1) ); + if( secondChild() ) + strlst.append( TQString::fromLatin1( secondChild()->frameType() ) + TQString::number( idSecond ) ); + + config->writeEntry( TQString::fromLatin1( "Children" ).prepend( prefix ), strlst ); + + //write orientation + TQString o; + if( orientation() == Qt::Horizontal ) + o = TQString::fromLatin1("Horizontal"); + else if( orientation() == Qt::Vertical ) + o = TQString::fromLatin1("Vertical"); + config->writeEntry( TQString::fromLatin1( "Orientation" ).prepend( prefix ), o ); + + //write docContainer + if (this == docContainer) config->writeEntry( TQString::fromLatin1( "docContainer" ).prepend( prefix ), true ); + + if (m_pSecondChild == m_pActiveChild) config->writeEntry( TQString::fromLatin1( "activeChildIndex" ).prepend( prefix ), 1 ); + else config->writeEntry( TQString::fromLatin1( "activeChildIndex" ).prepend( prefix ), 0 ); + + //write child configs + if( firstChild() ) { + TQString newPrefix = TQString::fromLatin1( firstChild()->frameType() ) + TQString::number(idSecond - 1); + newPrefix.append( '_' ); + firstChild()->saveConfig( config, newPrefix, saveURLs, docContainer, id, depth + 1 ); + } + + if( secondChild() ) { + TQString newPrefix = TQString::fromLatin1( secondChild()->frameType() ) + TQString::number( idSecond ); + newPrefix.append( '_' ); + secondChild()->saveConfig( config, newPrefix, saveURLs, docContainer, idSecond, depth + 1 ); + } +} + +void KonqFrameContainer::copyHistory( KonqFrameBase *other ) +{ + assert( other->frameType() == "Container" ); + if ( firstChild() ) + firstChild()->copyHistory( static_cast( other )->firstChild() ); + if ( secondChild() ) + secondChild()->copyHistory( static_cast( other )->secondChild() ); +} + +KonqFrameBase* KonqFrameContainer::otherChild( KonqFrameBase* child ) +{ + if( firstChild() == child ) + return secondChild(); + else if( secondChild() == child ) + return firstChild(); + return 0L; +} + +void KonqFrameContainer::printFrameInfo( const TQString& spaces ) +{ + kdDebug(1202) << spaces << "KonqFrameContainer " << this << " visible=" << TQString("%1").arg(isVisible()) + << " activeChild=" << m_pActiveChild << endl; + if (!m_pActiveChild) + kdDebug(1202) << "WARNING: " << this << " has a null active child!" << endl; + KonqFrameBase* child = firstChild(); + if (child != 0L) + child->printFrameInfo(spaces + " "); + else + kdDebug(1202) << spaces << " Null child" << endl; + child = secondChild(); + if (child != 0L) + child->printFrameInfo(spaces + " "); + else + kdDebug(1202) << spaces << " Null child" << endl; +} + +void KonqFrameContainer::reparentFrame( TQWidget* parent, const TQPoint & p, bool showIt ) +{ + TQWidget::reparent( parent, p, showIt ); +} + +void KonqFrameContainer::swapChildren() +{ + KonqFrameBase *firstCh = m_pFirstChild; + m_pFirstChild = m_pSecondChild; + m_pSecondChild = firstCh; +} + +void KonqFrameContainer::setTitle( const TQString &title , TQWidget* sender) +{ + //kdDebug(1202) << "KonqFrameContainer::setTitle( " << title << " , " << sender << " )" << endl; + if (m_pParentContainer && activeChild() && (sender == activeChild()->widget())) + m_pParentContainer->setTitle( title , this); +} + +void KonqFrameContainer::setTabIcon( const KURL &url, TQWidget* sender ) +{ + //kdDebug(1202) << "KonqFrameContainer::setTabIcon( " << url << " , " << sender << " )" << endl; + if (m_pParentContainer && activeChild() && (sender == activeChild()->widget())) + m_pParentContainer->setTabIcon( url, this ); +} + +void KonqFrameContainer::insertChildFrame( KonqFrameBase* frame, int /*index*/ ) +{ + //kdDebug(1202) << "KonqFrameContainer " << this << ": insertChildFrame " << frame << endl; + + if (frame) + { + if( !m_pFirstChild ) + { + m_pFirstChild = frame; + frame->setParentContainer(this); + //kdDebug(1202) << "Setting as first child" << endl; + } + else if( !m_pSecondChild ) + { + m_pSecondChild = frame; + frame->setParentContainer(this); + //kdDebug(1202) << "Setting as second child" << endl; + } + else + kdWarning(1202) << this << " already has two children..." + << m_pFirstChild << " and " << m_pSecondChild << endl; + } else + kdWarning(1202) << "KonqFrameContainer " << this << ": insertChildFrame(0L) !" << endl; +} + +void KonqFrameContainer::removeChildFrame( KonqFrameBase * frame ) +{ + //kdDebug(1202) << "KonqFrameContainer::RemoveChildFrame " << this << ". Child " << frame << " removed" << endl; + + if( m_pFirstChild == frame ) + { + m_pFirstChild = m_pSecondChild; + m_pSecondChild = 0L; + } + else if( m_pSecondChild == frame ) + m_pSecondChild = 0L; + + else + kdWarning(1202) << this << " Can't find this child:" << frame << endl; +} + +void KonqFrameContainer::childEvent( TQChildEvent *c ) +{ + // Child events cause layout changes. These are unnecassery if we are going + // to be deleted anyway. + if (!m_bAboutToBeDeleted) + TQSplitter::childEvent(c); +} + +void KonqFrameContainer::setRubberband( int pos ) +{ + emit setRubberbandCalled(); + TQSplitter::setRubberband( pos ); +} + +#include "konq_frame.moc" diff --git a/konqueror/konq_guiclients.cc b/konqueror/konq_guiclients.cc deleted file mode 100644 index 31647b0c3..000000000 --- a/konqueror/konq_guiclients.cc +++ /dev/null @@ -1,363 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 1998, 1999 Simon Hausmann - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include -#include -#include -#include "konq_view.h" -#include "konq_settingsxt.h" -#include "konq_frame.h" -#include "konq_guiclients.h" -#include "konq_viewmgr.h" -#include - -PopupMenuGUIClient::PopupMenuGUIClient( KonqMainWindow *mainWindow, - const TDETrader::OfferList &embeddingServices, - bool showEmbeddingServices, bool doTabHandling ) -{ - //giving a name to each guiclient: just for debugging - // (needs delete instance() in the dtor if enabled for good) - //setInstance( new TDEInstance( "PopupMenuGUIClient" ) ); - - m_mainWindow = mainWindow; - - m_doc = TQDomDocument( "kpartgui" ); - TQDomElement root = m_doc.createElement( "kpartgui" ); - root.setAttribute( "name", "konqueror" ); - m_doc.appendChild( root ); - - TQDomElement menu = m_doc.createElement( "Menu" ); - root.appendChild( menu ); - menu.setAttribute( "name", "popupmenu" ); - - if ( !mainWindow->menuBar()->isVisible() ) - { - TQDomElement showMenuBarElement = m_doc.createElement( "action" ); - showMenuBarElement.setAttribute( "name", "options_show_menubar" ); - menu.appendChild( showMenuBarElement ); - - menu.appendChild( m_doc.createElement( "separator" ) ); - } - - if ( mainWindow->fullScreenMode() ) - { - TQDomElement stopFullScreenElement = m_doc.createElement( "action" ); - stopFullScreenElement.setAttribute( "name", "fullscreen" ); - menu.appendChild( stopFullScreenElement ); - - menu.appendChild( m_doc.createElement( "separator" ) ); - } - - if ( showEmbeddingServices ) - { - TDETrader::OfferList::ConstIterator it = embeddingServices.begin(); - TDETrader::OfferList::ConstIterator end = embeddingServices.end(); - - if ( embeddingServices.count() == 1 ) - { - KService::Ptr service = *embeddingServices.begin(); - addEmbeddingService( menu, 0, i18n( "Preview in %1" ).arg( service->name() ), service ); - } - else if ( embeddingServices.count() > 1 ) - { - int idx = 0; - TQDomElement subMenu = m_doc.createElement( "menu" ); - menu.appendChild( subMenu ); - TQDomElement text = m_doc.createElement( "text" ); - subMenu.appendChild( text ); - text.appendChild( m_doc.createTextNode( i18n( "Preview In" ) ) ); - subMenu.setAttribute( "group", "preview" ); - subMenu.setAttribute( "name", "preview submenu" ); - - bool inserted = false; - - for (; it != end; ++it, ++idx ) - { - addEmbeddingService( subMenu, idx, (*it)->name(), *it ); - inserted = true; - } - - if ( !inserted ) // oops, if empty then remove the menu :-] - menu.removeChild( menu.namedItem( "menu" ) ); - } - } - - if ( doTabHandling ) - { - TQDomElement openInSameWindow = m_doc.createElement( "action" ); - openInSameWindow.setAttribute( "name", "sameview" ); - openInSameWindow.setAttribute( "group", "tabhandling" ); - menu.appendChild( openInSameWindow ); - - TQDomElement openInWindow = m_doc.createElement( "action" ); - openInWindow.setAttribute( "name", "newview" ); - openInWindow.setAttribute( "group", "tabhandling" ); - menu.appendChild( openInWindow ); - - TQDomElement openInTabElement = m_doc.createElement( "action" ); - openInTabElement.setAttribute( "name", "openintab" ); - openInTabElement.setAttribute( "group", "tabhandling" ); - menu.appendChild( openInTabElement ); - - TQDomElement openInTabFrontElement = m_doc.createElement( "action" ); - openInTabFrontElement.setAttribute( "name", "openintabfront" ); - openInTabFrontElement.setAttribute( "group", "tabhandling" ); - menu.appendChild( openInTabFrontElement ); - - TQDomElement separatorElement = m_doc.createElement( "separator" ); - separatorElement.setAttribute( "group", "tabhandling" ); - menu.appendChild( separatorElement ); - } - - //kdDebug() << k_funcinfo << m_doc.toString() << endl; - - setDOMDocument( m_doc ); -} - -PopupMenuGUIClient::~PopupMenuGUIClient() -{ -} - -TDEAction *PopupMenuGUIClient::action( const TQDomElement &element ) const -{ - TDEAction *res = KXMLGUIClient::action( element ); - - if ( !res ) - res = m_mainWindow->action( element ); - - return res; -} - -void PopupMenuGUIClient::addEmbeddingService( TQDomElement &menu, int idx, const TQString &name, const KService::Ptr &service ) -{ - TQDomElement action = m_doc.createElement( "action" ); - menu.appendChild( action ); - - TQCString actName; - actName.setNum( idx ); - - action.setAttribute( "name", TQString::number( idx ) ); - - action.setAttribute( "group", "preview" ); - - (void)new TDEAction( name, service->pixmap( TDEIcon::Small ), 0, - TQT_TQOBJECT(m_mainWindow), TQT_SLOT( slotOpenEmbedded() ), actionCollection(), actName ); -} - -ToggleViewGUIClient::ToggleViewGUIClient( KonqMainWindow *mainWindow ) -: TQObject( mainWindow ) -{ - m_mainWindow = mainWindow; - m_actions.setAutoDelete( true ); - - TDETrader::OfferList offers = TDETrader::self()->query( "Browser/View" ); - TDETrader::OfferList::Iterator it = offers.begin(); - while ( it != offers.end() ) - { - TQVariant prop = (*it)->property( "X-TDE-BrowserView-Toggable" ); - TQVariant orientation = (*it)->property( "X-TDE-BrowserView-ToggableView-Orientation" ); - - if ( !prop.isValid() || !prop.toBool() || - !orientation.isValid() || orientation.toString().isEmpty() ) - { - offers.remove( it ); - it = offers.begin(); - } - else - ++it; - } - - m_empty = ( offers.count() == 0 ); - - if ( m_empty ) - return; - - TDETrader::OfferList::ConstIterator cIt = offers.begin(); - TDETrader::OfferList::ConstIterator cEnd = offers.end(); - for (; cIt != cEnd; ++cIt ) - { - TQString description = i18n( "Show %1" ).arg( (*cIt)->name() ); - TQString name = (*cIt)->desktopEntryName(); - //kdDebug(1202) << "ToggleViewGUIClient: name=" << name << endl; - TDEToggleAction *action = new TDEToggleAction( description, 0, mainWindow->actionCollection(), name.latin1() ); - action->setCheckedState( i18n( "Hide %1" ).arg( (*cIt)->name() ) ); - - // HACK - if ( (*cIt)->icon() != "unknown" ) - action->setIcon( (*cIt)->icon() ); - - connect( action, TQT_SIGNAL( toggled( bool ) ), - this, TQT_SLOT( slotToggleView( bool ) ) ); - - m_actions.insert( name, action ); - - TQVariant orientation = (*cIt)->property( "X-TDE-BrowserView-ToggableView-Orientation" ); - bool horizontal = orientation.toString().lower() == "horizontal"; - m_mapOrientation.insert( name, horizontal ); - } - - connect( m_mainWindow, TQT_SIGNAL( viewAdded( KonqView * ) ), - this, TQT_SLOT( slotViewAdded( KonqView * ) ) ); - connect( m_mainWindow, TQT_SIGNAL( viewRemoved( KonqView * ) ), - this, TQT_SLOT( slotViewRemoved( KonqView * ) ) ); -} - -ToggleViewGUIClient::~ToggleViewGUIClient() -{ -} - -TQPtrList ToggleViewGUIClient::actions() const -{ - TQPtrList res; - - TQDictIterator it( m_actions ); - for (; it.current(); ++it ) - res.append( it.current() ); - - return res; -} - -void ToggleViewGUIClient::slotToggleView( bool toggle ) -{ - TQString serviceName = TQString::fromLatin1( TQT_TQOBJECT_CONST(sender())->name() ); - - bool horizontal = m_mapOrientation[ serviceName ]; - - KonqViewManager *viewManager = m_mainWindow->viewManager(); - - if ( toggle ) - { - - KonqView *childView = viewManager->splitWindow( horizontal ? Qt::Vertical : Qt::Horizontal, - TQString::fromLatin1( "Browser/View" ), - serviceName, - !horizontal /* vertical = make it first */); - - TQValueList newSplitterSizes; - - if ( horizontal ) - newSplitterSizes << 100 << 30; - else - newSplitterSizes << 30 << 100; - - if (!childView || !childView->frame()) - return; - - // Toggleviews don't need their statusbar - childView->frame()->statusbar()->hide(); - - KonqFrameContainerBase *newContainer = childView->frame()->parentContainer(); - - if (newContainer->frameType()=="Container") - static_cast(newContainer)->setSizes( newSplitterSizes ); - -#if 0 // already done by splitWindow - if ( m_mainWindow->currentView() ) - { - TQString locBarURL = m_mainWindow->currentView()->url().prettyURL(); // default one in case it doesn't set it - childView->openURL( m_mainWindow->currentView()->url(), locBarURL ); - } -#endif - - // If not passive, set as active :) - if (!childView->isPassiveMode()) - viewManager->setActivePart( childView->part() ); - - kdDebug() << "ToggleViewGUIClient::slotToggleView setToggleView(true) on " << childView << endl; - childView->setToggleView( true ); - - m_mainWindow->viewCountChanged(); - - } - else - { - TQPtrList viewList; - - m_mainWindow->listViews( &viewList ); - - TQPtrListIterator it( viewList ); - for (; it.current(); ++it ) - if ( it.current()->service()->desktopEntryName() == serviceName ) - // takes care of choosing the new active view, and also calls slotViewRemoved - viewManager->removeView( it.current() ); - } - -} - - -void ToggleViewGUIClient::saveConfig( bool add, const TQString &serviceName ) -{ - // This is used on konqueror's startup....... so it's never used, since - // the TDE menu only contains calls to kfmclient...... - // Well, it could be useful again in the future. - // Currently, the profiles save this info. - TQStringList toggableViewsShown = KonqSettings::toggableViewsShown(); - if (add) - { - if ( !toggableViewsShown.contains( serviceName ) ) - toggableViewsShown.append(serviceName); - } - else - toggableViewsShown.remove(serviceName); - KonqSettings::setToggableViewsShown( toggableViewsShown ); -} - -void ToggleViewGUIClient::slotViewAdded( KonqView *view ) -{ - TQString name = view->service()->desktopEntryName(); - - TDEAction *action = m_actions[ name ]; - - if ( action ) - { - static_cast( action )->setChecked( true ); - saveConfig( true, name ); - - // KonqView::isToggleView() is not set yet.. so just check for the orientation - -#if 0 - TQVariant vert = view->service()->property( "X-TDE-BrowserView-ToggableView-Orientation"); - bool vertical = vert.toString().lower() == "vertical"; - TQVariant nohead = view->service()->property( "X-TDE-BrowserView-ToggableView-NoHeader"); - bool noheader = nohead.isValid() ? nohead.toBool() : false; - // if it is a vertical toggle part, turn on the header. - // this works even when konq loads the view from a profile. - if ( vertical && (!noheader)) - { - view->frame()->header()->setText(view->service()->name()); - view->frame()->header()->setAction(action); - } -#endif - } -} - -void ToggleViewGUIClient::slotViewRemoved( KonqView *view ) -{ - TQString name = view->service()->desktopEntryName(); - - TDEAction *action = m_actions[ name ]; - - if ( action ) - { - static_cast( action )->setChecked( false ); - saveConfig( false, name ); - } -} - -#include "konq_guiclients.moc" diff --git a/konqueror/konq_guiclients.cpp b/konqueror/konq_guiclients.cpp new file mode 100644 index 000000000..31647b0c3 --- /dev/null +++ b/konqueror/konq_guiclients.cpp @@ -0,0 +1,363 @@ +/* This file is part of the KDE project + Copyright (C) 1998, 1999 Simon Hausmann + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include +#include +#include +#include "konq_view.h" +#include "konq_settingsxt.h" +#include "konq_frame.h" +#include "konq_guiclients.h" +#include "konq_viewmgr.h" +#include + +PopupMenuGUIClient::PopupMenuGUIClient( KonqMainWindow *mainWindow, + const TDETrader::OfferList &embeddingServices, + bool showEmbeddingServices, bool doTabHandling ) +{ + //giving a name to each guiclient: just for debugging + // (needs delete instance() in the dtor if enabled for good) + //setInstance( new TDEInstance( "PopupMenuGUIClient" ) ); + + m_mainWindow = mainWindow; + + m_doc = TQDomDocument( "kpartgui" ); + TQDomElement root = m_doc.createElement( "kpartgui" ); + root.setAttribute( "name", "konqueror" ); + m_doc.appendChild( root ); + + TQDomElement menu = m_doc.createElement( "Menu" ); + root.appendChild( menu ); + menu.setAttribute( "name", "popupmenu" ); + + if ( !mainWindow->menuBar()->isVisible() ) + { + TQDomElement showMenuBarElement = m_doc.createElement( "action" ); + showMenuBarElement.setAttribute( "name", "options_show_menubar" ); + menu.appendChild( showMenuBarElement ); + + menu.appendChild( m_doc.createElement( "separator" ) ); + } + + if ( mainWindow->fullScreenMode() ) + { + TQDomElement stopFullScreenElement = m_doc.createElement( "action" ); + stopFullScreenElement.setAttribute( "name", "fullscreen" ); + menu.appendChild( stopFullScreenElement ); + + menu.appendChild( m_doc.createElement( "separator" ) ); + } + + if ( showEmbeddingServices ) + { + TDETrader::OfferList::ConstIterator it = embeddingServices.begin(); + TDETrader::OfferList::ConstIterator end = embeddingServices.end(); + + if ( embeddingServices.count() == 1 ) + { + KService::Ptr service = *embeddingServices.begin(); + addEmbeddingService( menu, 0, i18n( "Preview in %1" ).arg( service->name() ), service ); + } + else if ( embeddingServices.count() > 1 ) + { + int idx = 0; + TQDomElement subMenu = m_doc.createElement( "menu" ); + menu.appendChild( subMenu ); + TQDomElement text = m_doc.createElement( "text" ); + subMenu.appendChild( text ); + text.appendChild( m_doc.createTextNode( i18n( "Preview In" ) ) ); + subMenu.setAttribute( "group", "preview" ); + subMenu.setAttribute( "name", "preview submenu" ); + + bool inserted = false; + + for (; it != end; ++it, ++idx ) + { + addEmbeddingService( subMenu, idx, (*it)->name(), *it ); + inserted = true; + } + + if ( !inserted ) // oops, if empty then remove the menu :-] + menu.removeChild( menu.namedItem( "menu" ) ); + } + } + + if ( doTabHandling ) + { + TQDomElement openInSameWindow = m_doc.createElement( "action" ); + openInSameWindow.setAttribute( "name", "sameview" ); + openInSameWindow.setAttribute( "group", "tabhandling" ); + menu.appendChild( openInSameWindow ); + + TQDomElement openInWindow = m_doc.createElement( "action" ); + openInWindow.setAttribute( "name", "newview" ); + openInWindow.setAttribute( "group", "tabhandling" ); + menu.appendChild( openInWindow ); + + TQDomElement openInTabElement = m_doc.createElement( "action" ); + openInTabElement.setAttribute( "name", "openintab" ); + openInTabElement.setAttribute( "group", "tabhandling" ); + menu.appendChild( openInTabElement ); + + TQDomElement openInTabFrontElement = m_doc.createElement( "action" ); + openInTabFrontElement.setAttribute( "name", "openintabfront" ); + openInTabFrontElement.setAttribute( "group", "tabhandling" ); + menu.appendChild( openInTabFrontElement ); + + TQDomElement separatorElement = m_doc.createElement( "separator" ); + separatorElement.setAttribute( "group", "tabhandling" ); + menu.appendChild( separatorElement ); + } + + //kdDebug() << k_funcinfo << m_doc.toString() << endl; + + setDOMDocument( m_doc ); +} + +PopupMenuGUIClient::~PopupMenuGUIClient() +{ +} + +TDEAction *PopupMenuGUIClient::action( const TQDomElement &element ) const +{ + TDEAction *res = KXMLGUIClient::action( element ); + + if ( !res ) + res = m_mainWindow->action( element ); + + return res; +} + +void PopupMenuGUIClient::addEmbeddingService( TQDomElement &menu, int idx, const TQString &name, const KService::Ptr &service ) +{ + TQDomElement action = m_doc.createElement( "action" ); + menu.appendChild( action ); + + TQCString actName; + actName.setNum( idx ); + + action.setAttribute( "name", TQString::number( idx ) ); + + action.setAttribute( "group", "preview" ); + + (void)new TDEAction( name, service->pixmap( TDEIcon::Small ), 0, + TQT_TQOBJECT(m_mainWindow), TQT_SLOT( slotOpenEmbedded() ), actionCollection(), actName ); +} + +ToggleViewGUIClient::ToggleViewGUIClient( KonqMainWindow *mainWindow ) +: TQObject( mainWindow ) +{ + m_mainWindow = mainWindow; + m_actions.setAutoDelete( true ); + + TDETrader::OfferList offers = TDETrader::self()->query( "Browser/View" ); + TDETrader::OfferList::Iterator it = offers.begin(); + while ( it != offers.end() ) + { + TQVariant prop = (*it)->property( "X-TDE-BrowserView-Toggable" ); + TQVariant orientation = (*it)->property( "X-TDE-BrowserView-ToggableView-Orientation" ); + + if ( !prop.isValid() || !prop.toBool() || + !orientation.isValid() || orientation.toString().isEmpty() ) + { + offers.remove( it ); + it = offers.begin(); + } + else + ++it; + } + + m_empty = ( offers.count() == 0 ); + + if ( m_empty ) + return; + + TDETrader::OfferList::ConstIterator cIt = offers.begin(); + TDETrader::OfferList::ConstIterator cEnd = offers.end(); + for (; cIt != cEnd; ++cIt ) + { + TQString description = i18n( "Show %1" ).arg( (*cIt)->name() ); + TQString name = (*cIt)->desktopEntryName(); + //kdDebug(1202) << "ToggleViewGUIClient: name=" << name << endl; + TDEToggleAction *action = new TDEToggleAction( description, 0, mainWindow->actionCollection(), name.latin1() ); + action->setCheckedState( i18n( "Hide %1" ).arg( (*cIt)->name() ) ); + + // HACK + if ( (*cIt)->icon() != "unknown" ) + action->setIcon( (*cIt)->icon() ); + + connect( action, TQT_SIGNAL( toggled( bool ) ), + this, TQT_SLOT( slotToggleView( bool ) ) ); + + m_actions.insert( name, action ); + + TQVariant orientation = (*cIt)->property( "X-TDE-BrowserView-ToggableView-Orientation" ); + bool horizontal = orientation.toString().lower() == "horizontal"; + m_mapOrientation.insert( name, horizontal ); + } + + connect( m_mainWindow, TQT_SIGNAL( viewAdded( KonqView * ) ), + this, TQT_SLOT( slotViewAdded( KonqView * ) ) ); + connect( m_mainWindow, TQT_SIGNAL( viewRemoved( KonqView * ) ), + this, TQT_SLOT( slotViewRemoved( KonqView * ) ) ); +} + +ToggleViewGUIClient::~ToggleViewGUIClient() +{ +} + +TQPtrList ToggleViewGUIClient::actions() const +{ + TQPtrList res; + + TQDictIterator it( m_actions ); + for (; it.current(); ++it ) + res.append( it.current() ); + + return res; +} + +void ToggleViewGUIClient::slotToggleView( bool toggle ) +{ + TQString serviceName = TQString::fromLatin1( TQT_TQOBJECT_CONST(sender())->name() ); + + bool horizontal = m_mapOrientation[ serviceName ]; + + KonqViewManager *viewManager = m_mainWindow->viewManager(); + + if ( toggle ) + { + + KonqView *childView = viewManager->splitWindow( horizontal ? Qt::Vertical : Qt::Horizontal, + TQString::fromLatin1( "Browser/View" ), + serviceName, + !horizontal /* vertical = make it first */); + + TQValueList newSplitterSizes; + + if ( horizontal ) + newSplitterSizes << 100 << 30; + else + newSplitterSizes << 30 << 100; + + if (!childView || !childView->frame()) + return; + + // Toggleviews don't need their statusbar + childView->frame()->statusbar()->hide(); + + KonqFrameContainerBase *newContainer = childView->frame()->parentContainer(); + + if (newContainer->frameType()=="Container") + static_cast(newContainer)->setSizes( newSplitterSizes ); + +#if 0 // already done by splitWindow + if ( m_mainWindow->currentView() ) + { + TQString locBarURL = m_mainWindow->currentView()->url().prettyURL(); // default one in case it doesn't set it + childView->openURL( m_mainWindow->currentView()->url(), locBarURL ); + } +#endif + + // If not passive, set as active :) + if (!childView->isPassiveMode()) + viewManager->setActivePart( childView->part() ); + + kdDebug() << "ToggleViewGUIClient::slotToggleView setToggleView(true) on " << childView << endl; + childView->setToggleView( true ); + + m_mainWindow->viewCountChanged(); + + } + else + { + TQPtrList viewList; + + m_mainWindow->listViews( &viewList ); + + TQPtrListIterator it( viewList ); + for (; it.current(); ++it ) + if ( it.current()->service()->desktopEntryName() == serviceName ) + // takes care of choosing the new active view, and also calls slotViewRemoved + viewManager->removeView( it.current() ); + } + +} + + +void ToggleViewGUIClient::saveConfig( bool add, const TQString &serviceName ) +{ + // This is used on konqueror's startup....... so it's never used, since + // the TDE menu only contains calls to kfmclient...... + // Well, it could be useful again in the future. + // Currently, the profiles save this info. + TQStringList toggableViewsShown = KonqSettings::toggableViewsShown(); + if (add) + { + if ( !toggableViewsShown.contains( serviceName ) ) + toggableViewsShown.append(serviceName); + } + else + toggableViewsShown.remove(serviceName); + KonqSettings::setToggableViewsShown( toggableViewsShown ); +} + +void ToggleViewGUIClient::slotViewAdded( KonqView *view ) +{ + TQString name = view->service()->desktopEntryName(); + + TDEAction *action = m_actions[ name ]; + + if ( action ) + { + static_cast( action )->setChecked( true ); + saveConfig( true, name ); + + // KonqView::isToggleView() is not set yet.. so just check for the orientation + +#if 0 + TQVariant vert = view->service()->property( "X-TDE-BrowserView-ToggableView-Orientation"); + bool vertical = vert.toString().lower() == "vertical"; + TQVariant nohead = view->service()->property( "X-TDE-BrowserView-ToggableView-NoHeader"); + bool noheader = nohead.isValid() ? nohead.toBool() : false; + // if it is a vertical toggle part, turn on the header. + // this works even when konq loads the view from a profile. + if ( vertical && (!noheader)) + { + view->frame()->header()->setText(view->service()->name()); + view->frame()->header()->setAction(action); + } +#endif + } +} + +void ToggleViewGUIClient::slotViewRemoved( KonqView *view ) +{ + TQString name = view->service()->desktopEntryName(); + + TDEAction *action = m_actions[ name ]; + + if ( action ) + { + static_cast( action )->setChecked( false ); + saveConfig( false, name ); + } +} + +#include "konq_guiclients.moc" diff --git a/konqueror/konq_main.cc b/konqueror/konq_main.cc deleted file mode 100644 index ee1fc71db..000000000 --- a/konqueror/konq_main.cc +++ /dev/null @@ -1,222 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 1998, 1999 Simon Hausmann - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "konq_main.h" -#include "konq_misc.h" -#include "konq_factory.h" -#include "konq_mainwindow.h" -#include "konq_view.h" -#include "konq_settingsxt.h" -#include "KonquerorIface.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -static const TDECmdLineOptions options[] = -{ - { "silent", I18N_NOOP("Start without a default window"), 0 }, - { "preload", I18N_NOOP("Preload for later use"), 0 }, - { "profile ", I18N_NOOP("Profile to open"), 0 }, - { "profiles", I18N_NOOP("List available profiles"), 0 }, - { "mimetype ", I18N_NOOP("Mimetype to use for this URL (e.g. text/html or inode/directory)"), 0 }, - { "select", I18N_NOOP("For URLs that point to files, opens the directory and selects the file, instead of opening the actual file"), 0 }, - { "+[URL]", I18N_NOOP("Location to open"), 0 }, - TDECmdLineLastOption -}; - -extern "C" KDE_EXPORT int kdemain( int argc, char **argv ) -{ - TDECmdLineArgs::init( argc, argv, KonqFactory::aboutData() ); - - TDECmdLineArgs::addCmdLineOptions( options ); // Add our own options. - TDECmdLineArgs::addTempFileOption(); - - KonquerorApplication app; - - app.dcopClient()->registerAs( "konqueror" ); - - KonquerorIface *kiface = new KonquerorIface; - app.dcopClient()->setDefaultObject( kiface->objId() ); - - TDEGlobal::locale()->insertCatalogue("libkonq"); // needed for apps using libkonq - KImageIO::registerFormats(); - - TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs(); - - KTempFile crashlog_file(locateLocal("tmp", "konqueror-crash-"), ".log"); - KonqMainWindow::s_crashlog_file = crashlog_file.file(); - - if ( kapp->isRestored() ) - { - int n = 1; - while ( KonqMainWindow::canBeRestored( n ) ) - { - TQString className = TDEMainWindow::classNameOfToplevel( n ); - if( className == TQString::fromLatin1( "KonqMainWindow" )) - (new KonqMainWindow( KURL(), false ) )->restore( n ); - else - kdWarning() << "Unknown class " << className << " in session saved data!" << endl; - n++; - } - } - else - { - if (args->isSet("profiles")) - { - TQStringList profiles = TDEGlobal::dirs()->findAllResources("data", "konqueror/profiles/*", false, true); - profiles.sort(); - for(TQStringList::ConstIterator it = profiles.begin(); - it != profiles.end(); ++it) - { - TQString file = *it; - file = file.mid(file.findRev('/')+1); - printf("%s\n", TQFile::encodeName(file).data()); - } - - return 0; - } - if (args->isSet("profile")) - { - TQString profile = TQString::fromLocal8Bit(args->getOption("profile")); - TQString profilePath = profile; - if (profile[0] != '/') - profilePath = locate( "data", TQString::fromLatin1("konqueror/profiles/")+profile ); - TQString url; - TQStringList filesToSelect; - if (args->count() == 1) - url = TQString::fromLocal8Bit(args->arg(0)); - KURL kurl(url); - KParts::URLArgs urlargs; - if (args->isSet("mimetype")) - urlargs.serviceType = TQString::fromLocal8Bit(args->getOption("mimetype")); - if (args->isSet("select")) { - TQString fn = kurl.fileName(false); - if( !fn.isEmpty() ){ - filesToSelect += fn; - kurl.setFileName(""); - } - } - kdDebug(1202) << "main() -> createBrowserWindowFromProfile servicetype=" << urlargs.serviceType << endl; - KonqMisc::createBrowserWindowFromProfile( profilePath, profile, kurl, urlargs, false, filesToSelect ); - } - else - { - if (args->count() == 0) - { - if (args->isSet("preload")) - { - if( KonqSettings::maxPreloadCount() > 0 ) - { - DCOPRef ref( "kded", "konqy_preloader" ); - if( !ref.callExt( "registerPreloadedKonqy", DCOPRef::NoEventLoop, 5000, - app.dcopClient()->appId(), tqt_xscreen())) - return 0; // too many preloaded or failed - KonqMainWindow* win = new KonqMainWindow( KURL(), false ); // prepare an empty window too - // KonqMainWindow ctor sets always the preloaded flag to false, so create the window before this - KonqMainWindow::setPreloadedFlag( true ); - KonqMainWindow::setPreloadedWindow( win ); - kdDebug(1202) << "Konqy preloaded :" << app.dcopClient()->appId() << endl; - } - else - { - return 0; // no preloading - } - } - else if (!args->isSet("silent")) - { - // By default try to open in webbrowser mode. People can use "konqueror ." to get a filemanager. - TQString profile = "webbrowsing"; - TQString profilePath = locate( "data", TQString::fromLatin1("konqueror/profiles/")+profile ); - if ( !profilePath.isEmpty() ) { - KonqMisc::createBrowserWindowFromProfile( profilePath, profile ); - } else { - KonqMainWindow *mainWindow = new KonqMainWindow; - mainWindow->show(); - } - } - kdDebug(1202) << "main() -> no args" << endl; - } - else - { - KURL::List urlList; - KonqMainWindow * mainwin = 0L; - for ( int i = 0; i < args->count(); i++ ) - { - // KonqMisc::konqFilteredURL doesn't cope with local files... A bit of hackery below - KURL url = args->url(i); - KURL urlToOpen; - TQStringList filesToSelect; - - if (url.isLocalFile() && TQFile::exists(url.path())) // "konqueror index.html" - urlToOpen = url; - else - urlToOpen = KURL( KonqMisc::konqFilteredURL(0L, TQString::fromLocal8Bit(args->arg(i))) ); // "konqueror slashdot.org" - - if ( !mainwin ) { - KParts::URLArgs urlargs; - if (args->isSet("mimetype")) - { - urlargs.serviceType = TQString::fromLocal8Bit(args->getOption("mimetype")); - kdDebug(1202) << "main() : setting serviceType to " << urlargs.serviceType << endl; - } - if (args->isSet("select")) - { - TQString fn = urlToOpen.fileName(false); - if( !fn.isEmpty() ){ - filesToSelect += fn; - urlToOpen.setFileName(""); - } - } - const bool tempFile = TDECmdLineArgs::isTempFileSet(); - mainwin = KonqMisc::createNewWindow( urlToOpen, urlargs, false, filesToSelect, tempFile ); - } else - urlList += urlToOpen; - } - if ( mainwin ) - mainwin->openMultiURL( urlList ); - } - } - } - args->clear(); - - app.exec(); - - // Delete all KonqMainWindows, so that we don't have - // any parts loaded when KLibLoader::cleanUp is called. - // Their deletion was postponed in their event() - // (and Qt doesn't delete WDestructiveClose widgets on exit anyway :( ) - while( KonqMainWindow::mainWindowList() != NULL ) - { // the list will be deleted by last KonqMainWindow - delete KonqMainWindow::mainWindowList()->first(); - } - - delete kiface; - - crashlog_file.unlink(); - - return 0; -} diff --git a/konqueror/konq_main.cpp b/konqueror/konq_main.cpp new file mode 100644 index 000000000..ee1fc71db --- /dev/null +++ b/konqueror/konq_main.cpp @@ -0,0 +1,222 @@ +/* This file is part of the KDE project + Copyright (C) 1998, 1999 Simon Hausmann + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "konq_main.h" +#include "konq_misc.h" +#include "konq_factory.h" +#include "konq_mainwindow.h" +#include "konq_view.h" +#include "konq_settingsxt.h" +#include "KonquerorIface.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +static const TDECmdLineOptions options[] = +{ + { "silent", I18N_NOOP("Start without a default window"), 0 }, + { "preload", I18N_NOOP("Preload for later use"), 0 }, + { "profile ", I18N_NOOP("Profile to open"), 0 }, + { "profiles", I18N_NOOP("List available profiles"), 0 }, + { "mimetype ", I18N_NOOP("Mimetype to use for this URL (e.g. text/html or inode/directory)"), 0 }, + { "select", I18N_NOOP("For URLs that point to files, opens the directory and selects the file, instead of opening the actual file"), 0 }, + { "+[URL]", I18N_NOOP("Location to open"), 0 }, + TDECmdLineLastOption +}; + +extern "C" KDE_EXPORT int kdemain( int argc, char **argv ) +{ + TDECmdLineArgs::init( argc, argv, KonqFactory::aboutData() ); + + TDECmdLineArgs::addCmdLineOptions( options ); // Add our own options. + TDECmdLineArgs::addTempFileOption(); + + KonquerorApplication app; + + app.dcopClient()->registerAs( "konqueror" ); + + KonquerorIface *kiface = new KonquerorIface; + app.dcopClient()->setDefaultObject( kiface->objId() ); + + TDEGlobal::locale()->insertCatalogue("libkonq"); // needed for apps using libkonq + KImageIO::registerFormats(); + + TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs(); + + KTempFile crashlog_file(locateLocal("tmp", "konqueror-crash-"), ".log"); + KonqMainWindow::s_crashlog_file = crashlog_file.file(); + + if ( kapp->isRestored() ) + { + int n = 1; + while ( KonqMainWindow::canBeRestored( n ) ) + { + TQString className = TDEMainWindow::classNameOfToplevel( n ); + if( className == TQString::fromLatin1( "KonqMainWindow" )) + (new KonqMainWindow( KURL(), false ) )->restore( n ); + else + kdWarning() << "Unknown class " << className << " in session saved data!" << endl; + n++; + } + } + else + { + if (args->isSet("profiles")) + { + TQStringList profiles = TDEGlobal::dirs()->findAllResources("data", "konqueror/profiles/*", false, true); + profiles.sort(); + for(TQStringList::ConstIterator it = profiles.begin(); + it != profiles.end(); ++it) + { + TQString file = *it; + file = file.mid(file.findRev('/')+1); + printf("%s\n", TQFile::encodeName(file).data()); + } + + return 0; + } + if (args->isSet("profile")) + { + TQString profile = TQString::fromLocal8Bit(args->getOption("profile")); + TQString profilePath = profile; + if (profile[0] != '/') + profilePath = locate( "data", TQString::fromLatin1("konqueror/profiles/")+profile ); + TQString url; + TQStringList filesToSelect; + if (args->count() == 1) + url = TQString::fromLocal8Bit(args->arg(0)); + KURL kurl(url); + KParts::URLArgs urlargs; + if (args->isSet("mimetype")) + urlargs.serviceType = TQString::fromLocal8Bit(args->getOption("mimetype")); + if (args->isSet("select")) { + TQString fn = kurl.fileName(false); + if( !fn.isEmpty() ){ + filesToSelect += fn; + kurl.setFileName(""); + } + } + kdDebug(1202) << "main() -> createBrowserWindowFromProfile servicetype=" << urlargs.serviceType << endl; + KonqMisc::createBrowserWindowFromProfile( profilePath, profile, kurl, urlargs, false, filesToSelect ); + } + else + { + if (args->count() == 0) + { + if (args->isSet("preload")) + { + if( KonqSettings::maxPreloadCount() > 0 ) + { + DCOPRef ref( "kded", "konqy_preloader" ); + if( !ref.callExt( "registerPreloadedKonqy", DCOPRef::NoEventLoop, 5000, + app.dcopClient()->appId(), tqt_xscreen())) + return 0; // too many preloaded or failed + KonqMainWindow* win = new KonqMainWindow( KURL(), false ); // prepare an empty window too + // KonqMainWindow ctor sets always the preloaded flag to false, so create the window before this + KonqMainWindow::setPreloadedFlag( true ); + KonqMainWindow::setPreloadedWindow( win ); + kdDebug(1202) << "Konqy preloaded :" << app.dcopClient()->appId() << endl; + } + else + { + return 0; // no preloading + } + } + else if (!args->isSet("silent")) + { + // By default try to open in webbrowser mode. People can use "konqueror ." to get a filemanager. + TQString profile = "webbrowsing"; + TQString profilePath = locate( "data", TQString::fromLatin1("konqueror/profiles/")+profile ); + if ( !profilePath.isEmpty() ) { + KonqMisc::createBrowserWindowFromProfile( profilePath, profile ); + } else { + KonqMainWindow *mainWindow = new KonqMainWindow; + mainWindow->show(); + } + } + kdDebug(1202) << "main() -> no args" << endl; + } + else + { + KURL::List urlList; + KonqMainWindow * mainwin = 0L; + for ( int i = 0; i < args->count(); i++ ) + { + // KonqMisc::konqFilteredURL doesn't cope with local files... A bit of hackery below + KURL url = args->url(i); + KURL urlToOpen; + TQStringList filesToSelect; + + if (url.isLocalFile() && TQFile::exists(url.path())) // "konqueror index.html" + urlToOpen = url; + else + urlToOpen = KURL( KonqMisc::konqFilteredURL(0L, TQString::fromLocal8Bit(args->arg(i))) ); // "konqueror slashdot.org" + + if ( !mainwin ) { + KParts::URLArgs urlargs; + if (args->isSet("mimetype")) + { + urlargs.serviceType = TQString::fromLocal8Bit(args->getOption("mimetype")); + kdDebug(1202) << "main() : setting serviceType to " << urlargs.serviceType << endl; + } + if (args->isSet("select")) + { + TQString fn = urlToOpen.fileName(false); + if( !fn.isEmpty() ){ + filesToSelect += fn; + urlToOpen.setFileName(""); + } + } + const bool tempFile = TDECmdLineArgs::isTempFileSet(); + mainwin = KonqMisc::createNewWindow( urlToOpen, urlargs, false, filesToSelect, tempFile ); + } else + urlList += urlToOpen; + } + if ( mainwin ) + mainwin->openMultiURL( urlList ); + } + } + } + args->clear(); + + app.exec(); + + // Delete all KonqMainWindows, so that we don't have + // any parts loaded when KLibLoader::cleanUp is called. + // Their deletion was postponed in their event() + // (and Qt doesn't delete WDestructiveClose widgets on exit anyway :( ) + while( KonqMainWindow::mainWindowList() != NULL ) + { // the list will be deleted by last KonqMainWindow + delete KonqMainWindow::mainWindowList()->first(); + } + + delete kiface; + + crashlog_file.unlink(); + + return 0; +} diff --git a/konqueror/konq_mainwindow.cc b/konqueror/konq_mainwindow.cc deleted file mode 100644 index ebd9ab8df..000000000 --- a/konqueror/konq_mainwindow.cc +++ /dev/null @@ -1,5998 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 1998, 1999 Simon Hausmann - Copyright (C) 2000 Carsten Pfeiffer - Copyright (C) 2000-2005 David Faure - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "konq_mainwindow.h" -#include "konq_guiclients.h" -#include "KonqMainWindowIface.h" -#include "konq_view.h" -#include "konq_run.h" -#include "konq_misc.h" -#include "konq_viewmgr.h" -#include "konq_frame.h" -#include "konq_tabs.h" -#include "konq_events.h" -#include "konq_actions.h" -#include "konq_settingsxt.h" -#include "konq_extensionmanager.h" -#include "delayedinitializer.h" -#include -#include -#include -#include -#include -#include -#include -// we define STRICT_ANSI to get rid of some warnings in glibc -#ifndef __STRICT_ANSI__ -#define __STRICT_ANSI__ -#define _WE_DEFINED_IT_ -#endif -#include -#ifdef _WE_DEFINED_IT_ -#undef __STRICT_ANSI__ -#undef _WE_DEFINED_IT_ -#endif -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "konq_main.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef KDE_MALLINFO_STDLIB -#include -#endif -#ifdef KDE_MALLINFO_MALLOC -#include -#endif - -#include -#include -#include -#include - -template class TQPtrList; -template class TQPtrList; - -TQPtrList *KonqMainWindow::s_lstViews = 0; -TDEConfig * KonqMainWindow::s_comboConfig = 0; -TDECompletion * KonqMainWindow::s_pCompletion = 0; -TQFile * KonqMainWindow::s_crashlog_file = 0; -bool KonqMainWindow::s_preloaded = false; -KonqMainWindow* KonqMainWindow::s_preloadedWindow = 0; -int KonqMainWindow::s_initialMemoryUsage = -1; -time_t KonqMainWindow::s_startupTime; -int KonqMainWindow::s_preloadUsageCount; - -KonqOpenURLRequest KonqOpenURLRequest::null; - -static int current_memory_usage( int* limit = NULL ); - -#include "konq_mainwindow_p.h" - -KonqExtendedBookmarkOwner::KonqExtendedBookmarkOwner(KonqMainWindow *w) -{ - m_pKonqMainWindow = w; -} - -KonqMainWindow::KonqMainWindow( const KURL &initialURL, bool openInitialURL, const char *name, const TQString& xmluiFile) - : KParts::MainWindow( NoDCOPObject, 0L, name, (WFlags)(WDestructiveClose | WStyle_ContextHelp | TQt::WGroupLeader) ) -{ - setPreloadedFlag( false ); - - if ( !s_lstViews ) - s_lstViews = new TQPtrList; - - s_lstViews->append( this ); - - m_urlCompletionStarted = false; - - m_currentView = 0L; - m_pChildFrame = 0L; - m_pActiveChild = 0L; - m_pWorkingTab = 0L; - m_initialKonqRun = 0L; - m_pBookmarkMenu = 0L; - m_dcopObject = new KonqMainWindowIface( this ); - m_combo = 0L; - m_bURLEnterLock = false; - m_bLocationBarConnected = false; - m_paBookmarkBar = 0L; - m_pURLCompletion = 0L; - m_goBuffer = 0; - m_configureDialog = 0L; - - m_bViewModeToggled = false; - - m_prevMenuBarVisible = true; - - m_pViewManager = new KonqViewManager( this ); - - m_toggleViewGUIClient = new ToggleViewGUIClient( this ); - - m_openWithActions.setAutoDelete( true ); - m_viewModeActions.setAutoDelete( true ); - m_toolBarViewModeActions.setAutoDelete( true ); - m_viewModeMenu = 0; - m_paDelete = 0; - m_bookmarkBarActionCollection = 0L; - KonqExtendedBookmarkOwner *extOwner = new KonqExtendedBookmarkOwner( this ); - m_pBookmarksOwner = extOwner; - connect( extOwner, - TQT_SIGNAL( signalFillBookmarksList(KExtendedBookmarkOwner::QStringPairList &) ), - extOwner, - TQT_SLOT( slotFillBookmarksList(KExtendedBookmarkOwner::QStringPairList &) ) ); - - // init history-manager, load history, get completion object - if ( !s_pCompletion ) { - KonqHistoryManager *mgr = new KonqHistoryManager( TQT_TQOBJECT(kapp), "history mgr" ); - s_pCompletion = mgr->completionObject(); - - - // setup the completion object before createGUI(), so that the combo - // picks up the correct mode from the HistoryManager (in slotComboPlugged) - int mode = KonqSettings::settingsCompletionMode(); - s_pCompletion->setCompletionMode( (TDEGlobalSettings::Completion) mode ); - } - connect(KParts::HistoryProvider::self(), TQT_SIGNAL(cleared()), TQT_SLOT(slotClearComboHistory())); - - KonqPixmapProvider *prov = KonqPixmapProvider::self(); - if ( !s_comboConfig ) { - s_comboConfig = new TDEConfig( "konq_history", false, false ); - KonqCombo::setConfig( s_comboConfig ); - s_comboConfig->setGroup( "Location Bar" ); - prov->load( s_comboConfig, "ComboIconCache" ); - } - connect( prov, TQT_SIGNAL( changed() ), TQT_SLOT( slotIconsChanged() ) ); - - initCombo(); - initActions(); - - setInstance( TDEGlobal::instance() ); - - connect( KSycoca::self(), TQT_SIGNAL( databaseChanged() ), - this, TQT_SLOT( slotDatabaseChanged() ) ); - - connect( kapp, TQT_SIGNAL( tdedisplayFontChanged()), TQT_SLOT(slotReconfigure())); - - //load the xmlui file specified in the profile or the default konqueror.rc - setXMLFile( xmluiFile ); - - setStandardToolBarMenuEnabled( true ); - - createGUI( 0L ); - - connect(toolBarMenuAction(),TQT_SIGNAL(activated()),this,TQT_SLOT(slotForceSaveMainWindowSettings()) ); - - if ( !m_toggleViewGUIClient->empty() ) - plugActionList( TQString::fromLatin1( "toggleview" ), m_toggleViewGUIClient->actions() ); - else - { - delete m_toggleViewGUIClient; - m_toggleViewGUIClient = 0; - } - - // Those menus are created by konqueror.rc so their address will never change - TQPopupMenu *popup = static_cast(factory()->container("edit",this)); - if (popup) - TDEAcceleratorManager::manage(popup); - popup = static_cast(factory()->container("tools",this)); - if (popup) - TDEAcceleratorManager::manage(popup); - - m_bSaveViewPropertiesLocally = KonqSettings::saveViewPropertiesLocally(); - m_bHTMLAllowed = KonqSettings::htmlAllowed(); - - m_ptaUseHTML->setChecked( m_bHTMLAllowed ); - m_paSaveViewPropertiesLocally->setChecked( m_bSaveViewPropertiesLocally ); - - KonqUndoManager::incRef(); - - connect( KonqUndoManager::self(), TQT_SIGNAL( undoAvailable( bool ) ), - this, TQT_SLOT( slotUndoAvailable( bool ) ) ); - m_bNeedApplyKonqMainWindowSettings = true; - - if ( !initialURL.isEmpty() ) - { - openFilteredURL( initialURL.url() ); - } - else if ( openInitialURL ) - { - KURL homeURL; - homeURL.setPath( TQDir::homeDirPath() ); - openURL( 0L, homeURL ); - } - else - // silent - m_bNeedApplyKonqMainWindowSettings = false; - - // Read basic main-view settings, and set to autosave - setAutoSaveSettings( "KonqMainWindow", false ); - - if ( !initialGeometrySet() ) - resize( 700, 480 ); - //kdDebug(1202) << "KonqMainWindow::KonqMainWindow " << this << " done" << endl; - - if( s_initialMemoryUsage == -1 ) - { - s_initialMemoryUsage = current_memory_usage(); - s_startupTime = time( NULL ); - s_preloadUsageCount = 0; - } -} - -KonqMainWindow::~KonqMainWindow() -{ - kdDebug(1202) << "KonqMainWindow::~KonqMainWindow " << this << endl; - - delete m_pViewManager; - - if ( s_lstViews ) - { - s_lstViews->removeRef( this ); - if ( s_lstViews->count() == 0 ) - { - delete s_lstViews; - s_lstViews = 0; - } - } - - disconnectActionCollection( actionCollection() ); - - saveToolBarServicesMap(); - - // createShellGUI( false ); - - delete m_pBookmarkMenu; - delete m_paBookmarkBar; - delete m_pBookmarksOwner; - delete m_pURLCompletion; - - m_viewModeActions.clear(); - - KonqUndoManager::decRef(); - - if ( s_lstViews == 0 ) { - delete KonqPixmapProvider::self(); - delete s_comboConfig; - s_comboConfig = 0L; - } - - delete m_configureDialog; - m_configureDialog = 0L; - delete m_dcopObject; - m_dcopObject = 0L; - delete m_combo; - m_combo = 0L; - delete m_locationLabel; - m_locationLabel = 0L; - - kdDebug(1202) << "KonqMainWindow::~KonqMainWindow " << this << " done" << endl; -} - -TQWidget * KonqMainWindow::createContainer( TQWidget *parent, int index, const TQDomElement &element, int &id ) -{ - static TQString nameBookmarkBar = TQString::fromLatin1( "bookmarkToolBar" ); - static TQString tagToolBar = TQString::fromLatin1( "ToolBar" ); - - TQWidget *res = KParts::MainWindow::createContainer( parent, index, element, id ); - - if ( res && (element.tagName() == tagToolBar) && (element.attribute( "name" ) == nameBookmarkBar) ) - { - assert( res->inherits( "TDEToolBar" ) ); - if (!kapp->authorizeTDEAction("bookmarks")) - { - delete res; - return 0; - } - - if ( !m_bookmarkBarActionCollection ) - { - // The actual menu needs a different action collection, so that the bookmarks - // don't appear in kedittoolbar - m_bookmarkBarActionCollection = new TDEActionCollection( this ); - m_bookmarkBarActionCollection->setHighlightingEnabled( true ); - connectActionCollection( m_bookmarkBarActionCollection ); - DelayedInitializer *initializer = new DelayedInitializer( TQEvent::Show, TQT_TQOBJECT(res) ); - connect( initializer, TQT_SIGNAL( initialize() ), this, TQT_SLOT(initBookmarkBar()) ); - } - } - - return res; -} - -void KonqMainWindow::initBookmarkBar() -{ - TDEToolBar * bar = static_cast( TQT_TQWIDGET(child( "bookmarkToolBar", "TDEToolBar" )) ); - - if (!bar) return; - - delete m_paBookmarkBar; - m_paBookmarkBar = new KBookmarkBar( KonqBookmarkManager::self(), m_pBookmarksOwner, bar, m_bookmarkBarActionCollection, TQT_TQOBJECT(this) ); - connect( m_paBookmarkBar, - TQT_SIGNAL( aboutToShowContextMenu(const KBookmark &, TQPopupMenu*) ), - this, TQT_SLOT( slotFillContextMenu(const KBookmark &, TQPopupMenu*) )); - connect( m_paBookmarkBar, - TQT_SIGNAL( openBookmark(const TQString &, TQt::ButtonState) ), - this, TQT_SLOT( slotOpenBookmarkURL(const TQString &, TQt::ButtonState) )); - - // hide if empty - if (bar->count() == 0 ) - bar->hide(); -} - -void KonqMainWindow::removeContainer( TQWidget *container, TQWidget *parent, TQDomElement &element, int id ) -{ - static TQString nameBookmarkBar = TQString::fromLatin1( "bookmarkToolBar" ); - static TQString tagToolBar = TQString::fromLatin1( "ToolBar" ); - - if ( element.tagName() == tagToolBar && element.attribute( "name" ) == nameBookmarkBar ) - { - assert( container->inherits( "TDEToolBar" ) ); - if (m_paBookmarkBar) - m_paBookmarkBar->clear(); - } - - KParts::MainWindow::removeContainer( container, parent, element, id ); -} - -// Detect a name filter (e.g. *.txt) in the url. -// Note that TDEShortURIFilter does the same, but we have no way of getting it from there -// -// Note: this removes the filter from the URL. -static TQString detectNameFilter( KURL & url ) -{ - if ( !KProtocolInfo::supportsListing(url) ) - return TQString::null; - - // Look for wildcard selection - TQString nameFilter; - TQString path = url.path(); - int lastSlash = path.findRev( '/' ); - if ( lastSlash > -1 ) - { - if ( !url.query().isEmpty() && lastSlash == (int)path.length()-1 ) { // In /tmp/?foo, foo isn't a query - path += url.query(); // includes the '?' - url.setQuery( TQString::null ); - } - const TQString fileName = path.mid( lastSlash + 1 ); - if ( fileName.find( '*' ) != -1 || fileName.find( '[' ) != -1 || fileName.find( '?' ) != -1 ) - { - // Check that a file or dir with all the special chars in the filename doesn't exist - if ( url.isLocalFile() ? !TQFile::exists( path ) : !TDEIO::NetAccess::exists( url, false, 0 ) ) - { - nameFilter = fileName; - url.setFileName( TQString::null ); - kdDebug(1202) << "Found wildcard. nameFilter=" << nameFilter << " New url=" << url << endl; - } - } - } - - return nameFilter; -} - -void KonqMainWindow::openFilteredURL( const TQString & url, KonqOpenURLRequest & req ) -{ - // Filter URL to build a correct one - if (m_currentDir.isEmpty() && m_currentView) - m_currentDir = m_currentView->url().path(1); - - KURL filteredURL ( KonqMisc::konqFilteredURL( this, url, m_currentDir ) ); - kdDebug(1202) << "url " << url << " filtered into " << filteredURL.prettyURL() << endl; - - if ( filteredURL.isEmpty() ) // initially empty, or error (e.g. ~unknown_user) - return; - - m_currentDir = TQString::null; - - openURL( 0L, filteredURL, TQString::null, req ); - - // #4070: Give focus to view after URL was entered manually - // Note: we do it here if the view mode (i.e. part) wasn't changed - // If it is changed, then it's done in KonqView::changeViewMode - if ( m_currentView && m_currentView->part() ) - m_currentView->part()->widget()->setFocus(); - -} - -void KonqMainWindow::openFilteredURL( const TQString & _url, bool inNewTab, bool tempFile ) -{ - KonqOpenURLRequest req( _url ); - req.newTab = inNewTab; - req.newTabInFront = true; - req.tempFile = tempFile; - - openFilteredURL( _url, req ); -} - -void KonqMainWindow::openURL( KonqView *_view, const KURL &_url, - const TQString &_serviceType, KonqOpenURLRequest& req, - bool trustedSource ) -{ - kdDebug(1202) << "KonqMainWindow::openURL : url = '" << _url << "' " - << "serviceType='" << _serviceType << "' req=" << req.debug() - << " view=" << _view << endl; - - KURL url( _url ); - if (url.url().startsWith("$(")) { - // check for environment variables and make necessary translations - TQString aValue = url.url(); - int nDollarPos = aValue.find( '$' ); - - while( nDollarPos != -1 && nDollarPos+1 < static_cast(aValue.length())) { - // there is at least one $ - if( (aValue)[nDollarPos+1] != '$' ) { - uint nEndPos = nDollarPos+1; - // the next character is no $ - TQString aVarName; - if (aValue[nEndPos]=='{') - { - while ( (nEndPos <= aValue.length()) && (aValue[nEndPos]!='}') ) - nEndPos++; - nEndPos++; - aVarName = aValue.mid( nDollarPos+2, nEndPos-nDollarPos-3 ); - } - else - { - while ( nEndPos <= aValue.length() && (aValue[nEndPos].isNumber() - || aValue[nEndPos].isLetter() || aValue[nEndPos]=='_' ) ) - nEndPos++; - aVarName = aValue.mid( nDollarPos+1, nEndPos-nDollarPos-1 ); - } - const char* pEnv = 0; - if (!aVarName.isEmpty()) - pEnv = getenv( aVarName.ascii() ); - if( pEnv ) { - // !!! Sergey A. Sukiyazov !!! - // A environment variables may contain values in 8bit - // locale cpecified encoding or in UTF8 encoding. - aValue.replace( nDollarPos, nEndPos-nDollarPos, KStringHandler::from8Bit( pEnv ) ); - } else - aValue.remove( nDollarPos, nEndPos-nDollarPos ); - } else { - // remove one of the dollar signs - aValue.remove( nDollarPos, 1 ); - nDollarPos++; - } - nDollarPos = aValue.find( '$', nDollarPos ); - } - url = KURL(aValue); - } - TQString serviceType( _serviceType ); - if ( url.url() == "about:blank" ) - { - serviceType = "text/html"; - } - else if ( !url.isValid() ) - { - KMessageBox::error(0, i18n("Malformed URL\n%1").arg(url.url())); - return; - } - else if ( !KProtocolInfo::isKnownProtocol( url ) && url.protocol() != "about" ) - { - KMessageBox::error(0, i18n("Protocol not supported\n%1").arg(url.protocol())); - return; - } - - // Default action for media encrypted disks is either lock or unlock based on current status - TQString lockingAction = TQString::null; - if (serviceType.contains("encrypted_locked")) { - lockingAction = "konqueror/servicemenus/media_unlock.desktop"; - } - else if (serviceType.contains("encrypted_unlocked")) { - lockingAction = "konqueror/servicemenus/media_lock.desktop"; - } - if (!lockingAction.isEmpty()) { - TQString lockingService = TDEGlobal::dirs()->findResource("data", lockingAction); - if (!lockingService.isEmpty()) { - TQValueList serviceList = KDEDesktopMimeType::userDefinedServices(lockingService, url.isLocalFile()); - if (serviceList.count() == 1) { - KURL::List m_lstURLs; - m_lstURLs.append(url); - KDEDesktopMimeType::executeService(m_lstURLs, serviceList[0]); - return; - } - } - } - - TQString nameFilter = detectNameFilter( url ); - if ( !nameFilter.isEmpty() ) - { - req.nameFilter = nameFilter; - url.setFileName( TQString::null ); - } - - KonqView *view = _view; - - // When clicking a 'follow active' view (e.g. view is the sidebar), - // open the URL in the active view - if ( view && view->isFollowActive() ) - view = m_currentView; - - if ( !view && !req.newTab ) - view = m_currentView; /* Note, this can be 0L, e.g. on startup */ - else if ( !view && req.newTab ) { - view = m_pViewManager->addTab(TQString::null, - TQString::null, - false, - req.openAfterCurrentPage); - if (view) { - view->setCaption( _url.host() ); - view->setLocationBarURL( _url ); - if ( !req.args.frameName.isEmpty() ) - view->setViewName( req.args.frameName ); // #44961 - - if ( req.newTabInFront ) - m_pViewManager->showTab( view ); - - updateViewActions(); //A new tab created -- we may need to enable the "remove tab" button (#56318) - } - else - req.newTab = false; - } - - const TQString oldLocationBarURL = m_combo->currentText(); - if ( view ) - { - if ( view == m_currentView ) - { - //will do all the stuff below plus GUI stuff - abortLoading(); - } - else - { - view->stop(); - // Don't change location bar if not current view - } - } - - // Fast mode for local files: do the stat ourselves instead of letting KRun do it. - if ( serviceType.isEmpty() && url.isLocalFile() ) - { - TQCString _path( TQFile::encodeName(url.path())); - KDE_struct_stat buff; - if ( KDE_stat( _path.data(), &buff ) != -1 ) - serviceType = KMimeType::findByURL( url, buff.st_mode )->name(); - } - - kdDebug(1202) << "trying openView for " << url << " (serviceType " << serviceType << ")" << endl; - if ( ( !serviceType.isEmpty() && serviceType != "application/octet-stream") || - url.url().startsWith("about:konqueror") || url.url() == "about:plugins" ) - { - KService::Ptr offer = KServiceTypeProfile::preferredService(serviceType, "Application"); - // If the associated app is konqueror itself, then make sure we try to embed before bailing out. - if ( isMimeTypeAssociatedWithSelf( serviceType, offer ) ) - req.forceAutoEmbed = true; - - // Built-in view ? - if ( !openView( serviceType, url, view /* can be 0L */, req ) ) - { - //kdDebug(1202) << "KonqMainWindow::openURL : openView returned false" << endl; - // Are we following another view ? Then forget about this URL. Otherwise fire app. - if ( !req.followMode ) - { - //kdDebug(1202) << "KonqMainWindow::openURL : we were not following. Fire app." << endl; - // We know the servicetype, let's try its preferred service - if ( isMimeTypeAssociatedWithSelf( serviceType, offer ) ) { - KMessageBox::error( this, i18n("There appears to be a configuration error. You have associated Konqueror with %1, but it cannot handle this file type.").arg(serviceType)); - return; - } - if ( !url.isLocalFile() && KonqRun::isTextExecutable( serviceType ) ) - serviceType = "text/plain"; // view, don't execute - // Remote URL: save or open ? - TQString protClass = KProtocolInfo::protocolClass(url.protocol()); - bool open = url.isLocalFile() || protClass==":local"; - if ( !open ) { - KParts::BrowserRun::AskSaveResult res = KonqRun::askSave( url, offer, serviceType ); - if ( res == KParts::BrowserRun::Save ) - KParts::BrowserRun::simpleSave( url, TQString::null, this ); - open = ( res == KParts::BrowserRun::Open ); - } - if ( open ) - { - KURL::List lst; - lst.append(url); - //kdDebug(1202) << "Got offer " << (offer ? offer->name().latin1() : "0") << endl; - if ( ( trustedSource || KonqRun::allowExecution( serviceType, url ) ) && - ( KonqRun::isExecutable( serviceType ) || !offer || !KRun::run( *offer, lst ) ) ) - { - setLocationBarURL( oldLocationBarURL ); // Revert to previous locationbar URL - (void)new KRun( url, this ); - } - } - } - } - } - else // no known serviceType, use KonqRun - { - if ( ( !view || view->url().isEmpty() ) && !req.newTab ) // startup with argument - { - // Show it for now in the location bar, but we'll need to store it in the view - // later on (can't do it yet since either view == 0 or updateHistoryEntry will be called). - kdDebug(1202) << "setLocationBarURL (startup) : url = " << url << endl; - setLocationBarURL( url ); - } - - kdDebug(1202) << "Creating new konqrun for " << url << " req.typedURL=" << req.typedURL << endl; - - KonqRun * run = new KonqRun( this, view /* can be 0L */, url, req, trustedSource ); - - // Never start in external browser - run->setEnableExternalBrowser(false); - - if ( view ) - view->setRun( run ); - else if ( !req.newTab ) - { - // there can be only one :) (when not a new tab) - delete m_initialKonqRun; - m_initialKonqRun = run; - } - - if ( view == m_currentView ) - startAnimation(); - - connect( run, TQT_SIGNAL( finished() ), this, TQT_SLOT( slotRunFinished() ) ); - } -} - -bool KonqMainWindow::openView( TQString serviceType, const KURL &_url, KonqView *childView, KonqOpenURLRequest& req ) -{ - // Second argument is referring URL - if ( !kapp->authorizeURLAction("open", childView ? childView->url() : KURL(), _url) ) - { - TQString msg = TDEIO::buildErrorString(TDEIO::ERR_ACCESS_DENIED, _url.prettyURL()); - KMessageBox::queuedMessageBox( this, KMessageBox::Error, msg ); - return true; // Nothing else to do. - } - - if ( KonqRun::isExecutable( serviceType ) ) - return false; // execute, don't open - // Contract: the caller of this method should ensure the view is stopped first. - -#ifndef NDEBUG - kdDebug(1202) << "KonqMainWindow::openView " << serviceType << " " << _url << " " << childView << " req:" << req.debug() << endl; -#endif - bool bOthersFollowed = false; - - if ( childView ) - { - // If we're not already following another view (and if we are not reloading) - if ( !req.followMode && !req.args.reload && !m_pViewManager->isLoadingProfile() ) - { - // When clicking a 'follow active' view (e.g. childView is the sidebar), - // open the URL in the active view - // (it won't do anything itself, since it's locked to its location) - if ( childView->isFollowActive() && childView != m_currentView ) - { - abortLoading(); - setLocationBarURL( _url ); - KonqOpenURLRequest newreq; - newreq.followMode = true; - newreq.args = req.args; - bOthersFollowed = openView( serviceType, _url, m_currentView, newreq ); - } - // "link views" feature, and "sidebar follows active view" feature - bOthersFollowed = makeViewsFollow(_url, req.args, serviceType, childView) || bOthersFollowed; - } - if ( childView->isLockedLocation() && !req.args.reload /* allow to reload a locked view*/ ) - return bOthersFollowed; - } - - TQString indexFile; - - KURL url( _url ); - - // Generic mechanism for redirecting to tar:// when clicking on a tar file, - // zip:// when clicking on a zip file, etc. - // The name of the protocol to redirect to, is read from the mimetype's .desktop file - if ( url.isLocalFile() ) - { - KServiceType::Ptr ptr = KServiceType::serviceType( serviceType ); - if ( ptr ) - { - const TQString protocol = ptr->property("X-TDE-LocalProtocol").toString(); - if ( !protocol.isEmpty() && KonqFMSettings::settings()->shouldEmbed( serviceType ) ) - { - url.setProtocol( protocol ); - if ( serviceType == "application/x-webarchive" ) - { - url.setPath( url.path() + "/index.html" ); - serviceType = "text/html"; - } - else - { - url.setPath( url.path() + '/' ); - serviceType = "inode/directory"; - } - } - } - } - - /////////// - - // In case we open an index.html, we want the location bar - // to still display the original URL (so that 'up' uses that URL, - // and since that's what the user entered). - // changeViewMode will take care of setting and storing that url. - TQString originalURL = url.pathOrURL(); - if ( !req.nameFilter.isEmpty() ) // keep filter in location bar - { - if (!originalURL.endsWith("/")) - originalURL += '/'; - originalURL += req.nameFilter; - } - - TQString serviceName; // default: none provided - - if ( url.url().startsWith("about:konqueror") || url.url() == "about:plugins" ) - { - serviceType = "KonqAboutPage"; // not KParts/ReadOnlyPart, it fills the Location menu ! :) - serviceName = "konq_aboutpage"; - originalURL = req.typedURL.isEmpty() ? TQString::null : url.url(); - // empty if from profile, about:konqueror if the user typed it (not req.typedURL, it could be "about:") - } - else if ( url.url() == "about:blank" && req.typedURL.isEmpty() ) - { - originalURL = TQString::null; - } - - // Look for which view mode to use, if a directory - not if view locked - if ( ( !childView || (!childView->isLockedViewMode()) ) - && serviceType == "inode/directory" ) - { // Phew ! - - // Set view mode if necessary (current view doesn't support directories) - if ( !childView || !childView->supportsServiceType( serviceType ) ) - serviceName = KonqSettings::mainViewViewMode(); - - if ( url.isLocalFile() ) // local, we can do better (.directory) - { - // Read it in the .directory file, default to m_bHTMLAllowed - KURL urlDotDir( url ); - urlDotDir.addPath(".directory"); - bool HTMLAllowed = m_bHTMLAllowed; - TQFile f( urlDotDir.path() ); - if ( f.open(IO_ReadOnly) ) - { - f.close(); - KSimpleConfig config( urlDotDir.path(), true ); - config.setGroup( "URL properties" ); - HTMLAllowed = config.readBoolEntry( "HTMLAllowed", m_bHTMLAllowed ); - serviceName = config.readEntry( "ViewMode", serviceName ); - kdDebug(1202) << "serviceName=" << serviceName << endl; - } - if ( HTMLAllowed && - ( ( indexFile = findIndexFile( url.path() ) ) != TQString::null ) ) - { - serviceType = "text/html"; - url = KURL(); - url.setPath( indexFile ); - serviceName = TQString::null; // cancel what we just set, this is not a dir finally - } - - // Reflect this setting in the menu - m_ptaUseHTML->setChecked( HTMLAllowed ); - } - } - - bool ok = true; - if ( !childView ) - { - if (req.newTab) - { - KonqFrameTabs* tabContainer = 0L; - int index = 0; - if ( m_pViewManager->docContainer() && m_pViewManager->docContainer()->frameType() == "Tabs") - { - tabContainer = static_cast(m_pViewManager->docContainer()); - index = tabContainer->currentPageIndex(); - } - childView = m_pViewManager->addTab( serviceType, serviceName, false, req.openAfterCurrentPage ); - - if (req.newTabInFront && childView) - { - if ( !tabContainer ) - tabContainer = static_cast(m_pViewManager->docContainer()); - if ( req.openAfterCurrentPage ) - tabContainer->setCurrentPage( index + 1 ); - else - tabContainer->setCurrentPage( tabContainer->count()-1 ); - } - } - - else - { - // Create a new view - // Initialize always uses force auto-embed even if user setting is "separate viewer", - // since this window has no view yet - we don't want to keep an empty mainwindow. - // This can happen with e.g. application/pdf from a target="_blank" link, or window.open. - childView = m_pViewManager->Initialize( serviceType, serviceName ); - - if ( childView ) - { - enableAllActions( true ); - m_currentView = childView; - } - } - - if ( !childView ) - return false; // It didn't work out. - - childView->setViewName( m_initialFrameName.isEmpty() ? req.args.frameName : m_initialFrameName ); - m_initialFrameName = TQString::null; - } - else // We know the child view - { - if ( !childView->isLockedViewMode() ) - { - bool forceAutoEmbed = req.forceAutoEmbed || req.newTab || req.userRequestedReload; - if ( !req.typedURL.isEmpty() ) // the user _typed_ the URL, he wants it in Konq. - forceAutoEmbed = true; - if ( url.protocol() == "about" ) - forceAutoEmbed = true; - // Related to KonqFactory::createView - if ( !forceAutoEmbed && !KonqFMSettings::settings()->shouldEmbed( serviceType ) ) - { - kdDebug(1202) << "openView: KonqFMSettings says: don't embed this servicetype" << endl; - ok = false; - } - - // If the protocol doesn't support writing (e.g. HTTP) then we might want to save instead of just embedding. - // So (if embedding would succeed, hence the checks above) we ask the user - // Otherwise the user will get asked 'open or save' in openURL anyway. - if ( ok && !forceAutoEmbed && !KProtocolInfo::supportsWriting( url ) ) { - TQString suggestedFilename; - - KonqRun* run = childView->run(); - int attachment = 0; - if (run) { - suggestedFilename = run->suggestedFilename(); - attachment = (run->serverSuggestsSave()) ? KParts::BrowserRun::AttachmentDisposition : KParts::BrowserRun::InlineDisposition; - } - - KParts::BrowserRun::AskSaveResult res = KParts::BrowserRun::askEmbedOrSave( - url, serviceType, suggestedFilename, attachment ); - if ( res == KParts::BrowserRun::Open ) - forceAutoEmbed = true; - else if ( res == KParts::BrowserRun::Cancel ) - return true; // handled, don't do anything else - else { // Save - KParts::BrowserRun::simpleSave( url, suggestedFilename, this ); - return true; // handled - } - } - if ( ok ) - ok = childView->changeViewMode( serviceType, serviceName, forceAutoEmbed ); - } - } - - if (ok) - { - //kdDebug(1202) << "req.nameFilter= " << req.nameFilter << endl; - //kdDebug(1202) << "req.typedURL= " << req.typedURL << endl; - //kdDebug(1202) << "Browser extension? " << (childView->browserExtension() ? "YES" : "NO") << endl; - //kdDebug(1202) << "Referrer: " << req.args.metaData()["referrer"] << endl; - childView->setTypedURL( req.typedURL ); - if ( childView->browserExtension() ) - childView->browserExtension()->setURLArgs( req.args ); - if ( childView->part()->inherits("KonqDirPart") ) - static_cast(childView->part())->setFilesToSelect( req.filesToSelect ); - if ( !url.isEmpty() ) - childView->openURL( url, originalURL, req.nameFilter, req.tempFile ); - } - kdDebug(1202) << "KonqMainWindow::openView ok=" << ok << " bOthersFollowed=" << bOthersFollowed << " returning " - << (ok || bOthersFollowed) - << endl; - return ok || bOthersFollowed; -} - -void KonqMainWindow::slotOpenURLRequest( const KURL &url, const KParts::URLArgs &args ) -{ - kdDebug(1202) << "KonqMainWindow::slotOpenURLRequest frameName=" << args.frameName << endl; - - KParts::ReadOnlyPart *callingPart = static_cast( TQT_TQOBJECT_CONST(sender())->parent() ); - TQString frameName = args.frameName; - - if ( !frameName.isEmpty() ) - { - static TQString _top = TQString::fromLatin1( "_top" ); - static TQString _self = TQString::fromLatin1( "_self" ); - static TQString _parent = TQString::fromLatin1( "_parent" ); - static TQString _blank = TQString::fromLatin1( "_blank" ); - - if ( frameName.lower() == _blank ) - { - slotCreateNewWindow( url, args ); - return; - } - - if ( frameName.lower() != _top && - frameName.lower() != _self && - frameName.lower() != _parent ) - { - KParts::BrowserHostExtension *hostExtension = 0; - KonqView *view = childView( callingPart, frameName, &hostExtension, 0 ); - if ( !view ) - { - KonqMainWindow *mainWindow = 0; - view = findChildView( callingPart, frameName, &mainWindow, &hostExtension, 0 ); - - if ( !view || !mainWindow ) - { - slotCreateNewWindow( url, args ); - return; - } - - if ( hostExtension ) - hostExtension->openURLInFrame( url, args ); - else - mainWindow->openURL( view, url, args ); - return; - } - - if ( hostExtension ) - hostExtension->openURLInFrame( url, args ); - else - openURL( view, url, args ); - return; - } - } - - KonqView *view = childView( callingPart ); - openURL( view, url, args ); -} - -//Called by slotOpenURLRequest -void KonqMainWindow::openURL( KonqView *childView, const KURL &url, const KParts::URLArgs &args ) -{ - kdDebug(1202) << "KonqMainWindow::openURL (from slotOpenURLRequest) url=" << url.prettyURL() << endl; - KonqOpenURLRequest req; - req.args = args; - - // Clicking on a link that points to the page itself (e.g. anchor) - if ( !args.doPost() && !args.reload && - childView && urlcmp( url.url(), childView->url().url(), true, true ) ) - { - TQString serviceType = args.serviceType; - if ( serviceType.isEmpty() ) - serviceType = childView->serviceType(); - - childView->stop(); - req.forceAutoEmbed = true; - - req.openAfterCurrentPage = KonqSettings::openAfterCurrentPage(); - openView( serviceType, url, childView, req ); - return; - } - - openURL( childView, url, args.serviceType, req, args.trustedSource ); -} - -TQObject *KonqMainWindow::lastFrame( KonqView *view ) -{ - TQObject *nextFrame, *viewFrame; - nextFrame = TQT_TQOBJECT(view->frame()); - viewFrame = 0; - while ( nextFrame != 0 && ! nextFrame->inherits( TQWIDGETSTACK_OBJECT_NAME_STRING ) ) { - viewFrame = nextFrame; - nextFrame = nextFrame->parent(); - } - return nextFrame ? viewFrame : 0L; -} - -// Linked-views feature, plus "sidebar follows URL opened in the active view" feature -bool KonqMainWindow::makeViewsFollow( const KURL & url, const KParts::URLArgs &args, - const TQString & serviceType, KonqView * senderView ) -{ - if ( !senderView->isLinkedView() && senderView != m_currentView ) - return false; // none of those features apply -> return - - bool res = false; - //kdDebug(1202) << "makeViewsFollow " << senderView->className() << " url=" << url << " serviceType=" << serviceType << endl; - KonqOpenURLRequest req; - req.followMode = true; - req.args = args; - // We can't iterate over the map here, and openURL for each, because the map can get modified - // (e.g. by part changes). Better copy the views into a list. - TQPtrList listViews; - MapViews::ConstIterator it = m_mapViews.begin(); - MapViews::ConstIterator end = m_mapViews.end(); - for (; it != end; ++it ) - listViews.append( it.data() ); - - TQObject *senderFrame = lastFrame( senderView ); - - for ( KonqView * view = listViews.first() ; view ; view = listViews.next()) - { - bool followed = false; - // Views that should follow this URL as both views are linked - if ( (view != senderView) && view->isLinkedView() && senderView->isLinkedView() ) - { - TQObject *viewFrame = lastFrame( view ); - - // Only views in the same tab of the sender will follow - if ( senderFrame && viewFrame && viewFrame != senderFrame ) - continue; - - kdDebug(1202) << "makeViewsFollow: Sending openURL to view " << view->part()->className() << " url=" << url << endl; - - // XXX duplicate code from ::openURL - if ( view == m_currentView ) - { - abortLoading(); - setLocationBarURL( url ); - } - else - view->stop(); - - followed = openView( serviceType, url, view, req ); - } - else - { - // Make the sidebar follow the URLs opened in the active view - if ((view!=senderView) && view->isFollowActive() && senderView == m_currentView) - { - followed = openView(serviceType, url, view, req); - } - } - - // Ignore return value if the view followed but doesn't really - // show the file contents. We still want to see that - // file, e.g. in a separate viewer. - // This happens in views locked to a directory mode, - // like sidebar and konsolepart (#52161). - bool ignore = view->isLockedViewMode() && view->supportsServiceType("inode/directory"); - //kdDebug(1202) << "View " << view->service()->name() - // << " supports dirs: " << view->supportsServiceType( "inode/directory" ) - // << " is locked-view-mode:" << view->isLockedViewMode() - // << " ignore=" << ignore << endl; - if ( !ignore ) - res = followed || res; - } - - return res; -} - -void KonqMainWindow::abortLoading() -{ - //kdDebug(1202) << "KonqMainWindow::abortLoading()" << endl; - if ( m_currentView ) - { - m_currentView->stop(); // will take care of the statusbar - stopAnimation(); - } -} - -void KonqMainWindow::slotCreateNewWindow( const KURL &url, const KParts::URLArgs &args ) -{ - kdDebug(1202) << "KonqMainWindow::slotCreateNewWindow url=" << url.prettyURL() << endl; - - if ( args.newTab() || ( KonqSettings::mmbOpensTab() && - (const_cast(&args)->metaData()["forcenewwindow"]).isEmpty()) ) { - KonqOpenURLRequest req; - req.newTab = true; - req.newTabInFront = KonqSettings::newTabsInFront(); - req.openAfterCurrentPage = KonqSettings::openAfterCurrentPage(); - - if (TDEApplication::keyboardMouseState() & TQt::ShiftButton) - req.newTabInFront = !req.newTabInFront; - req.args = args; - openURL( 0L, url, TQString::null, req ); - } - else - { - KonqMisc::createNewWindow( url, args ); - } -} - -// This is mostly for the JS window.open call -void KonqMainWindow::slotCreateNewWindow( const KURL &url, const KParts::URLArgs &args, - const KParts::WindowArgs &windowArgs, KParts::ReadOnlyPart *&part ) -{ - kdDebug(1202) << "KonqMainWindow::slotCreateNewWindow(4 args) url=" << url.prettyURL() - << " args.serviceType=" << args.serviceType - << " args.frameName=" << args.frameName << endl; - - part = 0; // Make sure to be initialized in case of failure... - - KonqMainWindow *mainWindow = 0L; - if ( !args.frameName.isEmpty() && args.frameName.lower() != "_blank" ) - { - KParts::BrowserHostExtension *hostExtension = 0; - KParts::ReadOnlyPart *ro_part = 0L; - KParts::BrowserExtension *be = ::tqqt_cast(sender()); - if (be) - ro_part = ::tqqt_cast(be->parent()); - if ( findChildView( ro_part, args.frameName, &mainWindow, &hostExtension, &part ) ) - { - // Found a view. If url isn't empty, we should open it - but this never happens currently - // findChildView put the resulting part in 'part', so we can just return now - //kdDebug() << " frame=" << args.frameName << " -> found part=" << part << " " << part->name() << endl; - return; - } - } - - if ( KonqSettings::popupsWithinTabs() || ( KonqSettings::mmbOpensTab() && windowArgs.lowerWindow ) ) { - bool aftercurrentpage = KonqSettings::openAfterCurrentPage(); - bool newtabsinfront = KonqSettings::newTabsInFront(); - if ( windowArgs.lowerWindow ) - newtabsinfront =! newtabsinfront; - - KonqView* newView = m_pViewManager->addTab(TQString::null, TQString::null, false, aftercurrentpage); - if (newView == 0L) return; - - if (newtabsinfront) - m_pViewManager->showTab( newView ); - - openURL( newView, url.isEmpty() ? KURL("about:blank") : url, TQString::null); - newView->setViewName( args.frameName ); - part=newView->part(); - - return; - } - - mainWindow = new KonqMainWindow( KURL(), false ); - mainWindow->setInitialFrameName( args.frameName ); - mainWindow->resetAutoSaveSettings(); // Don't autosave - - KonqOpenURLRequest req; - req.args = args; - - if ( args.serviceType.isEmpty() ) - mainWindow->openURL( 0L, url, TQString::null, req ); - else if ( !mainWindow->openView( args.serviceType, url, 0L, req ) ) - { - // we have problems. abort. - delete mainWindow; - part = 0; - return; - } - - KonqView * view = 0L; - // cannot use activePart/currentView, because the activation through the partmanager - // is delayed by a singleshot timer (see KonqViewManager::setActivePart) - if ( mainWindow->viewMap().count() ) - { - MapViews::ConstIterator it = mainWindow->viewMap().begin(); - view = it.data(); - part = it.key(); - } - - // activate the view _now_ in order to make the menuBar() hide call work - if ( part ) { - mainWindow->viewManager()->setActivePart( part, true ); - } - - TQString profileName = TQString::fromLatin1( url.isLocalFile() ? "konqueror/profiles/filemanagement" : "konqueror/profiles/webbrowsing" ); - KSimpleConfig cfg( locate( "data", profileName ), true ); - cfg.setGroup( "Profile" ); - - if ( windowArgs.x != -1 ) - mainWindow->move( windowArgs.x, mainWindow->y() ); - if ( windowArgs.y != -1 ) - mainWindow->move( mainWindow->x(), windowArgs.y ); - - TQSize size = KonqViewManager::readConfigSize( cfg, mainWindow ); - - int width; - if ( windowArgs.width != -1 ) - width = windowArgs.width; - else - width = size.isValid() ? size.width() : mainWindow->width(); - - int height; - if ( windowArgs.height != -1 ) - height = windowArgs.height; - else - height = size.isValid() ? size.height() : mainWindow->height(); - - mainWindow->resize( width, height ); - - // process the window args - - if ( !windowArgs.menuBarVisible ) - { - mainWindow->menuBar()->hide(); - mainWindow->m_paShowMenuBar->setChecked( false ); - } - - if ( !windowArgs.toolBarsVisible ) - { - for ( TQPtrListIterator it( mainWindow->toolBarIterator() ); it.current(); ++it ) - { - (*it)->hide(); - } - } - - if ( view ) { - if ( !windowArgs.scrollBarsVisible ) - view->disableScrolling(); - if ( !windowArgs.statusBarVisible ) - view->frame()->statusbar()->hide(); - } - - if ( !windowArgs.resizable ) - // ### this doesn't seem to work :-( - mainWindow->setSizePolicy( TQSizePolicy( TQSizePolicy::Fixed, TQSizePolicy::Fixed ) ); - -// Trying to show the window initially behind the current window is a bit tricky, -// as this involves the window manager, which may see things differently. -// Many WMs raise and activate new windows, which means without WM support this won't work very -// well. If the WM has support for _NET_WM_USER_TIME, it will be just set to 0 (=don't focus on show), -// and the WM should take care of it itself. - bool wm_usertime_support = false; - Time saved_last_input_time = GET_QT_X_USER_TIME(); - if ( windowArgs.lowerWindow ) - { - NETRootInfo wm_info( tqt_xdisplay(), NET::Supported ); - wm_usertime_support = wm_info.isSupported( NET::WM2UserTime ); - if( wm_usertime_support ) - { - // *sigh*, and I thought nobody would need TQWidget::dontFocusOnShow(). - // Avoid Qt's support for user time by setting it to 0, and - // set the property ourselves. - SET_QT_X_USER_TIME(0); - KWin::setUserTime( mainWindow->winId(), 0 ); - } - // Put below the current window before showing, in case that actually works with the WM. - // First do complete lower(), then stackUnder(), because the latter may not work with many WMs. - mainWindow->lower(); - mainWindow->stackUnder( this ); - } - - mainWindow->show(); - - if ( windowArgs.lowerWindow ) - { - SET_QT_X_USER_TIME(saved_last_input_time); - if( !wm_usertime_support ) - { // No WM support. Let's try ugly tricks. - mainWindow->lower(); - mainWindow->stackUnder( this ); - if( this->isActiveWindow()) - this->setActiveWindow(); - } - } - - if ( windowArgs.fullscreen ) - mainWindow->action( "fullscreen" )->activate(); -} - -void KonqMainWindow::slotNewWindow() -{ - // Use profile from current window, if set - TQString profile = m_pViewManager->currentProfile(); - if ( profile.isEmpty() ) - { - if ( m_currentView && m_currentView->url().protocol().startsWith( "http" ) ) - profile = TQString::fromLatin1("webbrowsing"); - else - profile = TQString::fromLatin1("filemanagement"); - } - KonqMisc::createBrowserWindowFromProfile( - locate( "data", TQString::fromLatin1("konqueror/profiles/")+profile ), - profile ); -} - -void KonqMainWindow::slotDuplicateWindow() -{ - KTempFile tempFile; - tempFile.setAutoDelete( true ); - TDEConfig config( tempFile.name() ); - config.setGroup( "View Profile" ); - m_pViewManager->saveViewProfile( config, true, true ); - - KonqMainWindow *mainWindow = new KonqMainWindow( KURL(), false, 0, xmlFile()); - mainWindow->viewManager()->loadViewProfile( config, m_pViewManager->currentProfile() ); - if (mainWindow->currentView()) - { - mainWindow->copyHistory( childFrame() ); - } - mainWindow->activateChild(); - mainWindow->show(); -#ifndef NDEBUG - mainWindow->viewManager()->printFullHierarchy( this ); -#endif -} - -void KonqMainWindow::slotSendURL() -{ - KURL::List lst = currentURLs(); - TQString body; - TQString fileNameList; - for ( KURL::List::Iterator it = lst.begin() ; it != lst.end() ; ++it ) - { - if ( !body.isEmpty() ) body += '\n'; - body += (*it).prettyURL(); - if ( !fileNameList.isEmpty() ) fileNameList += ", "; - fileNameList += (*it).fileName(); - } - TQString subject; - if ( m_currentView && !m_currentView->part()->inherits("KonqDirPart") ) - subject = m_currentView->caption(); - else - subject = fileNameList; - kapp->invokeMailer(TQString::null,TQString::null,TQString::null, - subject, body); -} - -void KonqMainWindow::slotSendFile() -{ - KURL::List lst = currentURLs(); - TQStringList urls; - TQString fileNameList; - for ( KURL::List::Iterator it = lst.begin() ; it != lst.end() ; ++it ) - { - if ( !fileNameList.isEmpty() ) fileNameList += ", "; - if ( (*it).isLocalFile() && TQFileInfo((*it).path()).isDir() ) - { - // Create a temp dir, so that we can put the ZIP file in it with a proper name - KTempFile zipFile; - TQString zipFileName = zipFile.name(); - zipFile.unlink(); - - TQDir().mkdir(zipFileName,true); - zipFileName = zipFileName+"/"+(*it).fileName()+".zip"; - KZip zip( zipFileName ); - if ( !zip.open( IO_WriteOnly ) ) - continue; // TODO error message - zip.addLocalDirectory( (*it).path(), TQString::null ); - zip.close(); - fileNameList += (*it).fileName()+".zip"; - urls.append( zipFileName ); - } - else - { - fileNameList += (*it).fileName(); - urls.append( (*it).url() ); - } - } - TQString subject; - if ( m_currentView && !m_currentView->part()->inherits("KonqDirPart") ) - subject = m_currentView->caption(); - else - subject = fileNameList; - kapp->invokeMailer(TQString::null, TQString::null, TQString::null, subject, - TQString::null, //body - TQString::null, - urls); // attachments -} - -void KonqMainWindow::slotOpenTerminal() -{ - TQString term = KonqSettings::terminalApplication(); - - TQString dir ( TQDir::homeDirPath() ); - - //Try to get the directory of the current view - if ( m_currentView ) - { - KURL u( m_currentView->url() ); - - // If the given directory is not local, it can still be the URL of an - // ioslave using UDS_LOCAL_PATH which to be converted first. - u = TDEIO::NetAccess::mostLocalURL(u, this); - - //If the URL is local after the above conversion, set the directory. - if ( u.isLocalFile() ) - { - TQString mime = m_currentView->serviceType(); - if ( KMimeType::mimeType(mime)->is("inode/directory") ) - dir = u.path(); - else - dir = u.directory(); - } - } - - TDEProcess cmd; - cmd.setWorkingDirectory(dir); - - // Compensate for terminal having arguments. - TQStringList args = TQStringList::split(' ', term); - for ( TQStringList::iterator it = args.begin(); it != args.end(); ++it ) - cmd << *it; - - kdDebug(1202) << "slotOpenTerminal: directory " << dir - << ", terminal:" << term << endl; - cmd.start(TDEProcess::DontCare); -} - -void KonqMainWindow::slotOpenLocation() -{ - // Don't pre-fill the url, as it is auto-selected and thus overwrites the - // X clipboard, making it impossible to paste in the url you really wanted. - // Another example of why the X clipboard sux - KURLRequesterDlg dlg( TQString::null, this, 0, true); - dlg.setCaption( i18n("Open Location") ); - // Set current directory for relative paths. - // Testcase: konqueror www.kde.org; Ctrl+O; file in $HOME; would open http://$file - TQString currentDir; - if (m_currentView && m_currentView->url().isLocalFile()) - currentDir = m_currentView->url().path(1); - dlg.urlRequester()->completionObject()->setDir( currentDir ); - dlg.urlRequester()->setMode( KFile::File | KFile::Directory | KFile::ExistingOnly ); - dlg.exec(); - const KURL& url = dlg.selectedURL(); - if (!url.isEmpty()) - openFilteredURL( url.url().stripWhiteSpace() ); -} - -void KonqMainWindow::slotToolFind() -{ - kdDebug(1202) << "KonqMainWindow::slotToolFind sender:" << TQT_TQOBJECT_CONST(sender())->className() << endl; - - if ( m_currentView && m_currentView->part()->inherits("KonqDirPart") ) - { - KonqDirPart* dirPart = static_cast(m_currentView->part()); - - if (!m_paFindFiles->isChecked()) - { - dirPart->slotFindClosed(); - return; - } - - KonqViewFactory factory = KonqFactory::createView( "Konqueror/FindPart" ); - if ( factory.isNull() ) - { - KMessageBox::error( this, i18n("Cannot create the find part, check your installation.") ); - m_paFindFiles->setChecked(false); - return; - } - - KParts::ReadOnlyPart* findPart = factory.create( m_currentView->frame(), "findPartWidget", dirPart, "findPart" ); - dirPart->setFindPart( findPart ); - - m_currentView->frame()->insertTopWidget( findPart->widget() ); - findPart->widget()->show(); - findPart->widget()->setFocus(); - - connect( dirPart, TQT_SIGNAL( findClosed(KonqDirPart *) ), - this, TQT_SLOT( slotFindClosed(KonqDirPart *) ) ); - } - else if ( TQT_TQOBJECT_CONST(sender())->inherits( "TDEAction" ) ) // don't go there if called by the singleShot below - { - KURL url; - if ( m_currentView && m_currentView->url().isLocalFile() ) - url = m_currentView->locationBarURL(); - else - url.setPath( TQDir::homeDirPath() ); - KonqMainWindow * mw = KonqMisc::createBrowserWindowFromProfile( - locate( "data", TQString::fromLatin1("konqueror/profiles/filemanagement") ), - "filemanagement", url, KParts::URLArgs(), true /* forbid "use html"*/ ); - mw->m_paFindFiles->setChecked(true); - // Delay it after the openURL call (hacky!) - TQTimer::singleShot( 1, mw, TQT_SLOT(slotToolFind())); - m_paFindFiles->setChecked(false); - } -} - -void KonqMainWindow::slotFindOpen( KonqDirPart * dirPart ) -{ - kdDebug(1202) << "KonqMainWindow::slotFindOpen " << dirPart << endl; - Q_ASSERT( m_currentView ); - Q_ASSERT( m_currentView->part() == dirPart ); - slotToolFind(); // lazy me -} - -void KonqMainWindow::slotFindClosed( KonqDirPart * dirPart ) -{ - kdDebug(1202) << "KonqMainWindow::slotFindClosed " << dirPart << endl; - KonqView * dirView = m_mapViews.find( dirPart ).data(); - Q_ASSERT(dirView); - kdDebug(1202) << "dirView=" << dirView << endl; - if ( dirView && dirView == m_currentView ) - m_paFindFiles->setEnabled( true ); - m_paFindFiles->setChecked(false); -} - -void KonqMainWindow::slotIconsChanged() -{ - //kdDebug(1202) << "KonqMainWindow::slotIconsChanged" << endl; - m_combo->updatePixmaps(); - m_pViewManager->updatePixmaps(); - setIcon( KonqPixmapProvider::self()->pixmapFor( m_combo->currentText() )); -} - -void KonqMainWindow::slotOpenWith() -{ - KURL::List lst; - lst.append( m_currentView->url() ); - - TQString serviceName = TQT_TQOBJECT_CONST(sender())->name(); - - TDETrader::OfferList offers = m_currentView->appServiceOffers(); - TDETrader::OfferList::ConstIterator it = offers.begin(); - TDETrader::OfferList::ConstIterator end = offers.end(); - for (; it != end; ++it ) - if ( (*it)->desktopEntryName() == serviceName ) - { - KRun::run( **it, lst ); - return; - } -} - -void KonqMainWindow::slotViewModeToggle( bool toggle ) -{ - if ( !toggle ) - return; - - TQString modeName = TQT_TQOBJECT_CONST(sender())->name(); - - if ( m_currentView->service()->desktopEntryName() == modeName ) - return; - - m_bViewModeToggled = true; - - m_currentView->stop(); - m_currentView->lockHistory(); - - // Save those, because changeViewMode will lose them - KURL url = m_currentView->url(); - TQString locationBarURL = m_currentView->locationBarURL(); - TQStringList filesToSelect; - if( m_currentView->part()->inherits( "KonqDirPart" ) ) { - KFileItemList fileItemsToSelect = static_cast(m_currentView->part())->selectedFileItems(); - KFileItemListIterator it( fileItemsToSelect ); - while( it.current() ){ - filesToSelect += it.current()->name(); - ++it; - } - } - - - bool bQuickViewModeChange = false; - - // iterate over all services, update the toolbar service map - // and check if we can do a quick property-based viewmode change - const TDETrader::OfferList offers = m_currentView->partServiceOffers(); - TDETrader::OfferList::ConstIterator oIt = offers.begin(); - TDETrader::OfferList::ConstIterator oEnd = offers.end(); - const TQString currentServiceKey = viewModeActionKey( m_currentView->service() ); - for (; oIt != oEnd; ++oIt ) - { - KService::Ptr service = *oIt; - - if ( service->desktopEntryName() == modeName ) - { - // we changed the viewmode of either iconview or listview - // -> update the service in the corresponding map, so that - // we can set the correct text, icon, etc. properties to the - // KonqViewModeAction when rebuilding the view-mode actions in - // updateViewModeActions - // (I'm saying iconview/listview here, but theoretically it could be - // any view :) - const TQString serviceKey = viewModeActionKey( service ); - m_viewModeToolBarServices[ serviceKey ] = service; - - if ( serviceKey == currentServiceKey ) - { - TQVariant modeProp = service->property( "X-TDE-BrowserView-ModeProperty" ); - TQVariant modePropValue = service->property( "X-TDE-BrowserView-ModePropertyValue" ); - if ( !modeProp.isValid() || !modePropValue.isValid() ) - break; - - m_currentView->part()->setProperty( modeProp.toString().latin1(), modePropValue ); - - KService::Ptr oldService = m_currentView->service(); - - // we aren't going to re-build the viewmode actions but instead of a - // quick viewmode change (iconview) -> find the iconview-konqviewmode - // action and set new text,icon,etc. properties, to show the new - // current viewmode - TQPtrListIterator it( m_toolBarViewModeActions ); - for (; it.current(); ++it ) - if ( TQString::fromLatin1( it.current()->name() ) == oldService->desktopEntryName() ) - { - assert( it.current()->inherits( "KonqViewModeAction" ) ); - - KonqViewModeAction *action = static_cast( it.current() ); - - action->setChecked( true ); - TQString servicename = service->genericName(); - if (servicename.isEmpty()) - servicename = service->name(); - action->setText( servicename ); - action->setIcon( service->icon() ); - action->setName( service->desktopEntryName().ascii() ); - - break; - } - - m_currentView->setService( service ); - - bQuickViewModeChange = true; - break; - } - } - } - - if ( !bQuickViewModeChange ) - { - m_currentView->changeViewMode( m_currentView->serviceType(), modeName ); - KURL locURL = KURL::fromPathOrURL( locationBarURL ); - TQString nameFilter = detectNameFilter( locURL ); - if( m_currentView->part()->inherits( "KonqDirPart" ) ) - static_cast( m_currentView->part() )->setFilesToSelect( filesToSelect ); - m_currentView->openURL( locURL, locationBarURL, nameFilter ); - } - - // Now save this setting, either locally or globally (for directories only) - // (We don't have views with viewmodes other than for dirs currently; - // once we do, we might want to implement per-mimetype global-saving) - if ( m_bSaveViewPropertiesLocally && m_currentView->supportsServiceType( "inode/directory" ) ) - { - KURL u ( m_currentView->url() ); - u.addPath(".directory"); - if ( u.isLocalFile() ) - { - KSimpleConfig config( u.path() ); // if we have no write access, just drop it - config.setGroup( "URL properties" ); - config.writeEntry( "ViewMode", modeName ); - config.sync(); - } - } else - { - // We save the global view mode only if the view is a built-in view - if ( m_currentView->isBuiltinView() ) - { - KonqSettings::setMainViewViewMode( modeName ); - KonqSettings::writeConfig(); - } - } -} - -void KonqMainWindow::showHTML( KonqView * _view, bool b, bool _activateView ) -{ - // Save this setting, either locally or globally - // This has to be done before calling openView since it relies on it - if ( m_bSaveViewPropertiesLocally ) - { - KURL u ( b ? _view->url() : KURL( _view->url().directory() ) ); - u.addPath(".directory"); - if ( u.isLocalFile() ) - { - KSimpleConfig config( u.path() ); // No checks for access - config.setGroup( "URL properties" ); - config.writeEntry( "HTMLAllowed", b ); - config.sync(); - } - } else - { - KonqSettings::setHtmlAllowed( b ); - KonqSettings::writeConfig(); - if ( _activateView ) - m_bHTMLAllowed = b; - } - - if ( b && _view->supportsServiceType( "inode/directory" ) ) - { - _view->lockHistory(); - openView( "inode/directory", _view->url(), _view ); - } - else if ( !b && _view->supportsServiceType( "text/html" ) ) - { - KURL u( _view->url() ); - TQString fileName = u.fileName().lower(); - if ( KProtocolInfo::supportsListing( u ) && fileName.startsWith("index.htm") ) { - _view->lockHistory(); - u.setPath( u.directory() ); - openView( "inode/directory", u, _view ); - } - } -} - -void KonqMainWindow::slotShowHTML() -{ - bool b = !m_currentView->allowHTML(); - - m_currentView->stop(); - m_currentView->setAllowHTML( b ); - showHTML( m_currentView, b, true ); //current view - m_pViewManager->showHTML(b ); - -} - -void KonqMainWindow::setShowHTML( bool b ) -{ - m_bHTMLAllowed = b; - if ( m_currentView ) - m_currentView->setAllowHTML( b ); - m_ptaUseHTML->setChecked( b ); -} - -void KonqMainWindow::slotLockView() -{ - m_currentView->setLockedLocation( m_paLockView->isChecked() ); -} - -void KonqMainWindow::slotStop() -{ - abortLoading(); - if ( m_currentView ) - { - m_currentView->frame()->statusbar()->message( i18n("Canceled.") ); - } -} - -void KonqMainWindow::slotLinkView() -{ - // Can't access this action in passive mode anyway - assert(!m_currentView->isPassiveMode()); - bool mode = !m_currentView->isLinkedView(); - - if (linkableViewsCount() == 2) - { - // Exactly two linkable views : link both - KonqMainWindow::MapViews::ConstIterator it = viewMap().begin(); - if( (*it)->isFollowActive() ) // skip sidebar - ++it; - (*it)->setLinkedView( mode ); - ++it; - if( (*it)->isFollowActive() ) // skip sidebar - ++it; - (*it)->setLinkedView( mode ); - } - else // Normal case : just this view - m_currentView->setLinkedView( mode ); -} - -void KonqMainWindow::slotReload( KonqView* reloadView ) -{ - if ( !reloadView ) - reloadView = m_currentView; - - if ( !reloadView || reloadView->url().isEmpty() ) - return; - - if ( reloadView->part() && (reloadView->part()->metaObject()->findProperty("modified") != -1) ) { - TQVariant prop = reloadView->part()->property("modified"); - if (prop.isValid() && prop.toBool()) - if ( KMessageBox::warningContinueCancel( this, - i18n("This page contains changes that have not been submitted.\nReloading the page will discard these changes."), - i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"reload"), "discardchangesreload") != KMessageBox::Continue ) - return; - } - - KonqOpenURLRequest req( reloadView->typedURL() ); - req.userRequestedReload = true; - if ( reloadView->prepareReload( req.args ) ) - { - reloadView->lockHistory(); - // Reuse current servicetype for local files, but not for remote files (it could have changed, e.g. over HTTP) - TQString serviceType = reloadView->url().isLocalFile() ? reloadView->serviceType() : TQString::null; - openURL( reloadView, reloadView->url(), serviceType, req ); - } -} - -void KonqMainWindow::slotReloadStop() { - if (m_paReloadStop->icon() == "reload") { - slotReload(); - toggleReloadStopButton(true); - } else { - slotStop(); - toggleReloadStopButton(false); - } -} - -void KonqMainWindow::toggleReloadStopButton(bool isReload) { - //m_paStop = new TDEAction( i18n( "&Stop" ), "process-stop", Key_Escape, this, TQT_SLOT( slotStop() ), actionCollection(), "stop" ); - if (isReload) { - m_paReloadStop->setIcon("process-stop"); - m_paReloadStop->setWhatsThis( i18n( "Stop loading the document

" - "All network transfers will be stopped and Konqueror will display the content " - "that has been received so far." ) ); - m_paReloadStop->setToolTip( i18n( "Stop loading the document" ) ); - //m_paReloadStop = new TDEAction( i18n( "&Reload" ), "reload", reloadShortcut, this, TQT_SLOT( slotReloadStop() ), actionCollection(), "reload" ); - } else { - m_paReloadStop->setIcon("reload"); - m_paReloadStop->setWhatsThis( i18n( "Reload the currently displayed document

" - "This may, for example, be needed to refresh webpages that have been " - "modified since they were loaded, in order to make the changes visible." ) ); - m_paReloadStop->setToolTip( i18n( "Reload the currently displayed document" ) ); - } -} - -void KonqMainWindow::slotReloadPopup() -{ - if (m_pWorkingTab) - slotReload( m_pWorkingTab->activeChildView() ); -} - -void KonqMainWindow::slotHome(TDEAction::ActivationReason, TQt::ButtonState state) -{ - TQString homeURL = m_pViewManager->profileHomeURL(); - - if (homeURL.isEmpty()) - homeURL = KonqFMSettings::settings()->homeURL(); - - KonqOpenURLRequest req; - req.newTab = true; - req.newTabInFront = KonqSettings::newTabsInFront(); - - if (state & TQt::ShiftButton) - req.newTabInFront = !req.newTabInFront; - - if( state & TQt::ControlButton ) // Ctrl Left/MMB - openFilteredURL( homeURL, req); - else if( state & Qt::MidButton ) - { - if(KonqSettings::mmbOpensTab()) - openFilteredURL( homeURL, req); - else - { - KURL finalURL = KonqMisc::konqFilteredURL( this, homeURL ); - KonqMisc::createNewWindow( finalURL.url() ); - } - } - else - openFilteredURL( homeURL, false ); -} - - -void KonqMainWindow::slotHome() -{ - slotHome(TDEAction::UnknownActivation, Qt::LeftButton); -} - -void KonqMainWindow::slotGoSystem() -{ - openURL( 0L, KURL( "system:/" ) ); -} - -void KonqMainWindow::slotGoApplications() -{ - openURL( 0L, KURL( "programs:/" ) ); -} - -void KonqMainWindow::slotGoMedia() -{ - openURL( 0L, KURL( "media:/" ) ); -} - -void KonqMainWindow::slotGoNetworkFolders() -{ - openURL( 0L, KURL( "remote:/" ) ); -} - -void KonqMainWindow::slotGoSettings() -{ - openURL( 0L, KURL( "settings:/" ) ); -} - -void KonqMainWindow::slotGoDirTree() -{ - KURL u; - u.setPath( locateLocal( "data", "konqueror/dirtree/" ) ); - openURL( 0L, u ); -} - -void KonqMainWindow::slotGoTrash() -{ - openURL( 0L, KURL( "trash:/" ) ); -} - -void KonqMainWindow::slotGoAutostart() -{ - KURL u; - u.setPath( TDEGlobalSettings::autostartPath() ); - openURL( 0L, u ); -} - -void KonqMainWindow::slotGoHistory() -{ - TDEAction *a = m_toggleViewGUIClient->action("konq_sidebartng"); - if (!a) { - KMessageBox::sorry(0L, i18n("Your sidebar is not functional or unavailable."), i18n("Show History Sidebar")); - return; - } - - // Show the sidebar - if (!static_cast(a)->isChecked()) { - a->activate(); - TQTimer::singleShot( 0, this, TQT_SLOT(slotGoHistory())); - return; - } - - // Tell it to show the history plugin - MapViews::ConstIterator it; - for (it = viewMap().begin(); it != viewMap().end(); ++it) { - KonqView *view = it.data(); - if (view) { - KService::Ptr svc = view->service(); - if (svc->desktopEntryName() == "konq_sidebartng") { - if (!view->part()->openURL("sidebar:history.desktop")) - KMessageBox::sorry(0L, i18n("Cannot find running history plugin in your sidebar."), i18n("Show History Sidebar")); - break; - } - } - } -} - -TQStringList KonqMainWindow::configModules() const -{ - return m_configureModules; -} - -void KonqMainWindow::slotConfigureExtensions() -{ - KonqExtensionManager extensionManager(0, this, m_currentView ? m_currentView->part() : 0); - extensionManager.exec(); -} - -void KonqMainWindow::slotConfigure() -{ - if( !m_configureDialog ) - { - m_configureDialog = new KCMultiDialog( this, "configureDialog" ); - - TQStringList modules = configModules(); - TQStringList::ConstIterator end( modules.end() ); - - for( TQStringList::ConstIterator it = modules.begin(); - it != end; ++it ) - { - if ( kapp->authorizeControlModule( *it ) ) - { - m_configureDialog->addModule( *it ); - } - } - - } - - m_configureDialog->show(); - -} - -void KonqMainWindow::slotConfigureSpellChecking() -{ - TDEApplication::startServiceByDesktopName("spellchecking"); -} - -void KonqMainWindow::slotConfigureToolbars() -{ - if ( autoSaveSettings() ) - saveMainWindowSettings( TDEGlobal::config(), "KonqMainWindow" ); - KEditToolbar dlg(factory()); - connect(&dlg,TQT_SIGNAL(newToolbarConfig()),this,TQT_SLOT(slotNewToolbarConfig())); - connect(&dlg,TQT_SIGNAL(newToolbarConfig()),this,TQT_SLOT(initBookmarkBar())); - dlg.exec(); -} - -void KonqMainWindow::slotNewToolbarConfig() // This is called when OK or Apply is clicked -{ - if ( m_toggleViewGUIClient ) - plugActionList( TQString::fromLatin1( "toggleview" ), m_toggleViewGUIClient->actions() ); - if ( m_currentView && m_currentView->appServiceOffers().count() > 0 ) - plugActionList( "openwith", m_openWithActions ); - - plugViewModeActions(); - - applyMainWindowSettings( TDEGlobal::config(), "KonqMainWindow" ); -} - -void KonqMainWindow::slotUndoAvailable( bool avail ) -{ - bool enable = false; - - if ( avail && m_currentView && m_currentView->part() ) - { - // Avoid tqWarning from TQObject::property if it doesn't exist - if ( m_currentView->part()->metaObject()->findProperty( "supportsUndo" ) != -1 ) - { - TQVariant prop = m_currentView->part()->property( "supportsUndo" ); - if ( prop.isValid() && prop.toBool() ) - enable = true; - } - } - - m_paUndo->setEnabled( enable ); -} - -void KonqMainWindow::slotPartChanged( KonqView *childView, KParts::ReadOnlyPart *oldPart, KParts::ReadOnlyPart *newPart ) -{ - kdDebug(1202) << "KonqMainWindow::slotPartChanged" << endl; - m_mapViews.remove( oldPart ); - m_mapViews.insert( newPart, childView ); - - // Remove the old part, and add the new part to the manager - // Note: this makes the new part active... so it calls slotPartActivated - - m_pViewManager->replacePart( oldPart, newPart, false ); - // Set active immediately - m_pViewManager->setActivePart( newPart, true ); - - viewsChanged(); -} - - -void KonqMainWindow::slotRunFinished() -{ - kdDebug(1202) << "KonqMainWindow::slotRunFinished()" << endl; - const KonqRun *run = static_cast( sender() ); - - if ( run == m_initialKonqRun ) - m_initialKonqRun = 0L; - - if ( !run->mailtoURL().isEmpty() ) - { - kapp->invokeMailer( run->mailtoURL() ); - } - - if ( run->hasError() ) { // we had an error - TQByteArray data; - TQDataStream s( data, IO_WriteOnly ); - s << run->url().prettyURL() << kapp->dcopClient()->defaultObject(); - kapp->dcopClient()->send( "konqueror*", "KonquerorIface", - "removeFromCombo(TQString,TQCString)", data); - } - - KonqView *childView = run->childView(); - - // Check if we found a mimetype _and_ we got no error (example: cancel in openwith dialog) - if ( run->foundMimeType() && !run->hasError() ) - { - - // We do this here and not in the constructor, because - // we are waiting for the first view to be set up before doing this... - // Note: this is only used when konqueror is started from command line..... - if ( m_bNeedApplyKonqMainWindowSettings ) - { - m_bNeedApplyKonqMainWindowSettings = false; // only once - applyKonqMainWindowSettings(); - } - - return; - } - - if ( childView ) - { - childView->setLoading( false ); - - if ( childView == m_currentView ) - { - stopAnimation(); - - // Revert to working URL - unless the URL was typed manually - kdDebug(1202) << " typed URL = " << run->typedURL() << endl; - if ( run->typedURL().isEmpty() && childView->history().current() ) // not typed - childView->setLocationBarURL( childView->history().current()->locationBarURL ); - } - } - else // No view, e.g. empty webbrowsing profile - stopAnimation(); -} - -void KonqMainWindow::applyKonqMainWindowSettings() -{ - TQStringList toggableViewsShown = KonqSettings::toggableViewsShown(); - TQStringList::ConstIterator togIt = toggableViewsShown.begin(); - TQStringList::ConstIterator togEnd = toggableViewsShown.end(); - for ( ; togIt != togEnd ; ++togIt ) - { - // Find the action by name - // TDEAction * act = m_toggleViewGUIClient->actionCollection()->action( (*togIt).latin1() ); - TDEAction *act = m_toggleViewGUIClient->action( *togIt ); - if ( act ) - act->activate(); - else - kdWarning(1202) << "Unknown toggable view in ToggableViewsShown " << *togIt << endl; - } -} - -void KonqMainWindow::slotSetStatusBarText( const TQString & ) -{ - // Reimplemented to disable KParts::MainWindow default behaviour - // Does nothing here, see konq_frame.cc -} - -void KonqMainWindow::slotViewCompleted( KonqView * view ) -{ - assert( view ); - - // Need to update the current working directory - // of the completion object every time the user - // changes the directory!! (DA) - if( m_pURLCompletion ) - { - KURL u( view->locationBarURL() ); - if( u.isLocalFile() ) - m_pURLCompletion->setDir( u.path() ); - else - m_pURLCompletion->setDir( u.url() ); //needs work!! (DA) - } -} - -void KonqMainWindow::slotPartActivated( KParts::Part *part ) -{ - kdDebug(1202) << "KonqMainWindow::slotPartActivated " << part << " " - << ( part && part->instance() && part->instance()->aboutData() ? part->instance()->aboutData()->appName() : "" ) << endl; - - KonqView *newView = 0; - KonqView *oldView = m_currentView; - - if ( part ) - { - newView = m_mapViews.find( static_cast( part ) ).data(); - - if ( newView->isPassiveMode() ) - { - // Passive view. Don't connect anything, don't change m_currentView - // Another view will become the current view very soon - kdDebug(1202) << "KonqMainWindow::slotPartActivated: Passive mode - return" << endl; - return; - } - } - - KParts::BrowserExtension *ext = 0; - - if ( oldView ) - { - ext = oldView->browserExtension(); - if ( ext ) - { - //kdDebug(1202) << "Disconnecting extension for view " << oldView << endl; - disconnectExtension( ext ); - } - - if ( oldView->part() ) - { - TDEActionCollection *coll = oldView->part()->actionCollection(); - if ( coll ) - disconnectActionCollection( coll ); - } - } - - kdDebug(1202) << "KonqMainWindow::slotPartActivated: New current view " << newView << endl; - m_currentView = newView; - if ( !part ) - { - kdDebug(1202) << "KonqMainWindow::slotPartActivated: No part activated - returning" << endl; - unplugViewModeActions(); - createGUI( 0L ); - KParts::MainWindow::setCaption( "" ); - KParts::MainWindow::setIcon( kapp->icon()); - return; - } - - ext = m_currentView->browserExtension(); - - if ( ext ) - { - connectExtension( ext ); - } - else - { - kdDebug(1202) << "KonqMainWindow::slotPartActivated: No Browser Extension for the new part" << endl; - // Disable all browser-extension actions - - KParts::BrowserExtension::ActionSlotMap * actionSlotMap = KParts::BrowserExtension::actionSlotMapPtr(); - KParts::BrowserExtension::ActionSlotMap::ConstIterator it = actionSlotMap->begin(); - KParts::BrowserExtension::ActionSlotMap::ConstIterator itEnd = actionSlotMap->end(); - - for ( ; it != itEnd ; ++it ) - { - TDEAction * act = actionCollection()->action( static_cast(it.key()) ); - Q_ASSERT(act); - if (act) - act->setEnabled( false ); - } - - m_paCopyFiles->setEnabled( false ); - m_paMoveFiles->setEnabled( false ); - m_paNewDir->setEnabled( false ); - } - createGUI( part ); - - TDEActionCollection *coll = m_currentView->part()->actionCollection(); - if ( coll ) - connectActionCollection( coll ); - - // View-dependent GUI - - KParts::MainWindow::setCaption( m_currentView->caption() ); - m_currentView->frame()->setTitle( m_currentView->caption() , 0L); - updateOpenWithActions(); - updateLocalPropsActions(); - updateViewActions(); // undo, lock, link and other view-dependent actions - - if ( m_bViewModeToggled ) - { - // if we just toggled the view mode via the view mode actions, then - // we don't need to do all the time-taking stuff below (Simon) - const TQString currentServiceDesktopEntryName = m_currentView->service()->desktopEntryName(); - TQPtrListIterator it( m_viewModeActions ); - for (; it.current(); ++it ) { - if ( it.current()->name() == currentServiceDesktopEntryName ) { - it.current()->setChecked( true ); - break; - } - } - const TQString currentServiceLibrary = viewModeActionKey( m_currentView->service() ); - TQPtrListIterator ittb( m_toolBarViewModeActions ); - for (; ittb.current(); ++ittb ) { - KService::Ptr serv = KService::serviceByDesktopName( ittb.current()->name() ); - if ( serv && viewModeActionKey( serv ) == currentServiceLibrary ) { - TDEToggleAction* ta = static_cast( ittb.current() ); - ta->setChecked( false ); - TQString servicename = m_currentView->service()->genericName(); - if (servicename.isEmpty()) - servicename = m_currentView->service()->name(); - ta->setText( servicename ); - ta->setIcon( m_currentView->service()->icon() ); - ta->setName( m_currentView->service()->desktopEntryName().ascii() ) ; - break; - } - } - } - else - { - updateViewModeActions(); - } - - m_bViewModeToggled = false; - - - m_pMenuNew->setEnabled( m_currentView->supportsServiceType( "inode/directory" ) ); - - m_currentView->frame()->statusbar()->updateActiveStatus(); - - if ( oldView && oldView->frame() ) - oldView->frame()->statusbar()->updateActiveStatus(); - - //kdDebug(1202) << "KonqMainWindow::slotPartActivated: setting location bar url to " - // << m_currentView->locationBarURL() << " m_currentView=" << m_currentView << endl; - m_currentView->setLocationBarURL( m_currentView->locationBarURL() ); - - updateToolBarActions(); - - m_currentView->setActiveInstance(); -} - -void KonqMainWindow::insertChildView( KonqView *childView ) -{ - kdDebug(1202) << "KonqMainWindow::insertChildView " << childView << endl; - m_mapViews.insert( childView->part(), childView ); - - connect( childView, TQT_SIGNAL( viewCompleted( KonqView * ) ), - this, TQT_SLOT( slotViewCompleted( KonqView * ) ) ); - - if ( !m_pViewManager->isLoadingProfile() ) // see KonqViewManager::loadViewProfile - viewCountChanged(); - emit viewAdded( childView ); -} - -// Called by KonqViewManager, internal -void KonqMainWindow::removeChildView( KonqView *childView ) -{ - kdDebug(1202) << "KonqMainWindow::removeChildView childView " << childView << endl; - - disconnect( childView, TQT_SIGNAL( viewCompleted( KonqView * ) ), - this, TQT_SLOT( slotViewCompleted( KonqView * ) ) ); - -#ifndef NDEBUG - dumpViewList(); -#endif - - MapViews::Iterator it = m_mapViews.begin(); - MapViews::Iterator end = m_mapViews.end(); - - // find it in the map - can't use the key since childView->part() might be 0L - - kdDebug(1202) << "Searching map" << endl; - - while ( it != end && it.data() != childView ) - ++it; - - kdDebug(1202) << "Verifying search results" << endl; - - if ( it == m_mapViews.end() ) - { - kdWarning(1202) << "KonqMainWindow::removeChildView childView " << childView << " not in map !" << endl; - return; - } - - kdDebug(1202) << "Removing view " << childView << endl; - - m_mapViews.remove( it ); - - kdDebug(1202) << "View " << childView << " removed from map" << endl; - - viewCountChanged(); - emit viewRemoved( childView ); - -#ifndef NDEBUG - dumpViewList(); -#endif - - // KonqViewManager takes care of m_currentView -} - -void KonqMainWindow::viewCountChanged() -{ - // This is called when the number of views changes. - kdDebug(1202) << "KonqMainWindow::viewCountChanged" << endl; - - int lvc = linkableViewsCount(); - m_paLinkView->setEnabled( lvc > 1 ); - - // Only one view (or one view + sidebar) -> make it/them unlinked - if ( lvc == 1 ) { - MapViews::Iterator it = m_mapViews.begin(); - MapViews::Iterator end = m_mapViews.end(); - for (; it != end; ++it ) - it.data()->setLinkedView( false ); - } - - viewsChanged(); - - m_pViewManager->viewCountChanged(); -} - -void KonqMainWindow::viewsChanged() -{ - // This is called when the number of views changes OR when - // the type of some view changes. - - // Nothing here anymore, but don't cleanup, some might come back later. - - updateViewActions(); // undo, lock, link and other view-dependent actions -} - -KonqView * KonqMainWindow::childView( KParts::ReadOnlyPart *view ) -{ - MapViews::ConstIterator it = m_mapViews.find( view ); - if ( it != m_mapViews.end() ) - return it.data(); - else - return 0L; -} - -KonqView * KonqMainWindow::childView( KParts::ReadOnlyPart *callingPart, const TQString &name, KParts::BrowserHostExtension **hostExtension, KParts::ReadOnlyPart **part ) -{ - kdDebug() << "KonqMainWindow::childView this=" << this << " looking for " << name << endl; - - MapViews::ConstIterator it = m_mapViews.begin(); - MapViews::ConstIterator end = m_mapViews.end(); - for (; it != end; ++it ) - { - KonqView* view = it.data(); - TQString viewName = view->viewName(); - kdDebug() << " - viewName=" << viewName << " " - << "frame names:" << view->frameNames().join( "," ) << endl; - - // First look for a hostextension containing this frame name - KParts::BrowserHostExtension *ext = KParts::BrowserHostExtension::childObject( view->part() ); - if ( ext ) - { - ext = ext->findFrameParent(callingPart, name); - kdDebug() << "BrowserHostExtension found part " << ext << endl; - if (!ext) - continue; // Don't use this window - } - - if ( !viewName.isEmpty() && viewName == name ) - { - kdDebug() << "found existing view by name: " << view << endl; - if ( hostExtension ) - *hostExtension = 0; - if ( part ) - *part = view->part(); - return view; - } - -// KParts::BrowserHostExtension* ext = KonqView::hostExtension( view->part(), name ); - - if ( ext ) - { - TQPtrList frames = ext->frames(); - TQPtrListIterator frameIt( frames ); - for ( ; frameIt.current() ; ++frameIt ) - { - if ( frameIt.current()->name() == name ) - { - kdDebug() << "found a frame of name " << name << " : " << frameIt.current() << endl; - if ( hostExtension ) - *hostExtension = ext; - if ( part ) - *part = frameIt.current(); - return view; - } - } - } - } - - return 0; -} - -// static -KonqView * KonqMainWindow::findChildView( KParts::ReadOnlyPart *callingPart, const TQString &name, KonqMainWindow **mainWindow, KParts::BrowserHostExtension **hostExtension, KParts::ReadOnlyPart **part ) -{ - if ( !s_lstViews ) - return 0; - - TQPtrListIterator it( *s_lstViews ); - for (; it.current(); ++it ) - { - KonqView *res = it.current()->childView( callingPart, name, hostExtension, part ); - if ( res ) - { - if ( mainWindow ) - *mainWindow = it.current(); - return res; - } - } - - return 0; -} - -int KonqMainWindow::activeViewsCount() const -{ - int res = 0; - MapViews::ConstIterator it = m_mapViews.begin(); - MapViews::ConstIterator end = m_mapViews.end(); - for (; it != end; ++it ) - if ( !it.data()->isPassiveMode() ) - ++res; - - return res; -} - -int KonqMainWindow::linkableViewsCount() const -{ - int res = 0; - MapViews::ConstIterator it = m_mapViews.begin(); - MapViews::ConstIterator end = m_mapViews.end(); - for (; it != end; ++it ) - if ( !it.data()->isFollowActive() ) - ++res; - - return res; -} - -int KonqMainWindow::mainViewsCount() const -{ - int res = 0; - MapViews::ConstIterator it = m_mapViews.begin(); - MapViews::ConstIterator end = m_mapViews.end(); - for (; it != end; ++it ) - if ( !it.data()->isPassiveMode() && !it.data()->isToggleView() ) - { - //kdDebug(1202) << "KonqMainWindow::mainViewsCount " << res << " " << it.data() << " " << it.data()->part()->widget() << endl; - ++res; - } - - return res; -} - -KParts::ReadOnlyPart * KonqMainWindow::currentPart() const -{ - /// ### This is currently unused. Check in the final version (!) if still unused. - if ( m_currentView ) - return m_currentView->part(); - else - return 0L; -} - -void KonqMainWindow::customEvent( TQCustomEvent *event ) -{ - KParts::MainWindow::customEvent( event ); - - if ( KonqFileSelectionEvent::test( event ) || - KonqFileMouseOverEvent::test( event ) ) - { - // Forward the event to all views - MapViews::ConstIterator it = m_mapViews.begin(); - MapViews::ConstIterator end = m_mapViews.end(); - for (; it != end; ++it ) - TQApplication::sendEvent( (*it)->part(), event ); - return; - } - if ( KParts::OpenURLEvent::test( event ) ) - { - KParts::OpenURLEvent * ev = static_cast(event); - KonqView * senderChildView = childView(ev->part()); - - // Enable/disable local properties actions if current view - if ( senderChildView == m_currentView ) - updateLocalPropsActions(); - - // Forward the event to all views - MapViews::ConstIterator it = m_mapViews.begin(); - MapViews::ConstIterator end = m_mapViews.end(); - for (; it != end; ++it ) - { - // Don't resend to sender - if (it.key() != ev->part()) - { - //kdDebug(1202) << "Sending event to view " << it.key()->className() << endl; - TQApplication::sendEvent( it.key(), event ); - - } - } - } -} - -void KonqMainWindow::updateLocalPropsActions() -{ - bool canWrite = false; - if ( m_currentView && m_currentView->url().isLocalFile() ) - { - // Can we write ? - TQFileInfo info( m_currentView->url().path() ); - canWrite = info.isDir() && info.isWritable(); - } - m_paSaveViewPropertiesLocally->setEnabled( canWrite ); - m_paRemoveLocalProperties->setEnabled( canWrite ); -} - -void KonqMainWindow::slotURLEntered( const TQString &text, int state ) -{ - if ( m_bURLEnterLock || text.isEmpty() ) - return; - - m_bURLEnterLock = true; - - if (state & ControlButton || state & AltButton) - { - m_combo->setURL( m_currentView ? m_currentView->url().prettyURL() : TQString::null ); - openFilteredURL( text.stripWhiteSpace(), true ); - } - else - openFilteredURL( text.stripWhiteSpace() ); - - m_bURLEnterLock = false; -} - -void KonqMainWindow::slotFileNewAboutToShow() -{ - // As requested by KNewMenu : - m_pMenuNew->slotCheckUpToDate(); - // And set the files that the menu apply on : - m_pMenuNew->setPopupFiles( KURL( m_currentView->url().url() ) ); -} - -void KonqMainWindow::slotSplitViewHorizontal() -{ - KonqView * newView = m_pViewManager->splitView( Qt::Horizontal ); - if (newView == 0L) return; - newView->openURL( m_currentView->url(), m_currentView->locationBarURL() ); -} - -void KonqMainWindow::slotSplitViewVertical() -{ - KonqView * newView = m_pViewManager->splitView( Qt::Vertical ); - if (newView == 0L) return; - newView->openURL( m_currentView->url(), m_currentView->locationBarURL() ); -} - -void KonqMainWindow::slotAddTab() -{ - KonqView* newView = m_pViewManager->addTab(TQString("text/html"), // this is what about:blank will use anyway - TQString::null, - false, - KonqSettings::openAfterCurrentPage()); - if (newView == 0L) return; - openURL( newView, KURL("about:blank"),TQString::null); - m_pViewManager->showTab( newView ); - focusLocationBar(); - m_pWorkingTab = 0L; -} - -void KonqMainWindow::slotDuplicateTab() -{ - m_pViewManager->duplicateTab( 0, KonqSettings::openAfterCurrentPage() ); -} - -void KonqMainWindow::slotDuplicateTabPopup() -{ - m_pViewManager->duplicateTab( m_pWorkingTab, KonqSettings::openAfterCurrentPage() ); -} - -void KonqMainWindow::slotBreakOffTab() -{ - if (m_currentView && m_currentView->part() && - (m_currentView->part()->metaObject()->findProperty("modified") != -1) ) { - TQVariant prop = m_currentView->part()->property("modified"); - if (prop.isValid() && prop.toBool()) - if ( KMessageBox::warningContinueCancel( this, - i18n("This tab contains changes that have not been submitted.\nDetaching the tab will discard these changes."), - i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"tab_breakoff"), "discardchangesdetach") != KMessageBox::Continue ) - return; - } - - m_pViewManager->breakOffTab(); - updateViewActions(); -} - -void KonqMainWindow::slotBreakOffTabPopup() -{ - KonqView* originalView = m_currentView; - KonqView *view = m_pWorkingTab->activeChildView(); - if (view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1) ) { - TQVariant prop = view->part()->property("modified"); - if (prop.isValid() && prop.toBool()) { - m_pViewManager->showTab( view ); - if ( KMessageBox::warningContinueCancel( this, - i18n("This tab contains changes that have not been submitted.\nDetaching the tab will discard these changes."), - i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"tab_breakoff"), "discardchangesdetach") != KMessageBox::Continue ) - { - m_pViewManager->showTab( originalView ); - return; - } - } - } - m_pViewManager->showTab( originalView ); - - //Can't do this safely here as the tabbar may disappear and we're - //hanging off here. - TQTimer::singleShot(0, this, TQT_SLOT( slotBreakOffTabPopupDelayed() ) ); -} - -void KonqMainWindow::slotBreakOffTabPopupDelayed() -{ - m_pViewManager->breakOffTab( m_pWorkingTab ); - updateViewActions(); -} - -void KonqMainWindow::slotPopupNewWindow() -{ - kdDebug(1202) << "KonqMainWindow::slotPopupNewWindow()" << endl; - - KFileItemListIterator it ( popupItems ); - for ( ; it.current(); ++it ) - { - KonqMisc::createNewWindow( (*it)->url(), popupUrlArgs ); - } -} - -void KonqMainWindow::slotPopupThisWindow() -{ - kdDebug(1202) << "KonqMainWindow::slotPopupThisWindow()" << endl; - - openURL( 0L, popupItems.getFirst()->url() ); -} - -void KonqMainWindow::slotPopupNewTabAtFront() -{ - TDEConfig *config = TDEGlobal::config(); - TDEConfigGroupSaver cs( config, TQString::fromLatin1("FMSettings") ); - bool openAfterCurrentPage = config->readBoolEntry( "OpenAfterCurrentPage", false ); - popupNewTab(true, openAfterCurrentPage); -} - -void KonqMainWindow::slotPopupNewTab() -{ - bool openAfterCurrentPage = KonqSettings::openAfterCurrentPage(); - bool newTabsInFront = KonqSettings::newTabsInFront(); - - if (TDEApplication::keyboardMouseState() & TQt::ShiftButton) - newTabsInFront = !newTabsInFront; - - popupNewTab(newTabsInFront, openAfterCurrentPage); -} - -void KonqMainWindow::slotPopupNewTabRight() -{ - bool newTabsInFront = KonqSettings::newTabsInFront(); - - if (TDEApplication::keyboardMouseState() & ShiftButton) - newTabsInFront = !newTabsInFront; - - popupNewTab(newTabsInFront, false); -} - -void KonqMainWindow::popupNewTab(bool infront, bool openAfterCurrentPage) -{ - kdDebug(1202) << "KonqMainWindow::popupNewTab()" << endl; - - KFileItemListIterator it ( popupItems ); - KonqOpenURLRequest req; - req.newTab = true; - req.newTabInFront = false; - req.openAfterCurrentPage = openAfterCurrentPage; - req.args = popupUrlArgs; - - for ( ; it.current(); ++it ) - { - if ( infront && it.atLast() ) - { - req.newTabInFront = true; - } - openURL( 0L, (*it)->url(), TQString::null, req ); - } -} - -void KonqMainWindow::openMultiURL( KURL::List url ) -{ - KURL::List::ConstIterator it = url.begin(); - KURL::List::ConstIterator end = url.end(); - for (; it != end; ++it ) - { - KonqView* newView = m_pViewManager->addTab(); - Q_ASSERT( newView ); - if (newView == 0L) continue; - openURL( newView, *it,TQString::null); - m_pViewManager->showTab( newView ); - focusLocationBar(); - m_pWorkingTab = 0L; - } -} - -void KonqMainWindow::slotRemoveView() -{ - if (m_currentView && m_currentView->part() && - (m_currentView->part()->metaObject()->findProperty("modified") != -1) ) { - TQVariant prop = m_currentView->part()->property("modified"); - if (prop.isValid() && prop.toBool()) - if ( KMessageBox::warningContinueCancel( this, - i18n("This view contains changes that have not been submitted.\nClosing the view will discard these changes."), - i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"view_remove"), "discardchangesclose") != KMessageBox::Continue ) - return; - } - - // takes care of choosing the new active view - m_pViewManager->removeView( m_currentView ); -} - -void KonqMainWindow::slotRemoveTab() -{ - if (m_currentView && m_currentView->part() && - (m_currentView->part()->metaObject()->findProperty("modified") != -1) ) { - TQVariant prop = m_currentView->part()->property("modified"); - if (prop.isValid() && prop.toBool()) - if ( KMessageBox::warningContinueCancel( this, - i18n("This tab contains changes that have not been submitted.\nClosing the tab will discard these changes."), - i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"tab_remove"), "discardchangesclose") != KMessageBox::Continue ) - return; - } - - m_pViewManager->removeTab(); -} - -void KonqMainWindow::slotRemoveTabPopup() -{ - KonqView *originalView = m_currentView; - KonqView *view = m_pWorkingTab->activeChildView(); - if (view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1) ) { - TQVariant prop = view->part()->property("modified"); - if (prop.isValid() && prop.toBool()) { - m_pViewManager->showTab( view ); - if ( KMessageBox::warningContinueCancel( this, - i18n("This tab contains changes that have not been submitted.\nClosing the tab will discard these changes."), - i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"tab_remove"), "discardchangesclose") != KMessageBox::Continue ) - { - m_pViewManager->showTab( originalView ); - return; - } - } - m_pViewManager->showTab( originalView ); - } - - //Can't do immediately - may kill the tabbar, and we're in an event path down from it - TQTimer::singleShot( 0, this, TQT_SLOT( slotRemoveTabPopupDelayed() ) ); -} - -void KonqMainWindow::slotRemoveTabPopupDelayed() -{ - m_pViewManager->removeTab( m_pWorkingTab ); -} - -void KonqMainWindow::slotRemoveOtherTabsPopup() -{ - if ( KMessageBox::warningContinueCancel( this, - i18n("Do you really want to close all other tabs?"), - i18n("Close Other Tabs Confirmation"), KGuiItem(i18n("Close &Other Tabs"),"tab_remove_other"), - "CloseOtherTabConfirm") != KMessageBox::Continue ) - return; - - KonqView *originalView = m_currentView; - MapViews::ConstIterator it = m_mapViews.begin(); - MapViews::ConstIterator end = m_mapViews.end(); - for (; it != end; ++it ) { - KonqView *view = it.data(); - if ( view != originalView && view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1) ) { - TQVariant prop = view->part()->property("modified"); - if (prop.isValid() && prop.toBool()) { - m_pViewManager->showTab( view ); - if ( KMessageBox::warningContinueCancel( this, - i18n("This tab contains changes that have not been submitted.\nClosing other tabs will discard these changes."), - i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"tab_remove"), "discardchangescloseother") != KMessageBox::Continue ) - { - m_pViewManager->showTab( originalView ); - return; - } - } - } - } - m_pViewManager->showTab( originalView ); - - //Can't do immediately - kills the tabbar, and we're in an event path down from it - TQTimer::singleShot( 0, this, TQT_SLOT( slotRemoveOtherTabsPopupDelayed() ) ); -} - -void KonqMainWindow::slotRemoveOtherTabsPopupDelayed() -{ - m_pViewManager->removeOtherTabs( m_pWorkingTab ); - updateViewActions(); -} - -void KonqMainWindow::slotReloadAllTabs() -{ - KonqView *originalView = m_currentView; - MapViews::ConstIterator it = m_mapViews.begin(); - MapViews::ConstIterator end = m_mapViews.end(); - for (; it != end; ++it ) { - KonqView *view = it.data(); - if (view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1) ) { - TQVariant prop = view->part()->property("modified"); - if (prop.isValid() && prop.toBool()) { - m_pViewManager->showTab( view ); - if ( KMessageBox::warningContinueCancel( this, - i18n("This tab contains changes that have not been submitted.\nReloading all tabs will discard these changes."), - i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"reload"), "discardchangesreload") != KMessageBox::Continue ) - { - m_pViewManager->showTab( originalView ); - return; - } - } - } - } - m_pViewManager->showTab( originalView ); - - m_pViewManager->reloadAllTabs(); - updateViewActions(); -} - - -void KonqMainWindow::slotActivateNextTab() -{ - m_pViewManager->activateNextTab(); -} - -void KonqMainWindow::slotActivatePrevTab() -{ - m_pViewManager->activatePrevTab(); -} - -void KonqMainWindow::slotActivateTab() -{ - m_pViewManager->activateTab( TQString( TQT_TQOBJECT_CONST(sender())->name() ).right( 2 ).toInt() -1 ); -} - -void KonqMainWindow::slotDumpDebugInfo() -{ -#ifndef NDEBUG - dumpViewList(); - m_pViewManager->printFullHierarchy( 0L ); -#endif -} - -void KonqMainWindow::slotSaveViewPropertiesLocally() -{ - m_bSaveViewPropertiesLocally = !m_bSaveViewPropertiesLocally; - // And this is a main-view setting, so save it - KonqSettings::setSaveViewPropertiesLocally( m_bSaveViewPropertiesLocally ); - KonqSettings::writeConfig(); - // Now tell the views - MapViews::ConstIterator it = m_mapViews.begin(); - MapViews::ConstIterator end = m_mapViews.end(); - for (; it != end; ++it ) - (*it)->callExtensionBoolMethod( "setSaveViewPropertiesLocally(bool)", m_bSaveViewPropertiesLocally ); -} - -void KonqMainWindow::slotRemoveLocalProperties() -{ - assert( m_currentView ); - KURL u ( m_currentView->url() ); - u.addPath(".directory"); - if ( u.isLocalFile() ) - { - TQFile f( u.path() ); - if ( f.open(IO_ReadWrite) ) - { - f.close(); - KSimpleConfig config( u.path() ); - config.deleteGroup( "URL properties" ); // Bye bye - config.sync(); - // TODO: Notify the view... - // Or the hard way: (and hoping it doesn't cache the values!) - slotReload(); - } else - { - Q_ASSERT( TQFile::exists(u.path()) ); // The action shouldn't be enabled, otherwise. - KMessageBox::sorry( this, i18n("No permissions to write to %1").arg(u.path()) ); - } - } -} - -bool KonqMainWindow::askForTarget(const TQString& text, KURL& url) -{ - const KURL initialUrl = (viewCount()==2) ? otherView(m_currentView)->url() : m_currentView->url(); - TQString label = text.arg( m_currentView->url().pathOrURL() ); - KURLRequesterDlg dlg(initialUrl.pathOrURL(), label, this, "urlrequester", true); - dlg.setCaption(i18n("Enter Target")); - dlg.urlRequester()->setMode( KFile::File | KFile::ExistingOnly | KFile::Directory ); - if (dlg.exec()) - { - url = dlg.selectedURL(); - if ( url.isValid() ) - return true; - else - { - KMessageBox::error( this, i18n("%1 is not valid").arg(url.url())); - return false; - } - } - return false; -} - -void KonqMainWindow::slotRequesterClicked( KURLRequester *req ) -{ - req->fileDialog()->setMode(KFile::Directory|KFile::ExistingOnly); -} - -void KonqMainWindow::slotCopyFiles() -{ - //kdDebug(1202) << "KonqMainWindow::slotCopyFiles()" << endl; - KURL dest; - if (!askForTarget(i18n("Copy selected files from %1 to:"),dest)) - return; - - KonqOperations::copy(this,KonqOperations::COPY,currentURLs(),dest); -} - -void KonqMainWindow::slotMoveFiles() -{ - //kdDebug(1202) << "KonqMainWindow::slotMoveFiles()" << endl; - KURL dest; - if (!askForTarget(i18n("Move selected files from %1 to:"),dest)) - return; - - KonqOperations::copy(this,KonqOperations::MOVE,currentURLs(),dest); -} - -void KonqMainWindow::slotNewDir() -{ - Q_ASSERT( m_currentView ); - if ( m_currentView ) - KonqOperations::newDir(this, m_currentView->url()); -} - -KURL::List KonqMainWindow::currentURLs() const -{ - KURL::List urls; - if ( m_currentView ) - { - urls.append( m_currentView->url() ); - if ( m_currentView->part()->inherits("KonqDirPart") ) - { - KFileItemList tmpList= static_cast(m_currentView->part())->selectedFileItems(); - KFileItem *item=tmpList.first(); - if (item) // Return list of selected items only if we have a selection - { - urls.clear(); - for (; item!=0; item=tmpList.next()) - urls.append(item->url()); - } - } - } - return urls; -} - -// Only valid if there are one or two views -KonqView * KonqMainWindow::otherView( KonqView * view ) const -{ - assert( viewCount() <= 2 ); - MapViews::ConstIterator it = m_mapViews.begin(); - if ( (*it) == view ) - ++it; - if ( it != m_mapViews.end() ) - return (*it); - return 0L; -} - -void KonqMainWindow::slotSaveViewProfile() -{ -#if 0 - if ( m_pViewManager->currentProfile().isEmpty() ) - { - // The action should be disabled........... - kdWarning(1202) << "No known profile. Use the Save Profile dialog box" << endl; - } else { - - m_pViewManager->saveViewProfile( m_pViewManager->currentProfile(), - m_pViewManager->currentProfileText(), - false /* URLs */, true /* size */ ); - - } -#endif - m_pViewManager->showProfileDlg( m_pViewManager->currentProfile() ); -} - -void KonqMainWindow::slotUpAboutToShow() -{ - TQPopupMenu *popup = m_paUp->popupMenu(); - - popup->clear(); - - uint i = 0; - - // Use the location bar URL, because in case we display a index.html - // we want to go up from the dir, not from the index.html - KURL u( m_currentView->locationBarURL() ); - u = u.upURL(); - while ( u.hasPath() ) - { - popup->insertItem( KonqPixmapProvider::self()->pixmapFor( u.url() ), - u.pathOrURL() ); - - if ( u.path() == "/" ) - break; - - if ( ++i > 10 ) - break; - - u = u.upURL(); - } -} - -void KonqMainWindow::slotUp(TDEAction::ActivationReason, TQt::ButtonState state) -{ - m_goState = state; - TQTimer::singleShot( 0, this, TQT_SLOT( slotUpDelayed() ) ); -} - -void KonqMainWindow::slotUp() -{ - m_goState = Qt::LeftButton; - TQTimer::singleShot( 0, this, TQT_SLOT( slotUpDelayed() ) ); -} - -void KonqMainWindow::slotUpDelayed() -{ - KonqOpenURLRequest req; - req.newTab = true; - - req.openAfterCurrentPage = KonqSettings::openAfterCurrentPage(); - req.newTabInFront = KonqSettings::newTabsInFront(); - - if (m_goState & TQt::ShiftButton) - req.newTabInFront = !req.newTabInFront; - - const TQString& url = m_currentView->upURL().url(); - if(m_goState & TQt::ControlButton) - openFilteredURL(url, req ); - else if(m_goState & Qt::MidButton) - { - if(KonqSettings::mmbOpensTab()) - openFilteredURL( url, req); - else - KonqMisc::createNewWindow( url ); - } - else - openFilteredURL( url, false ); - m_goState = Qt::LeftButton; -} - -void KonqMainWindow::slotUpActivated( int id ) -{ - KURL u( m_currentView->locationBarURL() ); - kdDebug(1202) << "slotUpActivated. Start URL is " << u << endl; - for ( int i = 0 ; i < m_paUp->popupMenu()->indexOf( id ) + 1 ; i ++ ) - u = u.upURL(); - openURL( 0L, u ); -} - -void KonqMainWindow::slotGoMenuAboutToShow() -{ - kdDebug(1202) << "KonqMainWindow::slotGoMenuAboutToShow" << endl; - if ( m_paHistory && m_currentView ) // (maybe this is before initialisation) - m_paHistory->fillGoMenu( m_currentView->history() ); -} - -void KonqMainWindow::slotGoHistoryActivated( int steps ) -{ - slotGoHistoryActivated( steps, Qt::LeftButton ); -} - -void KonqMainWindow::slotGoHistoryActivated( int steps, TQt::ButtonState state ) -{ - kdDebug() <<"slotGoHistoryActivated( "<addTabFromHistory( m_goBuffer, openAfterCurrentPage ); - if (newView && inFront) - m_pViewManager->showTab( newView ); - } - else if(m_goState & Qt::MidButton) - { - if(mmbOpensTab) - { - KonqView * newView = m_pViewManager->addTabFromHistory( m_goBuffer, openAfterCurrentPage ); - if (newView && inFront) - m_pViewManager->showTab( newView ); - } - else - KonqMisc::newWindowFromHistory(this->currentView(), m_goBuffer); - } - else - { - m_currentView->go( m_goBuffer ); - makeViewsFollow(m_currentView->url(), KParts::URLArgs(),m_currentView->serviceType(),m_currentView); - } - - m_goBuffer = 0; - m_goState = Qt::LeftButton; -} - - -void KonqMainWindow::slotBackAboutToShow() -{ - m_paBack->popupMenu()->clear(); - if ( m_currentView ) - KonqBidiHistoryAction::fillHistoryPopup( m_currentView->history(), m_paBack->popupMenu(), true, false ); -} - -void KonqMainWindow::slotBack() -{ - slotGoHistoryActivated(-1); -} - -void KonqMainWindow::slotBack(TDEAction::ActivationReason, TQt::ButtonState state) -{ - slotGoHistoryActivated( -1, state ); -} - -void KonqMainWindow::slotBackActivated( int id ) -{ - slotGoHistoryActivated( -(m_paBack->popupMenu()->indexOf( id ) + 1), m_paBack->popupMenu()->state()); -} - -void KonqMainWindow::slotForwardAboutToShow() -{ - m_paForward->popupMenu()->clear(); - if ( m_currentView ) - KonqBidiHistoryAction::fillHistoryPopup( m_currentView->history(), m_paForward->popupMenu(), false, true ); -} - -void KonqMainWindow::slotForward() -{ - slotGoHistoryActivated( 1 ); -} - -void KonqMainWindow::slotForward(TDEAction::ActivationReason, TQt::ButtonState state) -{ - slotGoHistoryActivated( 1, state ); -} - -void KonqMainWindow::slotForwardActivated( int id ) -{ - slotGoHistoryActivated( m_paForward->popupMenu()->indexOf( id ) + 1, m_paForward->popupMenu()->state() ); -} - -void KonqMainWindow::initCombo() -{ - m_combo = new KonqCombo( 0L, "history combo"); - - m_combo->init( s_pCompletion ); - - connect( m_combo, TQT_SIGNAL(activated(const TQString&,int)), - this, TQT_SLOT(slotURLEntered(const TQString&,int)) ); - connect( m_combo, TQT_SIGNAL(showPageSecurity()), - this, TQT_SLOT(showPageSecurity()) ); - - m_pURLCompletion = new KURLCompletion(); - m_pURLCompletion->setCompletionMode( s_pCompletion->completionMode() ); - - // This only turns completion off. ~ is still there in the result - // We do want completion of user names, right? - //m_pURLCompletion->setReplaceHome( false ); // Leave ~ alone! Will be taken care of by filters!! - - connect( m_combo, TQT_SIGNAL(completionModeChanged(TDEGlobalSettings::Completion)), - TQT_SLOT( slotCompletionModeChanged( TDEGlobalSettings::Completion ))); - connect( m_combo, TQT_SIGNAL( completion( const TQString& )), - TQT_SLOT( slotMakeCompletion( const TQString& ))); - connect( m_combo, TQT_SIGNAL( substringCompletion( const TQString& )), - TQT_SLOT( slotSubstringcompletion( const TQString& ))); - connect( m_combo, TQT_SIGNAL( textRotation( TDECompletionBase::KeyBindingType) ), - TQT_SLOT( slotRotation( TDECompletionBase::KeyBindingType ))); - connect( m_combo, TQT_SIGNAL( cleared() ), - TQT_SLOT ( slotClearHistory() ) ); - connect( m_pURLCompletion, TQT_SIGNAL( match(const TQString&) ), - TQT_SLOT( slotMatch(const TQString&) )); - - m_combo->lineEdit()->installEventFilter(this); - - static bool bookmarkCompletionInitialized = false; - if ( !bookmarkCompletionInitialized ) - { - bookmarkCompletionInitialized = true; - DelayedInitializer *initializer = new DelayedInitializer( TQEvent::KeyPress, TQT_TQOBJECT(m_combo->lineEdit()) ); - connect( initializer, TQT_SIGNAL( initialize() ), this, TQT_SLOT( bookmarksIntoCompletion() ) ); - } -} - -void KonqMainWindow::bookmarksIntoCompletion() -{ - // add all bookmarks to the completion list for easy access - bookmarksIntoCompletion( KonqBookmarkManager::self()->root() ); -} - -// the user changed the completion mode in the combo -void KonqMainWindow::slotCompletionModeChanged( TDEGlobalSettings::Completion m ) -{ - s_pCompletion->setCompletionMode( m ); - - KonqSettings::setSettingsCompletionMode( (int)m_combo->completionMode() ); - KonqSettings::writeConfig(); - - // tell the other windows too (only this instance currently) - KonqMainWindow *window = s_lstViews->first(); - while ( window ) { - if ( window->m_combo ) { - window->m_combo->setCompletionMode( m ); - window->m_pURLCompletion->setCompletionMode( m ); - } - window = s_lstViews->next(); - } -} - -// at first, try to find a completion in the current view, then use the global -// completion (history) -void KonqMainWindow::slotMakeCompletion( const TQString& text ) -{ - if( m_pURLCompletion ) - { - m_urlCompletionStarted = true; // flag for slotMatch() - - // kdDebug(1202) << "Local Completion object found!" << endl; - TQString completion = m_pURLCompletion->makeCompletion( text ); - m_currentDir = TQString::null; - - if ( completion.isNull() && !m_pURLCompletion->isRunning() ) - { - // No match() signal will come from m_pURLCompletion - // ask the global one - // tell the static completion object about the current completion mode - completion = s_pCompletion->makeCompletion( text ); - - // some special handling necessary for CompletionPopup - if ( m_combo->completionMode() == TDEGlobalSettings::CompletionPopup || - m_combo->completionMode() == TDEGlobalSettings::CompletionPopupAuto ) - m_combo->setCompletedItems( historyPopupCompletionItems( text ) ); - - else if ( !completion.isNull() ) - m_combo->setCompletedText( completion ); - } - else - { - // To be continued in slotMatch()... - if( !m_pURLCompletion->dir().isEmpty() ) - m_currentDir = m_pURLCompletion->dir(); - } - } - // kdDebug(1202) << "Current dir: " << m_currentDir << " Current text: " << text << endl; -} - -void KonqMainWindow::slotSubstringcompletion( const TQString& text ) -{ - bool filesFirst = currentURL().startsWith( "/" ) || - currentURL().startsWith( "file:/" ); - TQStringList items; - if ( filesFirst && m_pURLCompletion ) - items = m_pURLCompletion->substringCompletion( text ); - - items += s_pCompletion->substringCompletion( text ); - if ( !filesFirst && m_pURLCompletion ) - items += m_pURLCompletion->substringCompletion( text ); - - m_combo->setCompletedItems( items ); -} - -void KonqMainWindow::slotRotation( TDECompletionBase::KeyBindingType type ) -{ - // Tell slotMatch() to do nothing - m_urlCompletionStarted = false; - - bool prev = (type == TDECompletionBase::PrevCompletionMatch); - if ( prev || type == TDECompletionBase::NextCompletionMatch ) { - TQString completion = prev ? m_pURLCompletion->previousMatch() : - m_pURLCompletion->nextMatch(); - - if( completion.isNull() ) { // try the history TDECompletion object - completion = prev ? s_pCompletion->previousMatch() : - s_pCompletion->nextMatch(); - } - if ( completion.isEmpty() || completion == m_combo->currentText() ) - return; - - m_combo->setCompletedText( completion ); - } -} - -// Handle match() from m_pURLCompletion -void KonqMainWindow::slotMatch( const TQString &match ) -{ - if ( match.isEmpty() ) // this case is handled directly - return; - - // Check flag to avoid match() raised by rotation - if ( m_urlCompletionStarted ) { - m_urlCompletionStarted = false; - - // some special handling necessary for CompletionPopup - if ( m_combo->completionMode() == TDEGlobalSettings::CompletionPopup || - m_combo->completionMode() == TDEGlobalSettings::CompletionPopupAuto ) { - TQStringList items = m_pURLCompletion->allMatches(); - items += historyPopupCompletionItems( m_combo->currentText() ); - // items.sort(); // should we? - m_combo->setCompletedItems( items ); - } - else if ( !match.isNull() ) - m_combo->setCompletedText( match ); - } -} - -void KonqMainWindow::slotCtrlTabPressed() -{ - KonqView * view = m_pViewManager->chooseNextView( m_currentView ); - if ( view ) - m_pViewManager->setActivePart( view->part() ); -} - -void KonqMainWindow::slotClearHistory() -{ - KonqHistoryManager::kself()->emitClear(); -} - -void KonqMainWindow::slotClearComboHistory() -{ - if (m_combo && m_combo->count()) - m_combo->clearHistory(); -} - -bool KonqMainWindow::eventFilter(TQObject*obj,TQEvent *ev) -{ - if ( ( ev->type()==TQEvent::FocusIn || ev->type()==TQEvent::FocusOut ) && - m_combo && TQT_BASE_OBJECT(m_combo->lineEdit()) == TQT_BASE_OBJECT(obj) ) - { - //kdDebug(1202) << "KonqMainWindow::eventFilter " << obj << " " << obj->className() << " " << obj->name() << endl; - - TQFocusEvent * focusEv = TQT_TQFOCUSEVENT(ev); - if (focusEv->reason() == TQFocusEvent::Popup) - { - return KParts::MainWindow::eventFilter( obj, ev ); - } - - KParts::BrowserExtension * ext = 0; - if ( m_currentView ) - ext = m_currentView->browserExtension(); - TQStrList slotNames; - if (ext) - slotNames = ext->metaObject()->slotNames(); - - //for ( char * s = slotNames.first() ; s ; s = slotNames.next() ) - //{ - // kdDebug(1202) << "slotNames=" << s << endl; - //} - - - if (ev->type()==TQEvent::FocusIn) - { - //kdDebug(1202) << "ComboBox got the focus..." << endl; - if (m_bLocationBarConnected) - { - //kdDebug(1202) << "Was already connected..." << endl; - return KParts::MainWindow::eventFilter( obj, ev ); - } - m_bLocationBarConnected = true; - - // Workaround for Qt issue: usually, TQLineEdit reacts on Ctrl-D, - // but the duplicate_window action also has Ctrl-D as accel and - // prevents the lineedit from getting this event. IMHO the accel - // should be disabled in favor of the focus-widget. - TDEAction *duplicate = actionCollection()->action("duplicate_window"); - if ( duplicate->shortcut() == TQKeySequence(CTRL+Key_D) ) - duplicate->setEnabled( false ); - - if (slotNames.contains("cut()")) - disconnect( m_paCut, TQT_SIGNAL( activated() ), ext, TQT_SLOT( cut() ) ); - if (slotNames.contains("copy()")) - disconnect( m_paCopy, TQT_SIGNAL( activated() ), ext, TQT_SLOT( copy() ) ); - if (slotNames.contains("paste()")) - disconnect( m_paPaste, TQT_SIGNAL( activated() ), ext, TQT_SLOT( paste() ) ); - if (slotNames.contains("del()")) - disconnect( m_paDelete, TQT_SIGNAL( activated() ), ext, TQT_SLOT( del() ) ); - disconnect( m_paTrash, TQT_SIGNAL( activated( TDEAction::ActivationReason, TQt::ButtonState ) ), - this, TQT_SLOT( slotTrashActivated( TDEAction::ActivationReason, TQt::ButtonState ) ) ); - - connect( m_paCut, TQT_SIGNAL( activated() ), m_combo->lineEdit(), TQT_SLOT( cut() ) ); - connect( m_paCopy, TQT_SIGNAL( activated() ), m_combo->lineEdit(), TQT_SLOT( copy() ) ); - connect( m_paPaste, TQT_SIGNAL( activated() ), m_combo->lineEdit(), TQT_SLOT( paste() ) ); - connect( TQApplication::clipboard(), TQT_SIGNAL(dataChanged()), this, TQT_SLOT(slotClipboardDataChanged()) ); - connect( m_combo->lineEdit(), TQT_SIGNAL(textChanged(const TQString &)), this, TQT_SLOT(slotCheckComboSelection()) ); - connect( m_combo->lineEdit(), TQT_SIGNAL(selectionChanged()), this, TQT_SLOT(slotCheckComboSelection()) ); - - m_paTrash->setEnabled(false); - m_paDelete->setEnabled(false); - - slotClipboardDataChanged(); - - } - else if ( ev->type()==TQEvent::FocusOut) - { - //kdDebug(1202) << "ComboBox lost focus..." << endl; - if (!m_bLocationBarConnected) - { - //kdDebug(1202) << "Was already disconnected..." << endl; - return KParts::MainWindow::eventFilter( obj, ev ); - } - m_bLocationBarConnected = false; - - // see above in FocusIn for explanation - // we use new_window as reference, as it's always in the same state - // as duplicate_window - TDEAction *duplicate = actionCollection()->action("duplicate_window"); - if ( duplicate->shortcut() == TQKeySequence(CTRL+Key_D) ) - duplicate->setEnabled( actionCollection()->action("new_window")->isEnabled() ); - - if (slotNames.contains("cut()")) - connect( m_paCut, TQT_SIGNAL( activated() ), ext, TQT_SLOT( cut() ) ); - if (slotNames.contains("copy()")) - connect( m_paCopy, TQT_SIGNAL( activated() ), ext, TQT_SLOT( copy() ) ); - if (slotNames.contains("paste()")) - connect( m_paPaste, TQT_SIGNAL( activated() ), ext, TQT_SLOT( paste() ) ); - if (slotNames.contains("del()")) - connect( m_paDelete, TQT_SIGNAL( activated() ), ext, TQT_SLOT( del() ) ); - connect( m_paTrash, TQT_SIGNAL( activated( TDEAction::ActivationReason, TQt::ButtonState ) ), - this, TQT_SLOT( slotTrashActivated( TDEAction::ActivationReason, TQt::ButtonState ) ) ); - - disconnect( m_paCut, TQT_SIGNAL( activated() ), m_combo->lineEdit(), TQT_SLOT( cut() ) ); - disconnect( m_paCopy, TQT_SIGNAL( activated() ), m_combo->lineEdit(), TQT_SLOT( copy() ) ); - disconnect( m_paPaste, TQT_SIGNAL( activated() ), m_combo->lineEdit(), TQT_SLOT( paste() ) ); - disconnect( TQApplication::clipboard(), TQT_SIGNAL(dataChanged()), this, TQT_SLOT(slotClipboardDataChanged()) ); - disconnect( m_combo->lineEdit(), TQT_SIGNAL(textChanged(const TQString &)), this, TQT_SLOT(slotCheckComboSelection()) ); - disconnect( m_combo->lineEdit(), TQT_SIGNAL(selectionChanged()), this, TQT_SLOT(slotCheckComboSelection()) ); - - if ( ext ) - { - m_paCut->setEnabled( ext->isActionEnabled( "cut" ) ); - m_paCopy->setEnabled( ext->isActionEnabled( "copy" ) ); - m_paPaste->setEnabled( ext->isActionEnabled( "paste" ) ); - m_paDelete->setEnabled( ext->isActionEnabled( "delete" ) ); - m_paTrash->setEnabled( ext->isActionEnabled( "trash" ) ); - } - else - { - m_paCut->setEnabled( false ); - m_paCopy->setEnabled( false ); - m_paPaste->setEnabled( false ); - m_paDelete->setEnabled( false ); - m_paTrash->setEnabled( false ); - } - } - } - return KParts::MainWindow::eventFilter( obj, ev ); -} - -void KonqMainWindow::slotClipboardDataChanged() -{ - //kdDebug(1202) << "KonqMainWindow::slotClipboardDataChanged()" << endl; - TQMimeSource *data = TQApplication::clipboard()->data(); - m_paPaste->setEnabled( data->provides( "text/plain" ) ); - slotCheckComboSelection(); -} - -void KonqMainWindow::slotCheckComboSelection() -{ - //kdDebug(1202) << "m_combo->lineEdit()->hasMarkedText() : " << hasSelection << endl; - bool hasSelection = m_combo->lineEdit()->hasSelectedText(); - m_paCopy->setEnabled( hasSelection ); - m_paCut->setEnabled( hasSelection ); -} - -void KonqMainWindow::slotClearLocationBar( TDEAction::ActivationReason, TQt::ButtonState state ) -{ - kdDebug(1202) << "slotClearLocationBar" << endl; - slotStop(); - m_combo->clearTemporary(); - focusLocationBar(); - if ( state & Qt::MidButton ) - m_combo->setURL( TQApplication::clipboard()->text( TQClipboard::Selection ) ); -} - -void KonqMainWindow::slotForceSaveMainWindowSettings() -{ -// kdDebug(1202)<<"slotForceSaveMainWindowSettings()"<sync(); - } -} - -void KonqMainWindow::slotShowMenuBar() -{ - if (menuBar()->isVisible()) - menuBar()->hide(); - else - menuBar()->show(); - slotForceSaveMainWindowSettings(); -} - -void KonqMainWindow::slotUpdateFullScreen( bool set ) -{ - if( set ) - { - showFullScreen(); - // Create toolbar button for exiting from full-screen mode - // ...but only if there isn't one already... - - bool haveFullScreenButton = false; - - //Walk over the toolbars and check whether there is a show fullscreen button in any of them - TQPtrListIterator barIt = toolBarIterator(); - for (; barIt.current(); ++barIt ) - { - //Are we plugged here, in a visible toolbar? - if (barIt.current()->isVisible() && - action( "fullscreen" )->isPlugged(barIt.current())) - { - haveFullScreenButton = true; - break; - } - } - - if (!haveFullScreenButton) - { - TQPtrList lst; - lst.append( m_ptaFullScreen ); - plugActionList( "fullscreen", lst ); - } - - m_prevMenuBarVisible = menuBar()->isVisible(); - menuBar()->hide(); - m_paShowMenuBar->setChecked( false ); - - // Qt bug, the flags are lost. They know about it. - // happens only with the hackish non-_NET_WM_STATE_FULLSCREEN way - setWFlags( WDestructiveClose ); - // Qt bug (see below) - setAcceptDrops( FALSE ); - topData()->dnd = 0; - setAcceptDrops( TRUE ); - } - else - { -#if TQT_VERSION >= 0x030300 - setWindowState( windowState() & ~WindowFullScreen ); -#else - if( isMaximized()) - { - showNormal(); - showMaximized(); // showNormal() would reset maximize state - } - else - showNormal(); -#endif - unplugActionList( "fullscreen" ); - - if (m_prevMenuBarVisible) - { - menuBar()->show(); - m_paShowMenuBar->setChecked( true ); - } - - // Qt bug, the flags aren't restored. They know about it. - setWFlags( WType_TopLevel | WDestructiveClose ); - // Other Qt bug - setAcceptDrops( FALSE ); - topData()->dnd = 0; - setAcceptDrops( TRUE ); - } -} - -void KonqMainWindow::setLocationBarURL( const KURL &url ) -{ - setLocationBarURL( url.pathOrURL() ); -} - -void KonqMainWindow::setLocationBarURL( const TQString &url ) -{ - kdDebug(1202) << "KonqMainWindow::setLocationBarURL: url = " << url << endl; - - m_combo->setURL( url ); - - setIcon( KonqPixmapProvider::self()->pixmapFor( url ) ); -} - -void KonqMainWindow::setPageSecurity( PageSecurity pageSecurity ) -{ - m_combo->setPageSecurity( pageSecurity ); -} - -void KonqMainWindow::showPageSecurity() -{ - if ( m_currentView && m_currentView->part() ) { - TDEAction *act = m_currentView->part()->action( "security" ); - if ( act ) - act->activate(); - } -} - -// called via DCOP from KonquerorIface -void KonqMainWindow::comboAction( int action, const TQString& url, const TQCString& objId ) -{ - if (!s_lstViews) // this happens in "konqueror --silent" - return; - - KonqCombo *combo = 0L; - KonqMainWindow *window = s_lstViews->first(); - while ( window ) { - if ( window->m_combo ) { - combo = window->m_combo; - - switch ( action ) { - case ComboAdd: - combo->insertPermanent( url ); - break; - case ComboClear: - combo->clearHistory(); - break; - case ComboRemove: - combo->removeURL( url ); - break; - default: - break; - } - } - window = s_lstViews->next(); - } - - // only one instance should save... - if ( combo && objId == kapp->dcopClient()->defaultObject() ) - combo->saveItems(); -} - -TQString KonqMainWindow::locationBarURL() const -{ - return m_combo->currentText(); -} - -void KonqMainWindow::focusLocationBar() -{ - if ( m_combo->isVisible() || !isVisible() ) - m_combo->setFocus(); -} - -void KonqMainWindow::startAnimation() -{ - //kdDebug(1202) << "KonqMainWindow::startAnimation" << endl; - m_paAnimatedLogo->start(); - m_paStop->setEnabled( true ); - toggleReloadStopButton( true ); -} - -void KonqMainWindow::stopAnimation() -{ - //kdDebug(1202) << "KonqMainWindow::stopAnimation" << endl; - m_paAnimatedLogo->stop(); - m_paStop->setEnabled( false ); - toggleReloadStopButton( false ); -} - -void KonqMainWindow::setUpEnabled( const KURL &url ) -{ - //kdDebug(1202) << "KonqMainWindow::setUpEnabled(" << url << ")" << endl; - //kdDebug(1202) << "hasPath=" << url.hasPath() << endl; - bool bHasUpURL = false; - - bHasUpURL = ( ( url.hasPath() && url.path() != "/" && ( url.path()[0]=='/' ) ) - || !url.query().isEmpty() /*e.g. lists.kde.org*/ ); - if ( !bHasUpURL ) - bHasUpURL = url.hasSubURL(); - - m_paUp->setEnabled( bHasUpURL ); -} - -void KonqMainWindow::initActions() -{ - actionCollection()->setHighlightingEnabled( true ); - connectActionCollection( actionCollection() ); - - - // Note about this method : don't call setEnabled() on any of the actions. - // They are all disabled then re-enabled with enableAllActions - // If any one needs to be initially disabled, put that code in enableAllActions - - // File menu - m_pMenuNew = new KNewMenu ( actionCollection(), this, "new_menu" ); - TQObject::connect( m_pMenuNew->popupMenu(), TQT_SIGNAL(aboutToShow()), - this, TQT_SLOT(slotFileNewAboutToShow()) ); - - (void) new TDEAction( i18n( "&Edit File Type..." ), 0, actionCollection(), "editMimeType" ); - (void) new TDEAction( i18n( "Properties" ), ALT+Key_Return, actionCollection(), "properties" ); - (void) new TDEAction( i18n( "New &Window" ), "window-new", TDEStdAccel::shortcut(TDEStdAccel::New), TQT_TQOBJECT(this), TQT_SLOT( slotNewWindow() ), actionCollection(), "new_window" ); - (void) new TDEAction( i18n( "&Duplicate Window" ), "window_duplicate", CTRL+Key_D, TQT_TQOBJECT(this), TQT_SLOT( slotDuplicateWindow() ), actionCollection(), "duplicate_window" ); - (void) new TDEAction( i18n( "Send &Link Address..." ), "mail_generic", 0, TQT_TQOBJECT(this), TQT_SLOT( slotSendURL() ), actionCollection(), "sendURL" ); - (void) new TDEAction( i18n( "S&end File..." ), "mail_generic", 0, TQT_TQOBJECT(this), TQT_SLOT( slotSendFile() ), actionCollection(), "sendPage" ); - if (kapp->authorize("shell_access")) - { - (void) new TDEAction( i18n( "Open &Terminal" ), "openterm", Key_F4, TQT_TQOBJECT(this), TQT_SLOT( slotOpenTerminal() ), actionCollection(), "open_terminal" ); - } - (void) new TDEAction( i18n( "&Open Location..." ), "document-open", TDEStdAccel::shortcut(TDEStdAccel::Open), TQT_TQOBJECT(this), TQT_SLOT( slotOpenLocation() ), actionCollection(), "open_location" ); - - m_paFindFiles = new TDEToggleAction( i18n( "&Find File..." ), "filefind", TDEStdAccel::shortcut(TDEStdAccel::Find), TQT_TQOBJECT(this), TQT_SLOT( slotToolFind() ), actionCollection(), "findfile" ); - - m_paPrint = KStdAction::print( 0, 0, actionCollection(), "print" ); - (void) KStdAction::quit( TQT_TQOBJECT(this), TQT_SLOT( close() ), actionCollection(), "quit" ); - - m_ptaUseHTML = new TDEToggleAction( i18n( "&Use index.html" ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotShowHTML() ), actionCollection(), "usehtml" ); - m_paLockView = new TDEToggleAction( i18n( "Lock to Current Location"), 0, TQT_TQOBJECT(this), TQT_SLOT( slotLockView() ), actionCollection(), "lock" ); - m_paLinkView = new TDEToggleAction( i18n( "Lin&k View"), 0, TQT_TQOBJECT(this), TQT_SLOT( slotLinkView() ), actionCollection(), "link" ); - - // Go menu - m_paUp = new TDEToolBarPopupAction( i18n( "&Up" ), "go-up", TDEStdAccel::shortcut(TDEStdAccel::Up), actionCollection(), "up" ); - connect( m_paUp, TQT_SIGNAL( activated( TDEAction::ActivationReason, TQt::ButtonState) ), TQT_TQOBJECT(this), - TQT_SLOT( slotUp(TDEAction::ActivationReason, TQt::ButtonState) ) ); - connect( m_paUp->popupMenu(), TQT_SIGNAL( aboutToShow() ), TQT_TQOBJECT(this), TQT_SLOT( slotUpAboutToShow() ) ); - connect( m_paUp->popupMenu(), TQT_SIGNAL( activated( int ) ), TQT_TQOBJECT(this), TQT_SLOT( slotUpActivated( int ) ) ); - - TQPair< KGuiItem, KGuiItem > backForward = KStdGuiItem::backAndForward(); - m_paBack = new TDEToolBarPopupAction( backForward.first, TDEStdAccel::shortcut(TDEStdAccel::Back), 0, "", actionCollection(), "back" ); - connect( m_paBack, TQT_SIGNAL( activated( TDEAction::ActivationReason, TQt::ButtonState) ), TQT_TQOBJECT(this), - TQT_SLOT( slotBack(TDEAction::ActivationReason, TQt::ButtonState) ) ); - connect( m_paBack->popupMenu(), TQT_SIGNAL( aboutToShow() ), TQT_TQOBJECT(this), TQT_SLOT( slotBackAboutToShow() ) ); - connect( m_paBack->popupMenu(), TQT_SIGNAL( activated( int ) ), TQT_TQOBJECT(this), TQT_SLOT( slotBackActivated( int ) ) ); - - m_paForward = new TDEToolBarPopupAction( backForward.second, TDEStdAccel::shortcut(TDEStdAccel::Forward), 0, "", actionCollection(), "forward" ); - connect( m_paForward, TQT_SIGNAL( activated( TDEAction::ActivationReason, TQt::ButtonState) ), TQT_TQOBJECT(this), - TQT_SLOT( slotForward(TDEAction::ActivationReason, TQt::ButtonState) ) ); - connect( m_paForward->popupMenu(), TQT_SIGNAL( aboutToShow() ), TQT_TQOBJECT(this), TQT_SLOT( slotForwardAboutToShow() ) ); - connect( m_paForward->popupMenu(), TQT_SIGNAL( activated( int ) ), TQT_TQOBJECT(this), TQT_SLOT( slotForwardActivated( int ) ) ); - - m_paHistory = new KonqBidiHistoryAction( i18n("History"), actionCollection(), "history" ); - connect( m_paHistory, TQT_SIGNAL( menuAboutToShow() ), TQT_TQOBJECT(this), TQT_SLOT( slotGoMenuAboutToShow() ) ); - connect( m_paHistory, TQT_SIGNAL( activated( int ) ), TQT_TQOBJECT(this), TQT_SLOT( slotGoHistoryActivated( int ) ) ); - - m_paHome = new TDEAction( i18n( "Home" ), "go-home", TDEStdAccel::shortcut(TDEStdAccel::Home), actionCollection(), "home" ); - connect( m_paHome, TQT_SIGNAL( activated( TDEAction::ActivationReason, TQt::ButtonState) ), TQT_TQOBJECT(this), - TQT_SLOT( slotHome(TDEAction::ActivationReason, TQt::ButtonState) ) ); - - (void) new TDEAction( i18n( "S&ystem" ), "computer", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoSystem() ), actionCollection(), "go_system" ); - (void) new TDEAction( i18n( "App&lications" ), "kmenu", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoApplications() ), actionCollection(), "go_applications" ); - (void) new TDEAction( i18n( "&Storage Media" ), "computer", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoMedia() ), actionCollection(), "go_media" ); - (void) new TDEAction( i18n( "&Network Folders" ), "network", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoNetworkFolders() ), actionCollection(), "go_network_folders" ); - (void) new TDEAction( i18n( "Sett&ings" ), "kcontrol", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoSettings() ), actionCollection(), "go_settings" ); - //(void) new TDEAction( i18n( "Sidebar Configuration" ), 0, this, TQT_SLOT( slotGoDirTree() ), actionCollection(), "go_dirtree" ); - (void) new TDEAction( i18n( "Trash" ), "trashcan_full", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoTrash() ), actionCollection(), "go_trash" ); - (void) new TDEAction( i18n( "Autostart" ), "launch", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoAutostart() ), actionCollection(), "go_autostart" ); - KonqMostOftenURLSAction *mostOften = new KonqMostOftenURLSAction( i18n("Most Often Visited"), actionCollection(), "go_most_often" ); - connect( mostOften, TQT_SIGNAL( activated( const KURL& )), - TQT_SLOT( slotOpenURL( const KURL& ))); - (void) new TDEAction( i18n( "History" ), "history", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoHistory() ), actionCollection(), "go_history" ); - - // Settings menu - - m_paSaveViewProfile = new TDEAction( i18n( "&Save View Profile..." ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotSaveViewProfile() ), actionCollection(), "saveviewprofile" ); - m_paSaveViewPropertiesLocally = new TDEToggleAction( i18n( "Save View Changes per &Folder" ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotSaveViewPropertiesLocally() ), actionCollection(), "saveViewPropertiesLocally" ); - // "Remove" ? "Reset" ? The former is more correct, the latter is more kcontrol-like... - m_paRemoveLocalProperties = new TDEAction( i18n( "Remove Folder Properties" ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotRemoveLocalProperties() ), actionCollection(), "removeLocalProperties" ); - - - m_configureModules << "tde-filebehavior.desktop" << "tde-fileappearance.desktop" << - "tde-filepreviews.desktop" << "tde-filetypes.desktop" << - "tde-tdehtml_behavior.desktop" << "tde-tdehtml_userinterface.desktop" << - "tde-tdehtml_java_js.desktop" << "tde-tdehtml_filter.desktop" << - "tde-tdehtml_fonts.desktop" << "tde-ebrowsing.desktop" << - "tde-kcmhistory.desktop" << "tde-cookies.desktop" << - "tde-cache.desktop" << "tde-proxy.desktop" << "tde-kcmcss.desktop" << - "tde-kcmcgi.desktop" << "tde-crypto.desktop" << "tde-useragent.desktop" << - "tde-tdehtml_plugins.desktop" << "tde-kcmkonqyperformance.desktop"; - - - if (!kapp->authorizeControlModules(configModules()).isEmpty()) - KStdAction::preferences (TQT_TQOBJECT(this), TQT_SLOT (slotConfigure()), actionCollection() ); - - KStdAction::keyBindings( guiFactory(), TQT_SLOT( configureShortcuts() ), actionCollection() ); - KStdAction::configureToolbars( TQT_TQOBJECT(this), TQT_SLOT( slotConfigureToolbars() ), actionCollection() ); - - m_paConfigureExtensions = new TDEAction( i18n("Configure Extensions..."), 0, TQT_TQOBJECT(this), TQT_SLOT( slotConfigureExtensions()), actionCollection(), "options_configure_extensions"); - m_paConfigureSpellChecking = new TDEAction( i18n("Configure Spell Checking..."), "tools-check-spelling", 0,TQT_TQOBJECT(this), TQT_SLOT( slotConfigureSpellChecking()), actionCollection(), "configurespellcheck"); - - // Window menu - m_paSplitViewHor = new TDEAction( i18n( "Split View &Left/Right" ), "view_left_right", CTRL+SHIFT+Key_L, TQT_TQOBJECT(this), TQT_SLOT( slotSplitViewHorizontal() ), actionCollection(), "splitviewh" ); - m_paSplitViewVer = new TDEAction( i18n( "Split View &Top/Bottom" ), "view_top_bottom", CTRL+SHIFT+Key_T, TQT_TQOBJECT(this), TQT_SLOT( slotSplitViewVertical() ), actionCollection(), "splitviewv" ); - m_paAddTab = new TDEAction( i18n( "&New Tab" ), "tab_new", "CTRL+SHIFT+N;CTRL+T", TQT_TQOBJECT(this), TQT_SLOT( slotAddTab() ), actionCollection(), "newtab" ); - m_paDuplicateTab = new TDEAction( i18n( "&Duplicate Current Tab" ), "tab_duplicate", CTRL+SHIFT+Key_D, TQT_TQOBJECT(this), TQT_SLOT( slotDuplicateTab() ), actionCollection(), "duplicatecurrenttab" ); - m_paBreakOffTab = new TDEAction( i18n( "Detach Current Tab" ), "tab_breakoff", CTRL+SHIFT+Key_B, TQT_TQOBJECT(this), TQT_SLOT( slotBreakOffTab() ), actionCollection(), "breakoffcurrenttab" ); - m_paRemoveView = new TDEAction( i18n( "&Close Active View" ),"view_remove", CTRL+SHIFT+Key_R, TQT_TQOBJECT(this), TQT_SLOT( slotRemoveView() ), actionCollection(), "removeview" ); - m_paRemoveTab = new TDEAction( i18n( "Close Current Tab" ), "tab_remove", CTRL+Key_W, TQT_TQOBJECT(this), TQT_SLOT( slotRemoveTab() ), actionCollection(), "removecurrenttab" ); - m_paRemoveOtherTabs = new TDEAction( i18n( "Close &Other Tabs" ), "tab_remove_other", 0, TQT_TQOBJECT(this), TQT_SLOT( slotRemoveOtherTabsPopup() ), actionCollection(), "removeothertabs" ); - - m_paActivateNextTab = new TDEAction( i18n( "Activate Next Tab" ), "tab_next", TQApplication::reverseLayout() ? TDEStdAccel::tabPrev() : TDEStdAccel::tabNext(), TQT_TQOBJECT(this), TQT_SLOT( slotActivateNextTab() ), actionCollection(), "activatenexttab" ); - m_paActivatePrevTab = new TDEAction( i18n( "Activate Previous Tab" ), "tab_previous", TQApplication::reverseLayout() ? TDEStdAccel::tabNext() : TDEStdAccel::tabPrev(), TQT_TQOBJECT(this), TQT_SLOT( slotActivatePrevTab() ), actionCollection(), "activateprevtab" ); - - TQCString actionname; - for (int i=1;i<13;i++) { - actionname.sprintf("activate_tab_%02d", i); - new TDEAction(i18n("Activate Tab %1").arg(i), 0, TQT_TQOBJECT(this), TQT_SLOT(slotActivateTab()), actionCollection(), actionname); - } - - m_paMoveTabLeft = new TDEAction( i18n("Move Tab Left"), 0 , CTRL+SHIFT+Key_Left,TQT_TQOBJECT(this), TQT_SLOT( slotMoveTabLeft()),actionCollection(),"tab_move_left"); - m_paMoveTabRight = new TDEAction( i18n("Move Tab Right"), 0 , CTRL+SHIFT+Key_Right,TQT_TQOBJECT(this), TQT_SLOT( slotMoveTabRight()),actionCollection(),"tab_move_right"); - -#ifndef NDEBUG - (void) new TDEAction( i18n( "Dump Debug Info" ), "view_dump_debug_info", 0, TQT_TQOBJECT(this), TQT_SLOT( slotDumpDebugInfo() ), actionCollection(), "dumpdebuginfo" ); -#endif - - m_paSaveRemoveViewProfile = new TDEAction( i18n( "C&onfigure View Profiles..." ), 0, m_pViewManager, TQT_SLOT( slotProfileDlg() ), actionCollection(), "saveremoveviewprofile" ); - m_pamLoadViewProfile = new TDEActionMenu( i18n( "Load &View Profile" ), actionCollection(), "loadviewprofile" ); - - m_pViewManager->setProfiles( m_pamLoadViewProfile ); - - m_ptaFullScreen = KStdAction::fullScreen( 0, 0, actionCollection(), this ); - TDEShortcut fullScreenShortcut = m_ptaFullScreen->shortcut(); - fullScreenShortcut.append( KKey( Key_F11 ) ); - m_ptaFullScreen->setShortcut( fullScreenShortcut ); - connect( m_ptaFullScreen, TQT_SIGNAL( toggled( bool )), TQT_TQOBJECT(this), TQT_SLOT( slotUpdateFullScreen( bool ))); - - TDEShortcut reloadShortcut = TDEStdAccel::shortcut(TDEStdAccel::Reload); - reloadShortcut.append(KKey(CTRL + Key_R)); - m_paReload = new TDEAction( i18n( "&Reload" ), "reload", reloadShortcut, TQT_TQOBJECT(this), TQT_SLOT( slotReload() ), actionCollection(), "reload" ); - m_paReloadAllTabs = new TDEAction( i18n( "&Reload All Tabs" ), "reload_all_tabs", SHIFT+Key_F5, TQT_TQOBJECT(this), TQT_SLOT( slotReloadAllTabs() ), actionCollection(), "reload_all_tabs" ); - - m_paReloadStop = new TDEAction( i18n( "&Reload/Stop" ), "reload", 0, TQT_TQOBJECT(this), TQT_SLOT( slotReloadStop() ), actionCollection(), "reload_stop" ); - - m_paUndo = KStdAction::undo( KonqUndoManager::self(), TQT_SLOT( undo() ), actionCollection(), "undo" ); - //m_paUndo->setEnabled( KonqUndoManager::self()->undoAvailable() ); - connect( KonqUndoManager::self(), TQT_SIGNAL( undoTextChanged( const TQString & ) ), - m_paUndo, TQT_SLOT( setText( const TQString & ) ) ); - - // Those are connected to the browserextension directly - m_paCut = KStdAction::cut( 0, 0, actionCollection(), "cut" ); - TDEShortcut cutShortCut = m_paCut->shortcut(); - cutShortCut.remove( KKey( SHIFT + Key_Delete ) ); // used for deleting files - m_paCut->setShortcut( cutShortCut ); - - m_paCopy = KStdAction::copy( 0, 0, actionCollection(), "copy" ); - m_paPaste = KStdAction::paste( 0, 0, actionCollection(), "paste" ); - m_paStop = new TDEAction( i18n( "&Stop" ), "process-stop", Key_Escape, TQT_TQOBJECT(this), TQT_SLOT( slotStop() ), actionCollection(), "stop" ); - - m_paRename = new TDEAction( i18n( "&Rename" ), /*"editrename",*/ Key_F2, actionCollection(), "rename" ); - m_paTrash = new TDEAction( i18n( "&Move to Trash" ), "edittrash", Key_Delete, actionCollection(), "trash" ); - connect( m_paTrash, TQT_SIGNAL( activated( TDEAction::ActivationReason, TQt::ButtonState ) ), - TQT_TQOBJECT(this), TQT_SLOT( slotTrashActivated( TDEAction::ActivationReason, TQt::ButtonState ) ) ); - - m_paDelete = new TDEAction( i18n( "&Delete" ), "edit-delete", SHIFT+Key_Delete, actionCollection(), "del" ); - // F5 is the default key binding for Reload.... a la Windows. mc users want F5 for Copy and F6 for move, but I can't make that default. - m_paCopyFiles = new TDEAction( i18n("Copy &Files..."), "copyfiles", Key_F7, TQT_TQOBJECT(this), TQT_SLOT( slotCopyFiles() ), actionCollection(), "copyfiles" ); - m_paMoveFiles = new TDEAction( i18n("M&ove Files..."), "movefiles", Key_F8, TQT_TQOBJECT(this), TQT_SLOT( slotMoveFiles() ), actionCollection(), "movefiles" ); - // This action doesn't appear in the GUI, it's for the shortcut only. KNewMenu takes care of the GUI stuff. - m_paNewDir = new TDEAction( i18n("Create Folder..." ), "konq_create_dir", Key_F10, TQT_TQOBJECT(this), TQT_SLOT( slotNewDir() ), actionCollection(), "konq_create_dir" ); - m_paAnimatedLogo = new KonqLogoAction( i18n("Animated Logo"), 0, TQT_TQOBJECT(this), TQT_SLOT( slotDuplicateWindow() ), actionCollection(), "animated_logo" ); - - // Location bar - m_locationLabel = new KonqDraggableLabel( this, i18n("L&ocation: ") ); - (void) new KWidgetAction( m_locationLabel, i18n("L&ocation: "), Key_F6, TQT_TQOBJECT(this), TQT_SLOT( slotLocationLabelActivated() ), actionCollection(), "location_label" ); - m_locationLabel->setBuddy( m_combo ); - - KWidgetAction* comboAction = new KWidgetAction( m_combo, i18n( "Location Bar" ), 0, - 0, 0, actionCollection(), "toolbar_url_combo" ); - comboAction->setShortcutConfigurable( false ); - comboAction->setAutoSized( true ); - - TQWhatsThis::add( m_combo, i18n( "Location Bar

" - "Enter a web address or search term." ) ); - - TDEAction *clearLocation = new TDEAction( i18n( "Clear Location Bar" ), - TQApplication::reverseLayout() ? "clear_left" : "locationbar_erase", - CTRL+Key_L, actionCollection(), "clear_location" ); - connect( clearLocation, TQT_SIGNAL( activated( TDEAction::ActivationReason, TQt::ButtonState ) ), - TQT_SLOT( slotClearLocationBar( TDEAction::ActivationReason, TQt::ButtonState ) ) ); - clearLocation->setWhatsThis( i18n( "Clear Location bar

" - "Clears the content of the location bar." ) ); - - // Bookmarks menu - m_pamBookmarks = new TDEActionMenu( i18n( "&Bookmarks" ), "bookmark", actionCollection(), "bookmarks" ); - m_pamBookmarks->setDelayed( false ); - - // The actual menu needs a different action collection, so that the bookmarks - // don't appear in kedittoolbar - m_bookmarksActionCollection = new TDEActionCollection( this ); - m_bookmarksActionCollection->setHighlightingEnabled( true ); - connectActionCollection( m_bookmarksActionCollection ); - - m_pBookmarkMenu = new KBookmarkMenu( KonqBookmarkManager::self(), m_pBookmarksOwner, m_pamBookmarks->popupMenu(), m_bookmarksActionCollection, true ); - connect( m_pBookmarkMenu, - TQT_SIGNAL( aboutToShowContextMenu(const KBookmark &, TQPopupMenu*) ), - this, TQT_SLOT( slotFillContextMenu(const KBookmark &, TQPopupMenu*) )); - connect( m_pBookmarkMenu, - TQT_SIGNAL( openBookmark(const TQString &, TQt::ButtonState) ), - this, TQT_SLOT( slotOpenBookmarkURL(const TQString &, TQt::ButtonState) )); - - TDEAction *addBookmark = actionCollection()->action("add_bookmark"); - if (addBookmark) - addBookmark->setText(i18n("Bookmark This Location")); - - m_paShowMenuBar = KStdAction::showMenubar( TQT_TQOBJECT(this), TQT_SLOT( slotShowMenuBar() ), actionCollection() ); - - (void) new TDEAction( i18n( "Kon&queror Introduction" ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotIntro() ), actionCollection(), "konqintro" ); - - TDEAction *goUrl = new TDEAction( i18n( "Go" ), "key_enter", 0, TQT_TQOBJECT(this), TQT_SLOT( goURL() ), actionCollection(), "go_url" ); - goUrl->setWhatsThis( i18n( "Go

" - "Goes to the page that has been entered into the location bar." ) ); - - enableAllActions( false ); - - // help stuff - m_paUp->setWhatsThis( i18n( "Enter the parent folder

" - "For instance, if the current location is file:/home/%1 clicking this " - "button will take you to file:/home." ).arg( KUser().loginName() ) ); - m_paUp->setToolTip( i18n( "Enter the parent folder" ) ); - - m_paBack->setWhatsThis( i18n( "Move backwards one step in the browsing history

" ) ); - m_paBack->setToolTip( i18n( "Move backwards one step in the browsing history" ) ); - - m_paForward->setWhatsThis( i18n( "Move forward one step in the browsing history

" ) ); - m_paForward->setToolTip( i18n( "Move forward one step in the browsing history" ) ); - - m_paHome->setWhatsThis( i18n( "Navigate to your 'Home Location'

" - "You can configure the location this button takes you to in the " - "Trinity Control Center, under File Manager/Behavior." ) ); - m_paHome->setToolTip( i18n( "Navigate to your 'Home Location'" ) ); - - m_paReload->setWhatsThis( i18n( "Reload the currently displayed document

" - "This may, for example, be needed to refresh webpages that have been " - "modified since they were loaded, in order to make the changes visible." ) ); - m_paReload->setToolTip( i18n( "Reload the currently displayed document" ) ); - - m_paReloadAllTabs->setWhatsThis( i18n( "Reload all currently displayed documents in tabs

" - "This may, for example, be needed to refresh webpages that have been " - "modified since they were loaded, in order to make the changes visible." ) ); - m_paReloadAllTabs->setToolTip( i18n( "Reload all currently displayed document in tabs" ) ); - - m_paStop->setWhatsThis( i18n( "Stop loading the document

" - "All network transfers will be stopped and Konqueror will display the content " - "that has been received so far." ) ); - m_paStop->setToolTip( i18n( "Stop loading the document" ) ); - - m_paCut->setWhatsThis( i18n( "Cut the currently selected text or item(s) and move it " - "to the system clipboard

" - "This makes it available to the Paste command in Konqueror " - "and other TDE applications." ) ); - m_paCut->setToolTip( i18n( "Move the selected text or item(s) to the clipboard" ) ); - - m_paCopy->setWhatsThis( i18n( "Copy the currently selected text or item(s) to the " - "system clipboard

" - "This makes it available to the Paste command in Konqueror " - "and other TDE applications." ) ); - m_paCopy->setToolTip( i18n( "Copy the selected text or item(s) to the clipboard" ) ); - - m_paPaste->setWhatsThis( i18n( "Paste the previously cut or copied clipboard " - "contents

" - "This also works for text copied or cut from other TDE applications." ) ); - m_paPaste->setToolTip( i18n( "Paste the clipboard contents" ) ); - - m_paPrint->setWhatsThis( i18n( "Print the currently displayed document

" - "You will be presented with a dialog where you can set various " - "options, such as the number of copies to print and which printer " - "to use.

" - "This dialog also provides access to special TDE printing " - "services such as creating a PDF file from the current document." ) ); - m_paPrint->setToolTip( i18n( "Print the current document" ) ); - - - - // Please proof-read those (David) - - m_ptaUseHTML->setToolTip( i18n("If present, open index.html when entering a folder.") ); - m_paLockView->setToolTip( i18n("A locked view cannot change folders. Use in combination with 'link view' to explore many files from one folder") ); - m_paLinkView->setToolTip( i18n("Sets the view as 'linked'. A linked view follows folder changes made in other linked views.") ); -} - -void KonqMainWindow::slotFillContextMenu( const KBookmark &bk, TQPopupMenu * pm ) -{ - kdDebug() << "KonqMainWindow::slotFillContextMenu(bk, pm == " << pm << ")" << endl; - popupItems.clear(); - popupUrlArgs = KParts::URLArgs(); - - //Set tab_new_x to point to the correct icon based on NewTabsInFront - bool newtabsinfront = KonqSettings::newTabsInFront(); - TQString tab_new_x ; - if ( newtabsinfront ) - tab_new_x = "tab_new" ; - else - tab_new_x = "tab_new_bg" ; - - if ( bk.isGroup() ) - { - KBookmarkGroup grp = bk.toGroup(); - TQValueList list = grp.groupUrlList(); - TQValueList::Iterator it = list.begin(); - for (; it != list.end(); ++it ) - popupItems.append( new KFileItem( (*it), TQString::null, KFileItem::Unknown) ); - pm->insertItem( SmallIcon(tab_new_x), i18n( "Open Folder in Tabs" ), this, TQT_SLOT( slotPopupNewTabRight() ) ); - } - else - { - popupItems.append( new KFileItem( bk.url(), TQString::null, KFileItem::Unknown) ); - pm->insertItem( SmallIcon("window-new"), i18n( "Open in New Window" ), this, TQT_SLOT( slotPopupNewWindow() ) ); - pm->insertItem( SmallIcon(tab_new_x), i18n( "Open in New Tab" ), this, TQT_SLOT( slotPopupNewTabRight() ) ); - } -} - -void KonqMainWindow::slotOpenBookmarkURL( const TQString & url, TQt::ButtonState state) -{ - kdDebug(1202) << "KonqMainWindow::slotOpenBookmarkURL(" << url << ", " << state << ")" << endl; - - KonqOpenURLRequest req; - req.newTab = true; - req.newTabInFront = KonqSettings::newTabsInFront(); - - if (state & TQt::ShiftButton) - req.newTabInFront = !req.newTabInFront; - - if( state & TQt::ControlButton ) // Ctrl Left/MMB - openFilteredURL( url, req); - else if( state & Qt::MidButton ) - { - if(KonqSettings::mmbOpensTab()) - openFilteredURL( url, req); - else - { - KURL finalURL = KonqMisc::konqFilteredURL( this, url ); - KonqMisc::createNewWindow( finalURL.url() ); - } - } - else - openFilteredURL( url, false ); -} - -void KonqMainWindow::slotMoveTabLeft() -{ - if ( TQApplication::reverseLayout() ) - m_pViewManager->moveTabForward(); - else - m_pViewManager->moveTabBackward(); -} - -void KonqMainWindow::slotMoveTabRight() -{ - if ( TQApplication::reverseLayout() ) - m_pViewManager->moveTabBackward(); - else - m_pViewManager->moveTabForward(); -} - -void KonqMainWindow::updateToolBarActions( bool pendingAction /*=false*/) -{ - // Enables/disables actions that depend on the current view & url (mostly toolbar) - // Up, back, forward, the edit extension, stop button, wheel - setUpEnabled( m_currentView->url() ); - m_paBack->setEnabled( m_currentView->canGoBack() ); - m_paForward->setEnabled( m_currentView->canGoForward() ); - - if ( m_currentView->isLoading() ) - { - startAnimation(); // takes care of m_paStop - } - else - { - m_paAnimatedLogo->stop(); - m_paStop->setEnabled( pendingAction ); //enable/disable based on any pending actions... - toggleReloadStopButton( pendingAction ); - } - - if ( m_currentView && m_currentView->url().isLocalFile() && - !m_currentView->isLockedViewMode() ) { - if ( m_currentView->serviceTypes().contains( "inode/directory" ) ) - m_ptaUseHTML->setEnabled( true ); - else if ( m_currentView->serviceTypes().contains( "text/html" ) ) { - // Currently viewing an index.html file via this feature (i.e. url points to a dir) - TQString locPath = KURL( m_currentView->locationBarURL() ).path(); - m_ptaUseHTML->setEnabled( TQFileInfo( locPath ).isDir() ); - } else - m_ptaUseHTML->setEnabled( false ); - } - else - { - m_ptaUseHTML->setEnabled( false ); - } -} - -void KonqMainWindow::updateViewActions() -{ - // Update actions that depend on the current view and its mode, or on the number of views etc. - - // Don't do things in this method that depend on m_currentView->url(). - // When going 'back' in history this will be called before opening the url. - // Use updateToolBarActions instead. - - slotUndoAvailable( KonqUndoManager::self()->undoAvailable() ); - - // Can lock a view only if there is a next view - //m_paLockView->setEnabled( m_pViewManager->chooseNextView(m_currentView) != 0L && ); - //kdDebug(1202) << "KonqMainWindow::updateViewActions m_paLockView enabled ? " << m_paLockView->isEnabled() << endl; - - m_paLockView->setEnabled( viewCount() > 1 ); - m_paLockView->setChecked( m_currentView && m_currentView->isLockedLocation() ); - - // Can remove view if we'll still have a main view after that - m_paRemoveView->setEnabled( mainViewsCount() > 1 || - ( m_currentView && m_currentView->isToggleView() ) ); - - KonqFrameBase* docContainer = m_pViewManager->docContainer(); - - if ( docContainer == 0L && !(currentView() && currentView()->frame())) - { - m_paAddTab->setEnabled( false ); - m_paDuplicateTab->setEnabled( false ); - m_paRemoveTab->setEnabled( false ); - m_paRemoveOtherTabs->setEnabled( false ); - m_paBreakOffTab->setEnabled( false ); - m_paActivateNextTab->setEnabled( false ); - m_paActivatePrevTab->setEnabled( false ); - m_paMoveTabLeft->setEnabled( false ); - m_paMoveTabRight->setEnabled( false ); - } - else - { - m_paAddTab->setEnabled( true ); - m_paDuplicateTab->setEnabled( true ); - if ( docContainer && docContainer->frameType() == "Tabs" ) - { - KonqFrameTabs* tabContainer = static_cast(docContainer); - bool state = (tabContainer->count()>1); - m_paRemoveTab->setEnabled( state ); - m_paRemoveOtherTabs->setEnabled( state ); - m_paBreakOffTab->setEnabled( state ); - m_paActivateNextTab->setEnabled( state ); - m_paActivatePrevTab->setEnabled( state ); - - TQPtrList* childFrameList = tabContainer->childFrameList(); - m_paMoveTabLeft->setEnabled( currentView() ? currentView()->frame()!= - (TQApplication::reverseLayout() ? childFrameList->last() : childFrameList->first()) : false ); - m_paMoveTabRight->setEnabled( currentView() ? currentView()->frame()!= - (TQApplication::reverseLayout() ? childFrameList->first() : childFrameList->last()) : false ); - } - else - { - m_paRemoveTab->setEnabled( false ); - m_paRemoveOtherTabs->setEnabled( false ); - m_paBreakOffTab->setEnabled( false ); - m_paActivateNextTab->setEnabled( false ); - m_paActivatePrevTab->setEnabled( false ); - m_paMoveTabLeft->setEnabled( false ); - m_paMoveTabRight->setEnabled( false ); - - } - } - - // Can split a view if it's not a toggle view (because a toggle view can be here only once) - bool isNotToggle = m_currentView && !m_currentView->isToggleView(); - m_paSplitViewHor->setEnabled( isNotToggle ); - m_paSplitViewVer->setEnabled( isNotToggle ); - - m_paLinkView->setChecked( m_currentView && m_currentView->isLinkedView() ); - - if ( m_currentView && m_currentView->part() && - m_currentView->part()->inherits("KonqDirPart") ) - { - KonqDirPart * dirPart = static_cast(m_currentView->part()); - m_paFindFiles->setEnabled( dirPart->findPart() == 0 ); - - TQPtrList lst; - if (!m_paCopyFiles->isPlugged()) - lst.append( m_paCopyFiles ); - if (!m_paMoveFiles->isPlugged()) - lst.append( m_paMoveFiles ); - m_paCopyFiles->setEnabled( false ); - m_paMoveFiles->setEnabled( false ); - if (!lst.isEmpty()) - plugActionList( "operations", lst ); - } - else - { - m_paFindFiles->setEnabled( false ); - unplugActionList( "operations" ); - } -} - -TQString KonqMainWindow::findIndexFile( const TQString &dir ) -{ - TQDir d( dir ); - - TQString f = d.filePath( "index.html", false ); - if ( TQFile::exists( f ) ) - return f; - - f = d.filePath( "index.htm", false ); - if ( TQFile::exists( f ) ) - return f; - - f = d.filePath( "index.HTML", false ); - if ( TQFile::exists( f ) ) - return f; - - return TQString::null; -} - -void KonqMainWindow::connectExtension( KParts::BrowserExtension *ext ) -{ - //kdDebug(1202) << "Connecting extension " << ext << endl; - KParts::BrowserExtension::ActionSlotMap * actionSlotMap = KParts::BrowserExtension::actionSlotMapPtr(); - KParts::BrowserExtension::ActionSlotMap::ConstIterator it = actionSlotMap->begin(); - KParts::BrowserExtension::ActionSlotMap::ConstIterator itEnd = actionSlotMap->end(); - - TQStrList slotNames = ext->metaObject()->slotNames(); - - for ( ; it != itEnd ; ++it ) - { - TDEAction * act = actionCollection()->action( static_cast(it.key()) ); - //kdDebug(1202) << it.key() << endl; - if ( act ) - { - // Does the extension have a slot with the name of this action ? - if ( slotNames.contains( it.key()+"()" ) ) - { - if ( it.key() != "trash" ) - connect( act, TQT_SIGNAL( activated() ), ext, it.data() /* TQT_SLOT(slot name) */ ); - act->setEnabled( ext->isActionEnabled( it.key() ) ); - const TQString text = ext->actionText( it.key() ); - if ( !text.isEmpty() ) - act->setText( text ); - // TODO how to re-set the original action text, when switching to a part that didn't call setAction? - // Can't test with Paste... - } else - act->setEnabled(false); - - } else kdError(1202) << "Error in BrowserExtension::actionSlotMap(), unknown action : " << it.key() << endl; - } - -} - -void KonqMainWindow::disconnectExtension( KParts::BrowserExtension *ext ) -{ - //kdDebug(1202) << "Disconnecting extension " << ext << endl; - KParts::BrowserExtension::ActionSlotMap * actionSlotMap = KParts::BrowserExtension::actionSlotMapPtr(); - KParts::BrowserExtension::ActionSlotMap::ConstIterator it = actionSlotMap->begin(); - KParts::BrowserExtension::ActionSlotMap::ConstIterator itEnd = actionSlotMap->end(); - - TQStrList slotNames = ext->metaObject()->slotNames(); - - for ( ; it != itEnd ; ++it ) - { - TDEAction * act = actionCollection()->action( static_cast(it.key()) ); - //kdDebug(1202) << it.key() << endl; - if ( act && slotNames.contains( it.key()+"()" ) ) - { - //kdDebug(1202) << "disconnectExtension: " << act << " " << act->name() << endl; - act->disconnect( ext ); - } - } -} - -void KonqMainWindow::slotTrashActivated( TDEAction::ActivationReason reason, TQt::ButtonState state ) -{ - if ( !m_currentView ) - return; - if ( reason == TDEAction::PopupMenuActivation && ( state & TQt::ShiftButton ) ) - m_currentView->callExtensionMethod( "del()" ); - else - m_currentView->callExtensionMethod( "trash()" ); -} - -void KonqMainWindow::enableAction( const char * name, bool enabled ) -{ - TDEAction * act = actionCollection()->action( name ); - if (!act) - kdWarning(1202) << "Unknown action " << name << " - can't enable" << endl; - else - { - if ( m_bLocationBarConnected && ( - act==m_paCopy || act==m_paCut || act==m_paPaste || act==m_paDelete || act==m_paTrash ) ) - // Don't change action state while the location bar has focus. - return; - //kdDebug(1202) << "KonqMainWindow::enableAction " << name << " " << enabled << endl; - act->setEnabled( enabled ); - } - - // Update "copy files" and "move files" accordingly - if (m_paCopyFiles && !strcmp( name, "copy" )) - { - m_paCopyFiles->setEnabled( enabled ); - } - else if (m_paMoveFiles && !strcmp( name, "cut" )) - { - m_paMoveFiles->setEnabled( enabled ); - } -} - -void KonqMainWindow::setActionText( const char * name, const TQString& text ) -{ - TDEAction * act = actionCollection()->action( name ); - if (!act) - kdWarning(1202) << "Unknown action " << name << " - can't enable" << endl; - else - { - kdDebug(1202) << "KonqMainWindow::setActionText " << name << " " << text << endl; - act->setText( text ); - } -} - -void KonqMainWindow::currentProfileChanged() -{ - bool enabled = !m_pViewManager->currentProfile().isEmpty(); - m_paSaveViewProfile->setEnabled( enabled ); - m_paSaveViewProfile->setText( enabled ? i18n("&Save View Profile \"%1\"...").arg(m_pViewManager->currentProfileText()) - : i18n("&Save View Profile...") ); -} - -void KonqMainWindow::enableAllActions( bool enable ) -{ - kdDebug(1202) << "KonqMainWindow::enableAllActions " << enable << endl; - KParts::BrowserExtension::ActionSlotMap * actionSlotMap = KParts::BrowserExtension::actionSlotMapPtr(); - - TQValueList actions = actionCollection()->actions(); - TQValueList::Iterator it = actions.begin(); - TQValueList::Iterator end = actions.end(); - for (; it != end; ++it ) - { - TDEAction *act = *it; - if ( !TQString(act->name()).startsWith("options_configure") /* do not touch the configureblah actions */ - && ( !enable || !actionSlotMap->contains( act->name() ) ) ) /* don't enable BE actions */ - act->setEnabled( enable ); - } - // This method is called with enable=false on startup, and - // then only once with enable=true when the first view is setup. - // So the code below is where actions that should initially be disabled are disabled. - if (enable) - { - setUpEnabled( m_currentView ? m_currentView->url() : KURL() ); - // we surely don't have any history buffers at this time - m_paBack->setEnabled( false ); - m_paForward->setEnabled( false ); - - // Load profile submenu - m_pViewManager->profileListDirty( false ); - - currentProfileChanged(); - - updateViewActions(); // undo, lock, link and other view-dependent actions - - m_paStop->setEnabled( m_currentView && m_currentView->isLoading() ); - toggleReloadStopButton( m_currentView && m_currentView->isLoading() ); - - if (m_toggleViewGUIClient) - { - TQPtrList actions = m_toggleViewGUIClient->actions(); - for ( TDEAction * it = actions.first(); it ; it = actions.next() ) - it->setEnabled( true ); - } - - } - actionCollection()->action( "quit" )->setEnabled( true ); -} - -void KonqMainWindow::disableActionsNoView() -{ - // No view -> there are some things we can't do - m_paUp->setEnabled( false ); - m_paReload->setEnabled( false ); - m_paReloadAllTabs->setEnabled( false ); - m_paBack->setEnabled( false ); - m_paForward->setEnabled( false ); - m_ptaUseHTML->setEnabled( false ); - m_pMenuNew->setEnabled( false ); - m_paLockView->setEnabled( false ); - m_paLockView->setChecked( false ); - m_paSplitViewVer->setEnabled( false ); - m_paSplitViewHor->setEnabled( false ); - m_paRemoveView->setEnabled( false ); - m_paLinkView->setEnabled( false ); - if (m_toggleViewGUIClient) - { - TQPtrList actions = m_toggleViewGUIClient->actions(); - for ( TDEAction * it = actions.first(); it ; it = actions.next() ) - it->setEnabled( false ); - } - // There are things we can do, though : bookmarks, view profile, location bar, new window, - // settings, etc. - m_paHome->setEnabled( true ); - m_pamBookmarks->setEnabled( true ); - static const char* const s_enActions[] = { "new_window", "duplicate_window", "open_location", - "toolbar_url_combo", "clear_location", "animated_logo", - "konqintro", "go_most_often", "go_applications", "go_dirtree", - "go_trash", "go_settings", "go_network_folders", "go_autostart", - "go_url", "go_media", "go_history", "options_configure_extensions", 0 }; - for ( int i = 0 ; s_enActions[i] ; ++i ) - { - TDEAction * act = action(s_enActions[i]); - if (act) - act->setEnabled( true ); - } - m_pamLoadViewProfile->setEnabled( true ); - m_paSaveViewProfile->setEnabled( true ); - m_paSaveRemoveViewProfile->setEnabled( true ); - m_combo->clearTemporary(); - updateLocalPropsActions(); -} - -void KonqExtendedBookmarkOwner::openBookmarkURL( const TQString & /*url*/ ) -{ - // Do nothing, we catch the signal -} - -void KonqMainWindow::setCaption( const TQString &caption ) -{ - // KParts sends us empty captions when activating a brand new part - // We can't change it there (in case of apps removing all parts altogether) - // but here we never do that. - if ( !caption.isEmpty() && m_currentView ) - { - kdDebug(1202) << "KonqMainWindow::setCaption(" << caption << ")" << endl; - - // Keep an unmodified copy of the caption (before kapp->makeStdCaption is applied) - m_currentView->setCaption( caption ); - KParts::MainWindow::setCaption( m_currentView->caption() ); - } -} - -void KonqMainWindow::show() -{ - // We need to check if our toolbars are shown/hidden here, and set - // our menu items accordingly. We can't do it in the constructor because - // view profiles store toolbar info, and that info is read after - // construct time. - m_paShowMenuBar->setChecked( !menuBar()->isHidden() ); - updateBookmarkBar(); // hide if empty - - // Call parent method - KParts::MainWindow::show(); -} - -TQString KonqExtendedBookmarkOwner::currentURL() const -{ - return m_pKonqMainWindow->currentURL(); -} - -TQString KonqMainWindow::currentProfile() const -{ - return m_pViewManager->currentProfile(); -} - -TQString KonqMainWindow::currentURL() const -{ - if ( !m_currentView ) - return TQString::null; - TQString url = m_currentView->url().prettyURL(); - if ( m_currentView->part() && m_currentView->part()->inherits("KonqDirPart") ) - { - TQString nameFilter = static_cast(m_currentView->part())->nameFilter(); - if ( !nameFilter.isEmpty() ) - { - if (!url.endsWith("/")) - url += '/'; - url += nameFilter; - } - } - return url; -} - -void KonqExtendedBookmarkOwner::slotFillBookmarksList( KExtendedBookmarkOwner::QStringPairList & list ) -{ - KonqFrameBase *docContainer = m_pKonqMainWindow->viewManager()->docContainer(); - if (docContainer == 0L) return; - if (docContainer->frameType() != "Tabs") return; - - KonqFrameTabs* tabContainer = static_cast(docContainer); - - TQPtrList frameList = *tabContainer->childFrameList(); - TQPtrListIterator it( frameList ); - - for ( it.toFirst(); it != 0L; ++it ) - { - if ( !it.current()->activeChildView() ) - continue; - if( it.current()->activeChildView()->locationBarURL().isEmpty() ) - continue; - list << qMakePair( it.current()->activeChildView()->caption(), - it.current()->activeChildView()->url().url() ); - } -} - -TQString KonqExtendedBookmarkOwner::currentTitle() const -{ - return m_pKonqMainWindow->currentTitle(); -} - -TQString KonqMainWindow::currentTitle() const -{ - return m_currentView ? m_currentView->caption() : TQString::null; -} - -void KonqMainWindow::slotPopupMenu( const TQPoint &_global, const KURL &url, const TQString &_mimeType, mode_t _mode ) -{ - slotPopupMenu( 0L, _global, url, _mimeType, _mode ); -} - -void KonqMainWindow::slotPopupMenu( KXMLGUIClient *client, const TQPoint &_global, const KURL &url, const TQString &_mimeType, mode_t _mode ) -{ - KFileItem item( url, _mimeType, _mode ); - KFileItemList items; - items.append( &item ); - slotPopupMenu( client, _global, items, KParts::URLArgs(), KParts::BrowserExtension::DefaultPopupItems, false ); //BE CAREFUL WITH sender() ! -} - -void KonqMainWindow::slotPopupMenu( KXMLGUIClient *client, const TQPoint &_global, const KURL &url, const KParts::URLArgs &_args, KParts::BrowserExtension::PopupFlags f, mode_t _mode ) -{ - KFileItem item( url, _args.serviceType, _mode ); - KFileItemList items; - items.append( &item ); - slotPopupMenu( client, _global, items, _args, f, false ); //BE CAREFUL WITH sender() ! -} - -void KonqMainWindow::slotPopupMenu( const TQPoint &_global, const KFileItemList &_items ) -{ - slotPopupMenu( 0L, _global, _items ); -} - -void KonqMainWindow::slotPopupMenu( KXMLGUIClient *client, const TQPoint &_global, const KFileItemList &_items ) -{ - slotPopupMenu( client, _global, _items, KParts::URLArgs(), KParts::BrowserExtension::DefaultPopupItems, true ); -} - -void KonqMainWindow::slotPopupMenu( KXMLGUIClient *client, const TQPoint &_global, const KFileItemList &_items, const KParts::URLArgs &_args, KParts::BrowserExtension::PopupFlags _flags ) -{ - slotPopupMenu( client, _global, _items, _args, _flags, true ); -} - -void KonqMainWindow::slotPopupMenu( KXMLGUIClient *client, const TQPoint &_global, const KFileItemList &_items, const KParts::URLArgs &_args, KParts::BrowserExtension::PopupFlags itemFlags, bool showProperties ) -{ - KonqView * m_oldView = m_currentView; - - KonqView * currentView = childView( static_cast( TQT_TQOBJECT_CONST(sender())->parent() ) ); - - //kdDebug() << "KonqMainWindow::slotPopupMenu m_oldView=" << m_oldView << " new currentView=" << currentView << " passive:" << currentView->isPassiveMode() << endl; - - if ( (m_oldView != currentView) && currentView->isPassiveMode() ) - { - // Make this view active only temporarily (because it's passive) - m_currentView = currentView; - - if ( m_oldView && m_oldView->browserExtension() ) - disconnectExtension( m_oldView->browserExtension() ); - if ( m_currentView->browserExtension() ) - connectExtension( m_currentView->browserExtension() ); - } - // Note that if m_oldView!=currentView and currentView isn't passive, - // then the KParts mechanism has already noticed the click in it, - // but KonqViewManager delays the GUI-rebuilding with a single-shot timer. - // Right after the popup shows up, currentView _will_ be m_currentView. - - //kdDebug(1202) << "KonqMainWindow::slotPopupMenu( " << client << "...)" << " current view=" << m_currentView << " " << m_currentView->part()->className() << endl; - - // This action collection is used to pass actions to KonqPopupMenu. - // It has to be a TDEActionCollection instead of a TDEActionPtrList because we need - // the actionStatusText signal... - TDEActionCollection popupMenuCollection( (TQWidget*)0 ); - popupMenuCollection.insert( m_paBack ); - popupMenuCollection.insert( m_paForward ); - popupMenuCollection.insert( m_paUp ); - popupMenuCollection.insert( m_paReload ); - - popupMenuCollection.insert( m_paFindFiles ); - - popupMenuCollection.insert( m_paUndo ); - popupMenuCollection.insert( m_paCut ); - popupMenuCollection.insert( m_paCopy ); - popupMenuCollection.insert( m_paPaste ); - popupMenuCollection.insert( m_paTrash ); - popupMenuCollection.insert( m_paRename ); - popupMenuCollection.insert( m_paDelete ); - - // The pasteto action is used when clicking on a dir, to paste into it. - TDEAction *actPaste = KStdAction::paste( TQT_TQOBJECT(this), TQT_SLOT( slotPopupPasteTo() ), &popupMenuCollection, "pasteto" ); - actPaste->setEnabled( m_paPaste->isEnabled() ); - popupMenuCollection.insert( actPaste ); - - bool sReading = false; - if ( _items.count() > 0 ) - { - m_popupURL = _items.getFirst()->url(); - sReading = KProtocolInfo::supportsReading( m_popupURL ); - if (sReading) - m_popupServiceType = _items.getFirst()->mimetype(); - } - else - { - m_popupURL = KURL(); - m_popupServiceType = TQString::null; - } - - if ( (_items.count() == 1) && !m_popupServiceType.isEmpty() ) { - TQString currentServiceName = currentView->service()->desktopEntryName(); - - // List of services for the "Preview In" submenu. - m_popupEmbeddingServices = TDETrader::self()->query( - m_popupServiceType, - "KParts/ReadOnlyPart", - // Obey "HideFromMenus". It defaults to false so we want "absent or true" - // (wow, testing for 'true' if absent doesn't work, so order matters) - "(not exist [X-TDE-BrowserView-HideFromMenus] or not [X-TDE-BrowserView-HideFromMenus]) " - "and DesktopEntryName != '"+currentServiceName+"' " - // I had an old local dirtree.desktop without lib, no need for invalid entries - "and exist [Library]", - TQString::null ); - } - - - // Don't set the view URL for a toggle view. - // (This is a bit of a hack for the directory tree....) - // ## should use the new currentView->isHierarchicalView() instead? - // Would this be correct for the konqlistview tree view? - KURL viewURL = currentView->isToggleView() ? KURL() : currentView->url(); - - bool openedForViewURL = false; - //bool dirsSelected = false; - bool devicesFile = false; - - if ( _items.count() == 1 ) - { - KURL firstURL = _items.getFirst()->url(); - if ( !viewURL.isEmpty() ) - { - //firstURL.cleanPath(); - openedForViewURL = firstURL.equals( viewURL, true ); - } - devicesFile = firstURL.protocol().find("device", 0, false) == 0; - //dirsSelected = S_ISDIR( _items.getFirst()->mode() ); - } - //check if current url is trash - KURL url = viewURL; - url.cleanPath(); - bool isIntoTrash = url.protocol() == "trash" || url.url().startsWith( "system:/trash" ); - bool doTabHandling = !openedForViewURL && !isIntoTrash && sReading; - bool showEmbeddingServices = !isIntoTrash && !devicesFile && (itemFlags & KParts::BrowserExtension::ShowTextSelectionItems) == 0; - PopupMenuGUIClient *konqyMenuClient = new PopupMenuGUIClient( this, m_popupEmbeddingServices, - showEmbeddingServices, doTabHandling ); - - //kdDebug(1202) << "KonqMainWindow::slotPopupMenu " << viewURL.prettyURL() << endl; - - - // Those actions go into the PopupMenuGUIClient, since that's the one defining them. - TDEAction *actNewWindow = 0L; - if (doTabHandling) - { - if (_args.forcesNewWindow()) { - actNewWindow = new TDEAction( i18n( "Open in T&his Window" ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotPopupThisWindow() ), konqyMenuClient->actionCollection(), "sameview" ); - actNewWindow->setToolTip( i18n( "Open the document in current window" ) ); - } - actNewWindow = new TDEAction( i18n( "Open in New &Window" ), "window-new", 0, TQT_TQOBJECT(this), TQT_SLOT( slotPopupNewWindow() ), konqyMenuClient->actionCollection(), "newview" ); - actNewWindow->setToolTip( i18n( "Open the document in a new window" ) ); - - //Set tab_new_x to point to the correct icon based on NewTabsInFront - bool newtabsinfront = KonqSettings::newTabsInFront(); - TQString tab_new_x ; - if ( newtabsinfront ) - tab_new_x = "tab_new" ; - else - tab_new_x = "tab_new_bg" ; - - TDEAction *actNewTab = new TDEAction( i18n( "Open in &Background Tab" ), "tab_new_bg", 0, TQT_TQOBJECT(this), TQT_SLOT( slotPopupNewTab() ), actionCollection(), "openintab" ); - actNewTab->setStatusText( i18n( "Open the document in a new background tab" ) ); - TDEAction *actNewTabFront = new TDEAction( i18n( "Open in &New Tab" ), "tab_new", 0, TQT_TQOBJECT(this), TQT_SLOT( slotPopupNewTabAtFront() ), actionCollection(), "openintabfront" ); - actNewTabFront->setStatusText( i18n( "Open the document in a new foreground tab" ) ); - actNewTab = new TDEAction( i18n( "Open in &Background Tab" ), tab_new_x, 0, TQT_TQOBJECT(this), TQT_SLOT( slotPopupNewTab() ), konqyMenuClient->actionCollection(), "openintab" ); - actNewTabFront = new TDEAction( i18n( "Open in &New Tab" ), tab_new_x, 0, TQT_TQOBJECT(this), TQT_SLOT( slotPopupNewTabAtFront() ), konqyMenuClient->actionCollection(), "openintabfront" ); - actNewTab->setToolTip( i18n( "Open the document in a new background tab" ) ); - actNewTabFront->setToolTip( i18n( "Open the document in a new foreground tab" ) ); - doTabHandling = true; - } - - if (currentView->isHierarchicalView()) - itemFlags |= KParts::BrowserExtension::ShowCreateDirectory; - - KonqPopupMenu::KonqPopupFlags kpf = 0; - if ( showProperties ) - kpf |= KonqPopupMenu::ShowProperties; - else - kpf |= KonqPopupMenu::IsLink; // HACK - - TQGuardedPtr pPopupMenu = new KonqPopupMenu( - KonqBookmarkManager::self(), _items, - viewURL, - popupMenuCollection, - m_pMenuNew, - // This parent ensures that if the part destroys itself (e.g. TDEHTML redirection), - // it will close the popupmenu - currentView->part()->widget(), - kpf, - itemFlags ); - - if ( openedForViewURL && !viewURL.isLocalFile() ) - pPopupMenu->setURLTitle( currentView->caption() ); - - // We will need these if we call the newTab slot - popupItems = _items; - popupUrlArgs = _args; - popupUrlArgs.serviceType = TQString::null; // Reset so that Open in New Window/Tab does mimetype detection - - connectActionCollection( pPopupMenu->actionCollection() ); - - if (pPopupMenu->hasGroup("tabhandling")) - { - // "tabhandling" group in inserted in the popup menu if no encrypted media devices are part of "_items" - // see libkonq/konq_popupmenu.cc KonqPopupMenu::setup() method - pPopupMenu->factory()->addClient( konqyMenuClient ); - } - - if ( client ) - pPopupMenu->factory()->addClient( client ); - - KParts::BrowserExtension *be = ::tqqt_cast(sender()); - - if ( be ) - { - TQObject::connect( this, TQT_SIGNAL(popupItemsDisturbed()), pPopupMenu, TQT_SLOT(close()) ); - TQObject::connect( be, TQT_SIGNAL(itemsRemoved(const KFileItemList &)), - this, TQT_SLOT(slotItemsRemoved(const KFileItemList &)) ); - } - - TQObject::disconnect( m_pMenuNew->popupMenu(), TQT_SIGNAL(aboutToShow()), - this, TQT_SLOT(slotFileNewAboutToShow()) ); - - TQGuardedPtr guard(TQT_TQOBJECT(this)); // #149736 - pPopupMenu->exec( _global ); - - delete pPopupMenu; - - // We're sort of misusing TDEActionCollection here, but we need it for the actionStatusText signal... - // Anyway. If the action belonged to the view, and the view got deleted, we don't want ~TDEActionCollection - // to iterate over those deleted actions - TDEActionPtrList lst = popupMenuCollection.actions(); - TDEActionPtrList::iterator it = lst.begin(); - for ( ; it != lst.end() ; ++it ) - popupMenuCollection.take( *it ); - - if (guard.isNull()) { // the placement of this test is very important, double-check #149736 if moving stuff around - return; - } - - TQObject::connect( m_pMenuNew->popupMenu(), TQT_SIGNAL(aboutToShow()), - this, TQT_SLOT(slotFileNewAboutToShow()) ); - - if ( be ) - { - TQObject::disconnect( be, TQT_SIGNAL(itemsRemoved(const KFileItemList &)), - this, TQT_SLOT(slotItemsRemoved(const KFileItemList &)) ); - } - - delete konqyMenuClient; - m_popupEmbeddingServices.clear(); - popupItems.clear(); - - // Deleted by konqyMenuClient's actioncollection - //delete actNewWindow; - - delete actPaste; - - - //kdDebug(1202) << "-------- KonqMainWindow::slotPopupMenu() - m_oldView = " << m_oldView << ", currentView = " << currentView - //<< ", m_currentView = " << m_currentView << endl; - - // Restore current view if current is passive - if ( (m_oldView != currentView) && (currentView == m_currentView) && currentView->isPassiveMode() ) - { - //kdDebug() << "KonqMainWindow::slotPopupMenu restoring active view " << m_oldView << endl; - if ( m_currentView->browserExtension() ) - disconnectExtension( m_currentView->browserExtension() ); - if ( m_oldView ) - { - if ( m_oldView->browserExtension() ) - { - connectExtension( m_oldView->browserExtension() ); - m_currentView = m_oldView; - } - // Special case: RMB + renaming in sidebar; setFocus would abort editing. - TQWidget* fw = focusWidget(); - if ( !fw || !::tqqt_cast( fw ) ) - m_oldView->part()->widget()->setFocus(); - } - } -} - -void KonqMainWindow::slotItemsRemoved( const KFileItemList &items ) -{ - TQPtrListIterator it( items ); - for ( ; it.current(); ++it ) - { - if ( popupItems.contains( it.current() ) ) - { - emit popupItemsDisturbed(); - return; - } - } -} - -void KonqMainWindow::slotOpenEmbedded() -{ - TQCString name = TQT_TQOBJECT_CONST(sender())->name(); - - m_popupService = m_popupEmbeddingServices[ name.toInt() ]->desktopEntryName(); - - m_popupEmbeddingServices.clear(); - - TQTimer::singleShot( 0, this, TQT_SLOT( slotOpenEmbeddedDoIt() ) ); -} - -void KonqMainWindow::slotOpenEmbeddedDoIt() -{ - m_currentView->stop(); - m_currentView->setLocationBarURL(m_popupURL); - m_currentView->setTypedURL(TQString::null); - if ( m_currentView->changeViewMode( m_popupServiceType, - m_popupService ) ) - m_currentView->openURL( m_popupURL, m_popupURL.pathOrURL() ); -} - -void KonqMainWindow::slotDatabaseChanged() -{ - if ( KSycoca::isChanged("mimetypes") ) - { - MapViews::ConstIterator it = m_mapViews.begin(); - MapViews::ConstIterator end = m_mapViews.end(); - for (; it != end; ++it ) - (*it)->callExtensionMethod( "refreshMimeTypes()" ); - } -} - -void KonqMainWindow::slotPopupPasteTo() -{ - if ( !m_currentView || m_popupURL.isEmpty() ) - return; - m_currentView->callExtensionURLMethod( "pasteTo(const KURL&)", m_popupURL ); -} - -void KonqMainWindow::slotReconfigure() -{ - reparseConfiguration(); -} - -void KonqMainWindow::reparseConfiguration() -{ - kdDebug(1202) << "KonqMainWindow::reparseConfiguration() !" << endl; - - KonqSettings::self()->readConfig(); - - m_bSaveViewPropertiesLocally = KonqSettings::saveViewPropertiesLocally(); - m_bHTMLAllowed = KonqSettings::htmlAllowed(); - - MapViews::ConstIterator it = m_mapViews.begin(); - MapViews::ConstIterator end = m_mapViews.end(); - for (; it != end; ++it ) - (*it)->reparseConfiguration(); - - // Push updates to KonqViewManager as well - viewManager()->reparseConfiguration(); -} - -void KonqMainWindow::saveProperties( TDEConfig *config ) -{ - m_pViewManager->saveViewProfile( *config, true /* save URLs */, false ); -} - -void KonqMainWindow::readProperties( TDEConfig *config ) -{ - kdDebug(1202) << "KonqMainWindow::readProperties( TDEConfig *config )" << endl; - m_pViewManager->loadViewProfile( *config, TQString::null /*no profile name*/ ); -} - -void KonqMainWindow::setInitialFrameName( const TQString &name ) -{ - m_initialFrameName = name; -} - -void KonqMainWindow::slotActionStatusText( const TQString &text ) -{ - if ( !m_currentView ) - return; - - KonqFrameStatusBar *statusBar = m_currentView->frame()->statusbar(); - - if ( !statusBar ) - return; - - statusBar->message( text ); -} - -void KonqMainWindow::slotClearStatusText() -{ - if ( !m_currentView ) - return; - - KonqFrameStatusBar *statusBar = m_currentView->frame()->statusbar(); - - if ( !statusBar ) - return; - - statusBar->slotClear(); -} - -void KonqMainWindow::updateOpenWithActions() -{ - unplugActionList( "openwith" ); - - m_openWithActions.clear(); - - if (!kapp->authorizeTDEAction("openwith")) - return; - - const TDETrader::OfferList & services = m_currentView->appServiceOffers(); - TDETrader::OfferList::ConstIterator it = services.begin(); - TDETrader::OfferList::ConstIterator end = services.end(); - for (; it != end; ++it ) - { - TDEAction *action = new TDEAction( i18n( "Open with %1" ).arg( (*it)->name() ), 0, 0, (*it)->desktopEntryName().latin1() ); - action->setIcon( (*it)->icon() ); - - connect( action, TQT_SIGNAL( activated() ), - this, TQT_SLOT( slotOpenWith() ) ); - - m_openWithActions.append( action ); - } - if ( services.count() > 0 ) - { - m_openWithActions.append( new TDEActionSeparator ); - plugActionList( "openwith", m_openWithActions ); - } -} - -TQString KonqMainWindow::viewModeActionKey( KService::Ptr service ) -{ - TQString library = service->library(); - // Group all non-builtin views together - TQVariant builtIntoProp = service->property( "X-TDE-BrowserView-Built-Into" ); - if ( !builtIntoProp.isValid() || builtIntoProp.toString() != "konqueror" ) - library = "external"; - return library; -} - -void KonqMainWindow::updateViewModeActions() -{ - unplugViewModeActions(); - if ( m_viewModeMenu ) - { - TQPtrListIterator it( m_viewModeActions ); - for (; it.current(); ++it ) - it.current()->unplugAll(); - delete m_viewModeMenu; - } - - m_viewModeMenu = 0; - m_toolBarViewModeActions.clear(); - m_viewModeActions.clear(); - - // if we changed the viewmode to something new, then we have to - // make sure to also clear our [libiconview,liblistview]->service-for-viewmode - // map - if ( m_viewModeToolBarServices.count() > 0 && - !m_viewModeToolBarServices.begin().data()->serviceTypes().contains( m_currentView->serviceType() ) ) - { - // Save the current map to the config file, for later reuse - saveToolBarServicesMap(); - - m_viewModeToolBarServices.clear(); - } - - TDETrader::OfferList services = m_currentView->partServiceOffers(); - - if ( services.count() <= 1 ) - return; - - m_viewModeMenu = new TDEActionMenu( i18n( "&View Mode" ), TQT_TQOBJECT(this) ); - - // a temporary map, just like the m_viewModeToolBarServices map, but - // mapping to a KonqViewModeAction object. It's just temporary as we - // of use it to group the viewmode actions (iconview,multicolumnview, - // treeview, etc.) into to two groups -> icon/list - // Although I wrote this now only of icon/listview it has to work for - // any view, that's why it's so general :) - TQMap groupedServiceMap; - - // Another temporary map, the preferred service for each library (2 entries in our example) - TQMap preferredServiceMap; - - TDEConfig * config = TDEGlobal::config(); - config->setGroup( "ModeToolBarServices" ); - - TDETrader::OfferList::ConstIterator it = services.begin(); - TDETrader::OfferList::ConstIterator end = services.end(); - for (; it != end; ++it ) - { - TQVariant prop = (*it)->property( "X-TDE-BrowserView-Toggable" ); - if ( prop.isValid() && prop.toBool() ) // No toggable views in view mode - continue; - - TDERadioAction *action; - - TQString itname = (*it)->genericName(); - if (itname.isEmpty()) - itname = (*it)->name(); - - TQString icon = (*it)->icon(); - if ( icon != TQString::fromLatin1( "unknown" ) ) - // we *have* to specify a parent qobject, otherwise the exclusive group stuff doesn't work!(Simon) - action = new TDERadioAction( itname, icon, 0, TQT_TQOBJECT(this), (*it)->desktopEntryName().ascii() ); - else - action = new TDERadioAction( itname, 0, TQT_TQOBJECT(this), (*it)->desktopEntryName().ascii() ); - - action->setExclusiveGroup( "KonqMainWindow_ViewModes" ); - - connect( action, TQT_SIGNAL( toggled( bool ) ), - this, TQT_SLOT( slotViewModeToggle( bool ) ) ); - - m_viewModeActions.append( action ); - action->plug( m_viewModeMenu->popupMenu() ); - - const TQString library = viewModeActionKey( *it ); - - // look if we already have a KonqViewModeAction (in the toolbar) - // for this component - TQMap::Iterator mapIt = groupedServiceMap.find( library ); - - // if we don't have -> create one - if ( mapIt == groupedServiceMap.end() ) - { - // default service on this action: the current one (i.e. the first one) - TQString text = itname; - TQString icon = (*it)->icon(); - TQCString name = (*it)->desktopEntryName().latin1(); - //kdDebug(1202) << " Creating action for " << library << ". Default service " << itname << endl; - - // if we previously changed the viewmode (see slotViewModeToggle!) - // then we will want to use the previously used settings (previous as - // in before the actions got deleted) - TQMap::ConstIterator serviceIt = m_viewModeToolBarServices.find( library ); - if ( serviceIt != m_viewModeToolBarServices.end() ) - { - kdDebug(1202) << " Setting action for " << library << " to " << (*serviceIt)->name() << endl; - text = (*serviceIt)->genericName(); - if (text.isEmpty()) - text = (*serviceIt)->name(); - icon = (*serviceIt)->icon(); - name = (*serviceIt)->desktopEntryName().ascii(); - } else - { - // if we don't have it in the map, we should look for a setting - // for this library in the config file. - TQString preferredService = config->readEntry( library ); - if ( !preferredService.isEmpty() && name != preferredService.latin1() ) - { - //kdDebug(1202) << " Inserting into preferredServiceMap(" << library << ") : " << preferredService << endl; - // The preferred service isn't the current one, so remember to set it later - preferredServiceMap[ library ] = preferredService; - } - } - - KonqViewModeAction *tbAction = new KonqViewModeAction( text, - icon, - TQT_TQOBJECT(this), - name ); - - tbAction->setExclusiveGroup( "KonqMainWindow_ToolBarViewModes" ); - - tbAction->setChecked( action->isChecked() ); - - connect( tbAction, TQT_SIGNAL( toggled( bool ) ), - this, TQT_SLOT( slotViewModeToggle( bool ) ) ); - - m_toolBarViewModeActions.append( tbAction ); - - mapIt = groupedServiceMap.insert( library, tbAction ); - } - - // Check the actions (toolbar button and menu item) if they correspond to the current view - bool bIsCurrentView = (*it)->desktopEntryName() == m_currentView->service()->desktopEntryName(); - if ( bIsCurrentView ) - { - action->setChecked( true ); - } - - // Set the contents of the button from the current service, either if it's the current view - // or if it's our preferred service for this button (library) - if ( bIsCurrentView - || ( preferredServiceMap.contains( library ) && (*it)->desktopEntryName() == preferredServiceMap[ library ] ) ) - { - //kdDebug(1202) << " Changing action for " << library << " into service " << (*it)->name() << endl; - - TQString mapitname = (*it)->genericName(); - if (mapitname.isEmpty()) - mapitname = (*it)->name(); - (*mapIt)->setText( mapitname ); - (*mapIt)->setIcon( (*it)->icon() ); - (*mapIt)->setName( (*it)->desktopEntryName().ascii() ); // tricky... - preferredServiceMap.remove( library ); // The current view has priority over the saved settings - } - - // plug action also into the delayed popupmenu of appropriate toolbar action - action->plug( (*mapIt)->popupMenu() ); - } - -#ifndef NDEBUG - // Note that this can happen (map not empty) when a inode/directory view is removed, - // and remains in the TDEConfig file. - Q_ASSERT( preferredServiceMap.isEmpty() ); - TQMap::Iterator debugIt = preferredServiceMap.begin(); - TQMap::Iterator debugEnd = preferredServiceMap.end(); - for ( ; debugIt != debugEnd ; ++debugIt ) - kdDebug(1202) << " STILL IN preferredServiceMap : " << debugIt.key() << " | " << debugIt.data() << endl; -#endif - - if ( !m_currentView->isToggleView() ) // No view mode for toggable views - // (The other way would be to enforce a better servicetype for them, than Browser/View) - if ( /* already tested: services.count() > 1 && */ m_viewModeMenu ) - plugViewModeActions(); -} - -void KonqMainWindow::saveToolBarServicesMap() -{ - TQMap::ConstIterator serviceIt = m_viewModeToolBarServices.begin(); - TQMap::ConstIterator serviceEnd = m_viewModeToolBarServices.end(); - TDEConfig * config = TDEGlobal::config(); - config->setGroup( "ModeToolBarServices" ); - for ( ; serviceIt != serviceEnd ; ++serviceIt ) - config->writeEntry( serviceIt.key(), serviceIt.data()->desktopEntryName() ); - config->sync(); -} - -void KonqMainWindow::plugViewModeActions() -{ - TQPtrList lst; - lst.append( m_viewModeMenu ); - plugActionList( "viewmode", lst ); - // display the toolbar viewmode icons only for inode/directory, as here we have dedicated icons - if ( m_currentView && m_currentView->supportsServiceType( "inode/directory" ) ) - plugActionList( "viewmode_toolbar", m_toolBarViewModeActions ); -} - -void KonqMainWindow::unplugViewModeActions() -{ - unplugActionList( "viewmode" ); - unplugActionList( "viewmode_toolbar" ); -} - -KonqMainWindowIface* KonqMainWindow::dcopObject() -{ - return m_dcopObject; -} - -void KonqMainWindow::updateBookmarkBar() -{ - TDEToolBar * bar = static_cast( TQT_TQWIDGET(child( "bookmarkToolBar", "TDEToolBar" )) ); - - if (!bar) return; - - // hide if empty - if (m_paBookmarkBar && bar->count() == 0 ) - bar->hide(); - -} - -void KonqMainWindow::closeEvent( TQCloseEvent *e ) -{ - kdDebug(1202) << "KonqMainWindow::closeEvent begin" << endl; - // This breaks session management (the window is withdrawn in twin) - // so let's do this only when closed by the user. - if ( static_cast(kapp)->closedByUser() ) - { - if ( viewManager()->docContainer() && viewManager()->docContainer()->frameType()=="Tabs" ) - { - KonqFrameTabs* tabContainer = static_cast(viewManager()->docContainer()); - if ( tabContainer->count() > 1 ) - { - TDEConfig *config = TDEGlobal::config(); - TDEConfigGroupSaver cs( config, TQString::fromLatin1("Notification Messages") ); - - if ( !config->hasKey( "MultipleTabConfirm" ) ) - { - switch ( - KMessageBox::warningYesNoCancel( - this, - i18n("You have multiple tabs open in this window, " - "are you sure you want to quit?"), - i18n("Confirmation"), - KStdGuiItem::quit(), - KGuiItem(i18n( "C&lose Current Tab" ), "tab_remove"), - "MultipleTabConfirm" - ) - ) { - case KMessageBox::Yes : - break; - case KMessageBox::No : - { - e->ignore(); - slotRemoveTab(); - return; - } - break; - case KMessageBox::Cancel : - { - e->ignore(); - return; - } - } - } - } - - KonqView *originalView = m_currentView; - MapViews::ConstIterator it = m_mapViews.begin(); - MapViews::ConstIterator end = m_mapViews.end(); - for (; it != end; ++it ) { - KonqView *view = it.data(); - if (view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1) ) { - TQVariant prop = view->part()->property("modified"); - if (prop.isValid() && prop.toBool()) { - m_pViewManager->showTab( view ); - if ( KMessageBox::warningContinueCancel( this, - i18n("This tab contains changes that have not been submitted.\nClosing the window will discard these changes."), - i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"system-log-out"), "discardchangesclose") != KMessageBox::Continue ) - { - e->ignore(); - m_pViewManager->showTab( originalView ); - return; - } - } - } - } -// m_pViewManager->showTab( originalView ); - } - else if ( m_currentView && m_currentView->part() && - (m_currentView->part()->metaObject()->findProperty("modified") != -1) ) - { - TQVariant prop = m_currentView->part()->property("modified"); - if (prop.isValid() && prop.toBool()) - if ( KMessageBox::warningContinueCancel( this, - i18n("This page contains changes that have not been submitted.\nClosing the window will discard these changes."), - i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"system-log-out"), "discardchangesclose") != KMessageBox::Continue ) - { - e->ignore(); - return; - } - } - - // save size to have something to restore if the profile does not contain size - saveWindowSize(); - - hide(); - tqApp->flushX(); - } - // We're going to close - tell the parts - MapViews::ConstIterator it = m_mapViews.begin(); - MapViews::ConstIterator end = m_mapViews.end(); - for (; it != end; ++it ) - { - if ( (*it)->part() && (*it)->part()->widget() ) - TQApplication::sendEvent( (*it)->part()->widget(), e ); - } - KParts::MainWindow::closeEvent( e ); - if( isPreloaded() && !kapp->sessionSaving()) - { // queryExit() refused closing, hide instead - hide(); - } - kdDebug(1202) << "KonqMainWindow::closeEvent end" << endl; -} - -bool KonqMainWindow::queryExit() -{ - if( kapp->sessionSaving()) // *sigh* - return true; - return !stayPreloaded(); -} - -void KonqMainWindow::setIcon( const TQPixmap& pix ) -{ - KParts::MainWindow::setIcon( pix ); - - TQPixmap big = pix; - - TQString url = m_combo->currentText(); - - if ( !url.isEmpty() ) - big = KonqPixmapProvider::self()->pixmapFor( url, TDEIcon::SizeMedium ); - - KWin::setIcons( winId(), big, pix ); -} - -void KonqMainWindow::slotIntro() -{ - openURL( 0L, KURL("about:konqueror") ); -} - -void KonqMainWindow::goURL() -{ - TQLineEdit *lineEdit = m_combo->lineEdit(); - if ( !lineEdit ) - return; - - TQKeyEvent event( TQEvent::KeyPress, Key_Return, '\n', 0 ); - TQApplication::sendEvent( lineEdit, &event ); -} - -void KonqMainWindow::slotLocationLabelActivated() -{ - focusLocationBar(); - m_combo->lineEdit()->selectAll(); -} - -void KonqMainWindow::slotOpenURL( const KURL& url ) -{ - openURL( 0L, url ); -} - -bool KonqMainWindow::sidebarVisible() const -{ -TDEAction *a = m_toggleViewGUIClient->action("konq_sidebartng"); -return (a && static_cast(a)->isChecked()); -} - -void KonqMainWindow::slotAddWebSideBar(const KURL& url, const TQString& name) -{ - if (url.url().isEmpty() && name.isEmpty()) - return; - - kdDebug(1202) << "Requested to add URL " << url << " [" << name << "] to the sidebar!" << endl; - - TDEAction *a = m_toggleViewGUIClient->action("konq_sidebartng"); - if (!a) { - KMessageBox::sorry(0L, i18n("Your sidebar is not functional or unavailable. A new entry cannot be added."), i18n("Web Sidebar")); - return; - } - - int rc = KMessageBox::questionYesNo(0L, - i18n("Add new web extension \"%1\" to your sidebar?") - .arg(name.isEmpty() ? name : url.prettyURL()), - i18n("Web Sidebar"),i18n("Add"),i18n("Do Not Add")); - - if (rc == KMessageBox::Yes) { - // Show the sidebar - if (!static_cast(a)->isChecked()) { - a->activate(); - } - - // Tell it to add a new panel - MapViews::ConstIterator it; - for (it = viewMap().begin(); it != viewMap().end(); ++it) { - KonqView *view = it.data(); - if (view) { - KService::Ptr svc = view->service(); - if (svc->desktopEntryName() == "konq_sidebartng") { - emit view->browserExtension()->addWebSideBar(url, name); - break; - } - } - } - } -} - -void KonqMainWindow::bookmarksIntoCompletion( const KBookmarkGroup& group ) -{ - static const TQString& http = TDEGlobal::staticQString( "http" ); - static const TQString& ftp = TDEGlobal::staticQString( "ftp" ); - - if ( group.isNull() ) - return; - - for ( KBookmark bm = group.first(); - !bm.isNull(); bm = group.next(bm) ) { - if ( bm.isGroup() ) { - bookmarksIntoCompletion( bm.toGroup() ); - continue; - } - - KURL url = bm.url(); - if ( !url.isValid() ) - continue; - - TQString u = url.prettyURL(); - s_pCompletion->addItem( u ); - - if ( url.isLocalFile() ) - s_pCompletion->addItem( url.path() ); - else if ( url.protocol() == http ) - s_pCompletion->addItem( u.mid( 7 )); - else if ( url.protocol() == ftp && - url.host().startsWith( ftp ) ) - s_pCompletion->addItem( u.mid( 6 ) ); - } -} - -void KonqMainWindow::connectActionCollection( TDEActionCollection *coll ) -{ - connect( coll, TQT_SIGNAL( actionStatusText( const TQString & ) ), - this, TQT_SLOT( slotActionStatusText( const TQString & ) ) ); - connect( coll, TQT_SIGNAL( clearStatusText() ), - this, TQT_SLOT( slotClearStatusText() ) ); -} - -void KonqMainWindow::disconnectActionCollection( TDEActionCollection *coll ) -{ - disconnect( coll, TQT_SIGNAL( actionStatusText( const TQString & ) ), - this, TQT_SLOT( slotActionStatusText( const TQString & ) ) ); - disconnect( coll, TQT_SIGNAL( clearStatusText() ), - this, TQT_SLOT( slotClearStatusText() ) ); -} - -// -// the smart popup completion code , -// - -// prepend http://www. or http:// if there's no protocol in 's' -// used only when there are no completion matches -static TQString hp_tryPrepend( const TQString& s ) -{ - if( s.isEmpty() || s[ 0 ] == '/' ) - return TQString::null; - for( unsigned int pos = 0; - pos < s.length() - 2; // 4 = ://x - ++pos ) - { - if( s[ pos ] == ':' && s[ pos + 1 ] == '/' && s[ pos + 2 ] == '/' ) - return TQString::null; - if( !s[ pos ].isLetter() ) - break; - } - return ( s.startsWith( "www." ) ? "http://" : "http://www." ) + s; -} - - -static void hp_removeDupe( TDECompletionMatches& l, const TQString& dupe, - TDECompletionMatches::Iterator it_orig ) -{ - for( TDECompletionMatches::Iterator it = l.begin(); - it != l.end(); - ) { - if( it == it_orig ) { - ++it; - continue; - } - if( (*it).value() == dupe ) { - (*it_orig).first = kMax( (*it_orig).first, (*it).index()); - it = l.remove( it ); - continue; - } - ++it; - } -} - -// remove duplicates like 'http://www.kde.org' and 'http://www.kde.org/' -// (i.e. the trailing slash) -// some duplicates are also created by prepending protocols -static void hp_removeDuplicates( TDECompletionMatches& l ) -{ - TQString http = "http://"; - TQString ftp = "ftp://ftp."; - TQString file = "file:"; - TQString file2 = "file://"; - l.removeDuplicates(); - for( TDECompletionMatches::Iterator it = l.begin(); - it != l.end(); - ++it ) { - TQString str = (*it).value(); - if( str.startsWith( http )) { - if( str.find( '/', 7 ) < 0 ) { // http://something - hp_removeDupe( l, str + '/', it ); - hp_removeDupe( l, str.mid( 7 ) + '/', it ); - } else if( str[ str.length() - 1 ] == '/' ) { - hp_removeDupe( l, str.left( str.length() - 1 ), it ); - hp_removeDupe( l, str.left( str.length() - 1 ).mid( 7 ), it ); - } - hp_removeDupe( l, str.mid( 7 ), it ); - } - else if( str.startsWith( ftp )) // ftp://ftp. - hp_removeDupe( l, str.mid( 6 ), it ); // remove dupes without ftp:// - else if( str.startsWith( file2 )) - hp_removeDupe( l, str.mid( 7 ), it ); // remove dupes without file:// - else if( str.startsWith( file )) - hp_removeDupe( l, str.mid( 5 ), it ); // remove dupes without file: - } -} - -static void hp_removeCommonPrefix( TDECompletionMatches& l, const TQString& prefix ) -{ - for( TDECompletionMatches::Iterator it = l.begin(); - it != l.end(); - ) { - if( (*it).value().startsWith( prefix )) { - it = l.remove( it ); - continue; - } - ++it; - } -} - -// don't include common prefixes like 'http://', i.e. when s == 'h', include -// http://hotmail.com but don't include everything just starting with 'http://' -static void hp_checkCommonPrefixes( TDECompletionMatches& matches, const TQString& s ) -{ - static const char* const prefixes[] = { - "http://", - "https://", - "www.", - "ftp://", - "http://www.", - "https://www.", - "ftp://ftp.", - "file:", - "file://", - NULL }; - for( const char* const *pos = prefixes; - *pos != NULL; - ++pos ) { - TQString prefix = *pos; - if( prefix.startsWith( s )) { - hp_removeCommonPrefix( matches, prefix ); - } - } -} - -TQStringList KonqMainWindow::historyPopupCompletionItems( const TQString& s) -{ - const TQString http = "http://"; - const TQString https = "https://"; - const TQString www = "http://www."; - const TQString wwws = "https://www."; - const TQString ftp = "ftp://"; - const TQString ftpftp = "ftp://ftp."; - const TQString file = "file:"; // without /, because people enter /usr etc. - const TQString file2 = "file://"; - if( s.isEmpty()) - return TQStringList(); - TDECompletionMatches matches= s_pCompletion->allWeightedMatches( s ); - hp_checkCommonPrefixes( matches, s ); - bool checkDuplicates = false; - if ( !s.startsWith( ftp ) ) { - matches += s_pCompletion->allWeightedMatches( ftp + s ); - if( TQString( "ftp." ).startsWith( s )) - hp_removeCommonPrefix( matches, ftpftp ); - checkDuplicates = true; - } - if ( !s.startsWith( https ) ) { - matches += s_pCompletion->allWeightedMatches( https + s ); - if( TQString( "www." ).startsWith( s )) - hp_removeCommonPrefix( matches, wwws ); - checkDuplicates = true; - } - if ( !s.startsWith( http )) { - matches += s_pCompletion->allWeightedMatches( http + s ); - if( TQString( "www." ).startsWith( s )) - hp_removeCommonPrefix( matches, www ); - checkDuplicates = true; - } - if ( !s.startsWith( www ) ) { - matches += s_pCompletion->allWeightedMatches( www + s ); - checkDuplicates = true; - } - if ( !s.startsWith( wwws ) ) { - matches += s_pCompletion->allWeightedMatches( wwws + s ); - checkDuplicates = true; - } - if ( !s.startsWith( ftpftp ) ) { - matches += s_pCompletion->allWeightedMatches( ftpftp + s ); - checkDuplicates = true; - } - if ( !s.startsWith( file ) ) { - matches += s_pCompletion->allWeightedMatches( file + s ); - checkDuplicates = true; - } - if ( !s.startsWith( file2 ) ) { - matches += s_pCompletion->allWeightedMatches( file2 + s ); - checkDuplicates = true; - } - if( checkDuplicates ) - hp_removeDuplicates( matches ); - TQStringList items = matches.list(); - if( items.count() == 0 - && !s.contains( ':' ) && s[ 0 ] != '/' ) - { - TQString pre = hp_tryPrepend( s ); - if( !pre.isNull()) - items += pre; - } - return items; -} - -#ifndef NDEBUG -void KonqMainWindow::dumpViewList() -{ - MapViews::Iterator end = m_mapViews.end(); - - kdDebug(1202) << m_mapViews.count() << "Views" << endl; - - for (MapViews::Iterator it = m_mapViews.begin(); it != end; it++) - { - kdDebug(1202) << it.data() << endl; - } -} -#endif - -// KonqFrameContainerBase implementation BEGIN - -/** - * Call this after inserting a new frame into the splitter. - */ -void KonqMainWindow::insertChildFrame( KonqFrameBase * frame, int /*index*/ ) -{ - m_pChildFrame = frame; - m_pActiveChild = frame; - frame->setParentContainer(this); - setCentralWidget( frame->widget() ); -} - -/** - * Call this before deleting one of our children. - */ -void KonqMainWindow::removeChildFrame( KonqFrameBase * /*frame*/ ) -{ - m_pChildFrame = 0L; - m_pActiveChild = 0L; -} - -void KonqMainWindow::saveConfig( TDEConfig* config, const TQString &prefix, bool saveURLs, KonqFrameBase* docContainer, int id, int depth ) { if( m_pChildFrame ) m_pChildFrame->saveConfig( config, prefix, saveURLs, docContainer, id, depth); } - -void KonqMainWindow::copyHistory( KonqFrameBase *other ) { if( m_pChildFrame ) m_pChildFrame->copyHistory( other ); } - -void KonqMainWindow::printFrameInfo( const TQString &spaces ) { if( m_pChildFrame ) m_pChildFrame->printFrameInfo( spaces ); } - -void KonqMainWindow::reparentFrame( TQWidget* /*parent*/, - const TQPoint & /*p*/, bool /*showIt*/ ) { return; } - -KonqFrameContainerBase* KonqMainWindow::parentContainer()const { return 0L; } -void KonqMainWindow::setParentContainer(KonqFrameContainerBase* /*parent*/) { return; } - -void KonqMainWindow::setTitle( const TQString &/*title*/ , TQWidget* /*sender*/) { return; } -void KonqMainWindow::setTabIcon( const KURL &/*url*/, TQWidget* /*sender*/ ) { return; } - -TQWidget* KonqMainWindow::widget() { return this; } - -void KonqMainWindow::listViews( ChildViewList *viewList ) { if( m_pChildFrame ) m_pChildFrame->listViews( viewList ); } - -TQCString KonqMainWindow::frameType() { return TQCString("MainWindow"); } - -KonqFrameBase* KonqMainWindow::childFrame()const { return m_pChildFrame; } - -void KonqMainWindow::setActiveChild( KonqFrameBase* /*activeChild*/ ) { return; } - -bool KonqMainWindow::isMimeTypeAssociatedWithSelf( const TQString &mimeType ) -{ - return isMimeTypeAssociatedWithSelf( mimeType, KServiceTypeProfile::preferredService( mimeType, "Application" ) ); -} - -bool KonqMainWindow::isMimeTypeAssociatedWithSelf( const TQString &/*mimeType*/, const KService::Ptr &offer ) -{ - // Prevention against user stupidity : if the associated app for this mimetype - // is konqueror/kfmclient, then we'll loop forever. So we have to - // 1) force embedding first, if that works we're ok - // 2) check what KRun is going to do before calling it. - return ( offer && ( offer->desktopEntryName() == "konqueror" || - offer->exec().stripWhiteSpace().startsWith( "kfmclient" ) ) ); -} - -// KonqFrameContainerBase implementation END - -void KonqMainWindow::setPreloadedFlag( bool preloaded ) -{ - if( s_preloaded == preloaded ) - return; - s_preloaded = preloaded; - if( s_preloaded ) - { - kapp->disableSessionManagement(); // dont restore preloaded konqy's - return; // was registered before calling this - } - delete s_preloadedWindow; // preloaded state was abandoned without reusing the window - s_preloadedWindow = NULL; - kapp->enableSessionManagement(); // enable SM again - DCOPRef ref( "kded", "konqy_preloader" ); - ref.send( "unregisterPreloadedKonqy", kapp->dcopClient()->appId()); -} - -void KonqMainWindow::setPreloadedWindow( KonqMainWindow* window ) -{ - s_preloadedWindow = window; - if( window == NULL ) - return; - window->viewManager()->clear(); - TDEIO::Scheduler::unregisterWindow( TQT_TQOBJECT(window) ); -} - -// used by preloading - this KonqMainWindow will be reused, reset everything -// that won't be reset by loading a profile -void KonqMainWindow::resetWindow() -{ - char data[ 1 ]; - // empty append to get current X timestamp - TQWidget tmp_widget; - XChangeProperty( tqt_xdisplay(), tmp_widget.winId(), XA_WM_CLASS, XA_STRING, 8, - PropModeAppend, (unsigned char*) &data, 0 ); - XEvent ev; - XWindowEvent( tqt_xdisplay(), tmp_widget.winId(), PropertyChangeMask, &ev ); - long x_time = ev.xproperty.time; - // bad hack - without updating the _TDE_NET_WM_USER_CREATION_TIME property, - // KWin will apply don't_steal_focus to this window, and will not make it active - // (shows mainly with 'konqueror --preload') - static Atom atom = XInternAtom( tqt_xdisplay(), "_TDE_NET_WM_USER_CREATION_TIME", False ); - XChangeProperty( tqt_xdisplay(), winId(), atom, XA_CARDINAL, 32, - PropModeReplace, (unsigned char *) &x_time, 1); - SET_QT_X_USER_TIME(CurrentTime); // won't have _NET_WM_USER_TIME set -#if !KDE_IS_VERSION( 3, 2, 90 ) // _KDE_NET_USER_TIME is obsolete - static Atom atom2 = XInternAtom( tqt_xdisplay(), "_KDE_NET_USER_TIME", False ); - timeval tv; - gettimeofday( &tv, NULL ); - unsigned long now = tv.tv_sec * 10 + tv.tv_usec / 100000; - XChangeProperty(tqt_xdisplay(), winId(), atom2, XA_CARDINAL, - 32, PropModeReplace, (unsigned char *)&now, 1); -#endif - static Atom atom3 = XInternAtom( tqt_xdisplay(), "_NET_WM_USER_TIME", False ); - XDeleteProperty( tqt_xdisplay(), winId(), atom3 ); -// Qt remembers the iconic state if the window was withdrawn while on another virtual desktop - clearWState( WState_Minimized ); - ignoreInitialGeometry(); - kapp->setTopWidget( this ); // set again the default window icon -} - -bool KonqMainWindow::event( TQEvent* e ) -{ - if( e->type() == TQEvent::DeferredDelete ) - { - // since the preloading code tries to reuse KonqMainWindow, - // the last window shouldn't be really deleted, but only hidden - // deleting WDestructiveClose windows is done using deleteLater(), - // so catch TQEvent::DefferedDelete and check if this window should stay - if( stayPreloaded()) - { - setWFlags(WDestructiveClose); // was reset before deleteLater() - return true; // no deleting - } - } - return KParts::MainWindow::event( e ); -} - -bool KonqMainWindow::stayPreloaded() -{ - // last window? - if( mainWindowList()->count() > 1 ) - return false; - // not running in full KDE environment? - if( getenv( "TDE_FULL_SESSION" ) == NULL || getenv( "TDE_FULL_SESSION" )[ 0 ] == '\0' ) - return false; - // not the same user like the one running the session (most likely we're run via sudo or something) - if( getenv( "TDE_SESSION_UID" ) != NULL && uid_t( atoi( getenv( "TDE_SESSION_UID" ))) != getuid()) - return false; - if( KonqSettings::maxPreloadCount() == 0 ) - return false; - viewManager()->clear(); // reduce resource usage before checking it - if( !checkPreloadResourceUsage()) - return false; - DCOPRef ref( "kded", "konqy_preloader" ); - if( !ref.callExt( "registerPreloadedKonqy", DCOPRef::NoEventLoop, 5000, - kapp->dcopClient()->appId(), tqt_xscreen())) - { - return false; - } - KonqMainWindow::setPreloadedFlag( true ); - kdDebug(1202) << "Konqy kept for preloading :" << kapp->dcopClient()->appId() << endl; - KonqMainWindow::setPreloadedWindow( this ); - return true; -} - -// try to avoid staying running when leaking too much memory -// this is checked by using mallinfo() and comparing -// memory usage during konqy startup and now, if the difference -// is too large -> leaks -> quit -// also, if this process is running for too long, or has been -// already reused too many times -> quit, just in case -bool KonqMainWindow::checkPreloadResourceUsage() -{ - if( -#ifndef NDEBUG - isatty( STDIN_FILENO ) || -#endif - isatty( STDOUT_FILENO ) || isatty( STDERR_FILENO )) - { - kdDebug(1202) << "Running from tty, not keeping for preloading" << endl; - return false; - } - int limit; - int usage = current_memory_usage( &limit ); - kdDebug(1202) << "Memory usage increase: " << ( usage - s_initialMemoryUsage ) - << " (" << usage << "/" << s_initialMemoryUsage << "), increase limit: " << limit << endl; - int max_allowed_usage = s_initialMemoryUsage + limit; - if( usage > max_allowed_usage ) // too much memory used? - { - kdDebug(1202) << "Not keeping for preloading due to high memory usage" << endl; - return false; - } - // working memory usage test ( usage != 0 ) makes others less strict - if( ++s_preloadUsageCount > ( usage != 0 ? 100 : 10 )) // reused too many times? - { - kdDebug(1202) << "Not keeping for preloading due to high usage count" << endl; - return false; - } - if( time( NULL ) > s_startupTime + 60 * 60 * ( usage != 0 ? 4 : 1 )) // running for too long? - { - kdDebug(1202) << "Not keeping for preloading due to long usage time" << endl; - return false; - } - return true; -} - -static int current_memory_usage( int* limit ) -{ -#ifdef __linux__ -// Check whole memory usage - VmSize - TQFile f( TQCString().sprintf( "/proc/%i/statm", getpid())); - if( f.open( IO_ReadOnly )) - { - TQString line; - if( f.readLine( line, 1024 ) > 0 ) - { - line = line.stripWhiteSpace(); - int usage = line.section( ' ', 0, 0 ).toInt(); - if( usage > 0 ) - { - int pagesize = sysconf (_SC_PAGE_SIZE); - if( pagesize < 0 ) - pagesize = 4096; - if( limit != NULL ) - *limit = 16 * 1024 * 1024; - return usage * pagesize; - } - } - } - kdWarning() << "Couldn't read VmSize from /proc/*/statm." << endl; -#endif -// Check malloc() usage - very imprecise, but better than nothing. - int usage_sum = 0; -#if defined(KDE_MALLINFO_STDLIB) || defined(KDE_MALLINFO_MALLOC) - // ugly hack for tdecore/malloc - extern int kde_malloc_is_used; - free( calloc( 4, 4 )); // trigger setting kde_malloc_is_used - if( kde_malloc_is_used ) - { - struct mallinfo m = mallinfo(); - usage_sum = m.hblkhd + m.uordblks; - } - else - { - struct mallinfo m = mallinfo(); -#ifdef KDE_MALLINFO_FIELD_hblkhd - usage_sum += m.hblkhd; -#endif -#ifdef KDE_MALLINFO_FIELD_uordblks - usage_sum += m.uordblks; -#endif -#ifdef KDE_MALLINFO_FIELD_usmblks - usage_sum += m.usmblks; -#endif - } - // unlike /proc , this doesn't include things like size of dlopened modules, - // and also doesn't include malloc overhead - if( limit != NULL ) - *limit = 6 * 1024 * 1024; -#endif - return usage_sum; -} - -void KonqMainWindow::saveWindowSize() const -{ - TQString savedGroup = TDEGlobal::config()->group(); - TDEGlobal::config()->setGroup( "KonqMainWindow_Size" ); - - KParts::MainWindow::saveWindowSize( TDEGlobal::config() ); - - TDEGlobal::config()->setGroup( savedGroup ); - TDEGlobal::config()->sync(); -} - -void KonqMainWindow::restoreWindowSize() -{ - TQString savedGroup = TDEGlobal::config()->group(); - TDEGlobal::config()->setGroup( "KonqMainWindow_Size" ); - - KParts::MainWindow::restoreWindowSize( TDEGlobal::config() ); - - TDEGlobal::config()->setGroup( savedGroup ); -} - - -#include "konq_mainwindow.moc" -#include "konq_mainwindow_p.moc" diff --git a/konqueror/konq_mainwindow.cpp b/konqueror/konq_mainwindow.cpp new file mode 100644 index 000000000..90dd451af --- /dev/null +++ b/konqueror/konq_mainwindow.cpp @@ -0,0 +1,5998 @@ +/* This file is part of the KDE project + Copyright (C) 1998, 1999 Simon Hausmann + Copyright (C) 2000 Carsten Pfeiffer + Copyright (C) 2000-2005 David Faure + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "konq_mainwindow.h" +#include "konq_guiclients.h" +#include "KonqMainWindowIface.h" +#include "konq_view.h" +#include "konq_run.h" +#include "konq_misc.h" +#include "konq_viewmgr.h" +#include "konq_frame.h" +#include "konq_tabs.h" +#include "konq_events.h" +#include "konq_actions.h" +#include "konq_settingsxt.h" +#include "konq_extensionmanager.h" +#include "delayedinitializer.h" +#include +#include +#include +#include +#include +#include +#include +// we define STRICT_ANSI to get rid of some warnings in glibc +#ifndef __STRICT_ANSI__ +#define __STRICT_ANSI__ +#define _WE_DEFINED_IT_ +#endif +#include +#ifdef _WE_DEFINED_IT_ +#undef __STRICT_ANSI__ +#undef _WE_DEFINED_IT_ +#endif +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "konq_main.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef KDE_MALLINFO_STDLIB +#include +#endif +#ifdef KDE_MALLINFO_MALLOC +#include +#endif + +#include +#include +#include +#include + +template class TQPtrList; +template class TQPtrList; + +TQPtrList *KonqMainWindow::s_lstViews = 0; +TDEConfig * KonqMainWindow::s_comboConfig = 0; +TDECompletion * KonqMainWindow::s_pCompletion = 0; +TQFile * KonqMainWindow::s_crashlog_file = 0; +bool KonqMainWindow::s_preloaded = false; +KonqMainWindow* KonqMainWindow::s_preloadedWindow = 0; +int KonqMainWindow::s_initialMemoryUsage = -1; +time_t KonqMainWindow::s_startupTime; +int KonqMainWindow::s_preloadUsageCount; + +KonqOpenURLRequest KonqOpenURLRequest::null; + +static int current_memory_usage( int* limit = NULL ); + +#include "konq_mainwindow_p.h" + +KonqExtendedBookmarkOwner::KonqExtendedBookmarkOwner(KonqMainWindow *w) +{ + m_pKonqMainWindow = w; +} + +KonqMainWindow::KonqMainWindow( const KURL &initialURL, bool openInitialURL, const char *name, const TQString& xmluiFile) + : KParts::MainWindow( NoDCOPObject, 0L, name, (WFlags)(WDestructiveClose | WStyle_ContextHelp | TQt::WGroupLeader) ) +{ + setPreloadedFlag( false ); + + if ( !s_lstViews ) + s_lstViews = new TQPtrList; + + s_lstViews->append( this ); + + m_urlCompletionStarted = false; + + m_currentView = 0L; + m_pChildFrame = 0L; + m_pActiveChild = 0L; + m_pWorkingTab = 0L; + m_initialKonqRun = 0L; + m_pBookmarkMenu = 0L; + m_dcopObject = new KonqMainWindowIface( this ); + m_combo = 0L; + m_bURLEnterLock = false; + m_bLocationBarConnected = false; + m_paBookmarkBar = 0L; + m_pURLCompletion = 0L; + m_goBuffer = 0; + m_configureDialog = 0L; + + m_bViewModeToggled = false; + + m_prevMenuBarVisible = true; + + m_pViewManager = new KonqViewManager( this ); + + m_toggleViewGUIClient = new ToggleViewGUIClient( this ); + + m_openWithActions.setAutoDelete( true ); + m_viewModeActions.setAutoDelete( true ); + m_toolBarViewModeActions.setAutoDelete( true ); + m_viewModeMenu = 0; + m_paDelete = 0; + m_bookmarkBarActionCollection = 0L; + KonqExtendedBookmarkOwner *extOwner = new KonqExtendedBookmarkOwner( this ); + m_pBookmarksOwner = extOwner; + connect( extOwner, + TQT_SIGNAL( signalFillBookmarksList(KExtendedBookmarkOwner::QStringPairList &) ), + extOwner, + TQT_SLOT( slotFillBookmarksList(KExtendedBookmarkOwner::QStringPairList &) ) ); + + // init history-manager, load history, get completion object + if ( !s_pCompletion ) { + KonqHistoryManager *mgr = new KonqHistoryManager( TQT_TQOBJECT(kapp), "history mgr" ); + s_pCompletion = mgr->completionObject(); + + + // setup the completion object before createGUI(), so that the combo + // picks up the correct mode from the HistoryManager (in slotComboPlugged) + int mode = KonqSettings::settingsCompletionMode(); + s_pCompletion->setCompletionMode( (TDEGlobalSettings::Completion) mode ); + } + connect(KParts::HistoryProvider::self(), TQT_SIGNAL(cleared()), TQT_SLOT(slotClearComboHistory())); + + KonqPixmapProvider *prov = KonqPixmapProvider::self(); + if ( !s_comboConfig ) { + s_comboConfig = new TDEConfig( "konq_history", false, false ); + KonqCombo::setConfig( s_comboConfig ); + s_comboConfig->setGroup( "Location Bar" ); + prov->load( s_comboConfig, "ComboIconCache" ); + } + connect( prov, TQT_SIGNAL( changed() ), TQT_SLOT( slotIconsChanged() ) ); + + initCombo(); + initActions(); + + setInstance( TDEGlobal::instance() ); + + connect( KSycoca::self(), TQT_SIGNAL( databaseChanged() ), + this, TQT_SLOT( slotDatabaseChanged() ) ); + + connect( kapp, TQT_SIGNAL( tdedisplayFontChanged()), TQT_SLOT(slotReconfigure())); + + //load the xmlui file specified in the profile or the default konqueror.rc + setXMLFile( xmluiFile ); + + setStandardToolBarMenuEnabled( true ); + + createGUI( 0L ); + + connect(toolBarMenuAction(),TQT_SIGNAL(activated()),this,TQT_SLOT(slotForceSaveMainWindowSettings()) ); + + if ( !m_toggleViewGUIClient->empty() ) + plugActionList( TQString::fromLatin1( "toggleview" ), m_toggleViewGUIClient->actions() ); + else + { + delete m_toggleViewGUIClient; + m_toggleViewGUIClient = 0; + } + + // Those menus are created by konqueror.rc so their address will never change + TQPopupMenu *popup = static_cast(factory()->container("edit",this)); + if (popup) + TDEAcceleratorManager::manage(popup); + popup = static_cast(factory()->container("tools",this)); + if (popup) + TDEAcceleratorManager::manage(popup); + + m_bSaveViewPropertiesLocally = KonqSettings::saveViewPropertiesLocally(); + m_bHTMLAllowed = KonqSettings::htmlAllowed(); + + m_ptaUseHTML->setChecked( m_bHTMLAllowed ); + m_paSaveViewPropertiesLocally->setChecked( m_bSaveViewPropertiesLocally ); + + KonqUndoManager::incRef(); + + connect( KonqUndoManager::self(), TQT_SIGNAL( undoAvailable( bool ) ), + this, TQT_SLOT( slotUndoAvailable( bool ) ) ); + m_bNeedApplyKonqMainWindowSettings = true; + + if ( !initialURL.isEmpty() ) + { + openFilteredURL( initialURL.url() ); + } + else if ( openInitialURL ) + { + KURL homeURL; + homeURL.setPath( TQDir::homeDirPath() ); + openURL( 0L, homeURL ); + } + else + // silent + m_bNeedApplyKonqMainWindowSettings = false; + + // Read basic main-view settings, and set to autosave + setAutoSaveSettings( "KonqMainWindow", false ); + + if ( !initialGeometrySet() ) + resize( 700, 480 ); + //kdDebug(1202) << "KonqMainWindow::KonqMainWindow " << this << " done" << endl; + + if( s_initialMemoryUsage == -1 ) + { + s_initialMemoryUsage = current_memory_usage(); + s_startupTime = time( NULL ); + s_preloadUsageCount = 0; + } +} + +KonqMainWindow::~KonqMainWindow() +{ + kdDebug(1202) << "KonqMainWindow::~KonqMainWindow " << this << endl; + + delete m_pViewManager; + + if ( s_lstViews ) + { + s_lstViews->removeRef( this ); + if ( s_lstViews->count() == 0 ) + { + delete s_lstViews; + s_lstViews = 0; + } + } + + disconnectActionCollection( actionCollection() ); + + saveToolBarServicesMap(); + + // createShellGUI( false ); + + delete m_pBookmarkMenu; + delete m_paBookmarkBar; + delete m_pBookmarksOwner; + delete m_pURLCompletion; + + m_viewModeActions.clear(); + + KonqUndoManager::decRef(); + + if ( s_lstViews == 0 ) { + delete KonqPixmapProvider::self(); + delete s_comboConfig; + s_comboConfig = 0L; + } + + delete m_configureDialog; + m_configureDialog = 0L; + delete m_dcopObject; + m_dcopObject = 0L; + delete m_combo; + m_combo = 0L; + delete m_locationLabel; + m_locationLabel = 0L; + + kdDebug(1202) << "KonqMainWindow::~KonqMainWindow " << this << " done" << endl; +} + +TQWidget * KonqMainWindow::createContainer( TQWidget *parent, int index, const TQDomElement &element, int &id ) +{ + static TQString nameBookmarkBar = TQString::fromLatin1( "bookmarkToolBar" ); + static TQString tagToolBar = TQString::fromLatin1( "ToolBar" ); + + TQWidget *res = KParts::MainWindow::createContainer( parent, index, element, id ); + + if ( res && (element.tagName() == tagToolBar) && (element.attribute( "name" ) == nameBookmarkBar) ) + { + assert( res->inherits( "TDEToolBar" ) ); + if (!kapp->authorizeTDEAction("bookmarks")) + { + delete res; + return 0; + } + + if ( !m_bookmarkBarActionCollection ) + { + // The actual menu needs a different action collection, so that the bookmarks + // don't appear in kedittoolbar + m_bookmarkBarActionCollection = new TDEActionCollection( this ); + m_bookmarkBarActionCollection->setHighlightingEnabled( true ); + connectActionCollection( m_bookmarkBarActionCollection ); + DelayedInitializer *initializer = new DelayedInitializer( TQEvent::Show, TQT_TQOBJECT(res) ); + connect( initializer, TQT_SIGNAL( initialize() ), this, TQT_SLOT(initBookmarkBar()) ); + } + } + + return res; +} + +void KonqMainWindow::initBookmarkBar() +{ + TDEToolBar * bar = static_cast( TQT_TQWIDGET(child( "bookmarkToolBar", "TDEToolBar" )) ); + + if (!bar) return; + + delete m_paBookmarkBar; + m_paBookmarkBar = new KBookmarkBar( KonqBookmarkManager::self(), m_pBookmarksOwner, bar, m_bookmarkBarActionCollection, TQT_TQOBJECT(this) ); + connect( m_paBookmarkBar, + TQT_SIGNAL( aboutToShowContextMenu(const KBookmark &, TQPopupMenu*) ), + this, TQT_SLOT( slotFillContextMenu(const KBookmark &, TQPopupMenu*) )); + connect( m_paBookmarkBar, + TQT_SIGNAL( openBookmark(const TQString &, TQt::ButtonState) ), + this, TQT_SLOT( slotOpenBookmarkURL(const TQString &, TQt::ButtonState) )); + + // hide if empty + if (bar->count() == 0 ) + bar->hide(); +} + +void KonqMainWindow::removeContainer( TQWidget *container, TQWidget *parent, TQDomElement &element, int id ) +{ + static TQString nameBookmarkBar = TQString::fromLatin1( "bookmarkToolBar" ); + static TQString tagToolBar = TQString::fromLatin1( "ToolBar" ); + + if ( element.tagName() == tagToolBar && element.attribute( "name" ) == nameBookmarkBar ) + { + assert( container->inherits( "TDEToolBar" ) ); + if (m_paBookmarkBar) + m_paBookmarkBar->clear(); + } + + KParts::MainWindow::removeContainer( container, parent, element, id ); +} + +// Detect a name filter (e.g. *.txt) in the url. +// Note that TDEShortURIFilter does the same, but we have no way of getting it from there +// +// Note: this removes the filter from the URL. +static TQString detectNameFilter( KURL & url ) +{ + if ( !KProtocolInfo::supportsListing(url) ) + return TQString::null; + + // Look for wildcard selection + TQString nameFilter; + TQString path = url.path(); + int lastSlash = path.findRev( '/' ); + if ( lastSlash > -1 ) + { + if ( !url.query().isEmpty() && lastSlash == (int)path.length()-1 ) { // In /tmp/?foo, foo isn't a query + path += url.query(); // includes the '?' + url.setQuery( TQString::null ); + } + const TQString fileName = path.mid( lastSlash + 1 ); + if ( fileName.find( '*' ) != -1 || fileName.find( '[' ) != -1 || fileName.find( '?' ) != -1 ) + { + // Check that a file or dir with all the special chars in the filename doesn't exist + if ( url.isLocalFile() ? !TQFile::exists( path ) : !TDEIO::NetAccess::exists( url, false, 0 ) ) + { + nameFilter = fileName; + url.setFileName( TQString::null ); + kdDebug(1202) << "Found wildcard. nameFilter=" << nameFilter << " New url=" << url << endl; + } + } + } + + return nameFilter; +} + +void KonqMainWindow::openFilteredURL( const TQString & url, KonqOpenURLRequest & req ) +{ + // Filter URL to build a correct one + if (m_currentDir.isEmpty() && m_currentView) + m_currentDir = m_currentView->url().path(1); + + KURL filteredURL ( KonqMisc::konqFilteredURL( this, url, m_currentDir ) ); + kdDebug(1202) << "url " << url << " filtered into " << filteredURL.prettyURL() << endl; + + if ( filteredURL.isEmpty() ) // initially empty, or error (e.g. ~unknown_user) + return; + + m_currentDir = TQString::null; + + openURL( 0L, filteredURL, TQString::null, req ); + + // #4070: Give focus to view after URL was entered manually + // Note: we do it here if the view mode (i.e. part) wasn't changed + // If it is changed, then it's done in KonqView::changeViewMode + if ( m_currentView && m_currentView->part() ) + m_currentView->part()->widget()->setFocus(); + +} + +void KonqMainWindow::openFilteredURL( const TQString & _url, bool inNewTab, bool tempFile ) +{ + KonqOpenURLRequest req( _url ); + req.newTab = inNewTab; + req.newTabInFront = true; + req.tempFile = tempFile; + + openFilteredURL( _url, req ); +} + +void KonqMainWindow::openURL( KonqView *_view, const KURL &_url, + const TQString &_serviceType, KonqOpenURLRequest& req, + bool trustedSource ) +{ + kdDebug(1202) << "KonqMainWindow::openURL : url = '" << _url << "' " + << "serviceType='" << _serviceType << "' req=" << req.debug() + << " view=" << _view << endl; + + KURL url( _url ); + if (url.url().startsWith("$(")) { + // check for environment variables and make necessary translations + TQString aValue = url.url(); + int nDollarPos = aValue.find( '$' ); + + while( nDollarPos != -1 && nDollarPos+1 < static_cast(aValue.length())) { + // there is at least one $ + if( (aValue)[nDollarPos+1] != '$' ) { + uint nEndPos = nDollarPos+1; + // the next character is no $ + TQString aVarName; + if (aValue[nEndPos]=='{') + { + while ( (nEndPos <= aValue.length()) && (aValue[nEndPos]!='}') ) + nEndPos++; + nEndPos++; + aVarName = aValue.mid( nDollarPos+2, nEndPos-nDollarPos-3 ); + } + else + { + while ( nEndPos <= aValue.length() && (aValue[nEndPos].isNumber() + || aValue[nEndPos].isLetter() || aValue[nEndPos]=='_' ) ) + nEndPos++; + aVarName = aValue.mid( nDollarPos+1, nEndPos-nDollarPos-1 ); + } + const char* pEnv = 0; + if (!aVarName.isEmpty()) + pEnv = getenv( aVarName.ascii() ); + if( pEnv ) { + // !!! Sergey A. Sukiyazov !!! + // A environment variables may contain values in 8bit + // locale cpecified encoding or in UTF8 encoding. + aValue.replace( nDollarPos, nEndPos-nDollarPos, KStringHandler::from8Bit( pEnv ) ); + } else + aValue.remove( nDollarPos, nEndPos-nDollarPos ); + } else { + // remove one of the dollar signs + aValue.remove( nDollarPos, 1 ); + nDollarPos++; + } + nDollarPos = aValue.find( '$', nDollarPos ); + } + url = KURL(aValue); + } + TQString serviceType( _serviceType ); + if ( url.url() == "about:blank" ) + { + serviceType = "text/html"; + } + else if ( !url.isValid() ) + { + KMessageBox::error(0, i18n("Malformed URL\n%1").arg(url.url())); + return; + } + else if ( !KProtocolInfo::isKnownProtocol( url ) && url.protocol() != "about" ) + { + KMessageBox::error(0, i18n("Protocol not supported\n%1").arg(url.protocol())); + return; + } + + // Default action for media encrypted disks is either lock or unlock based on current status + TQString lockingAction = TQString::null; + if (serviceType.contains("encrypted_locked")) { + lockingAction = "konqueror/servicemenus/media_unlock.desktop"; + } + else if (serviceType.contains("encrypted_unlocked")) { + lockingAction = "konqueror/servicemenus/media_lock.desktop"; + } + if (!lockingAction.isEmpty()) { + TQString lockingService = TDEGlobal::dirs()->findResource("data", lockingAction); + if (!lockingService.isEmpty()) { + TQValueList serviceList = KDEDesktopMimeType::userDefinedServices(lockingService, url.isLocalFile()); + if (serviceList.count() == 1) { + KURL::List m_lstURLs; + m_lstURLs.append(url); + KDEDesktopMimeType::executeService(m_lstURLs, serviceList[0]); + return; + } + } + } + + TQString nameFilter = detectNameFilter( url ); + if ( !nameFilter.isEmpty() ) + { + req.nameFilter = nameFilter; + url.setFileName( TQString::null ); + } + + KonqView *view = _view; + + // When clicking a 'follow active' view (e.g. view is the sidebar), + // open the URL in the active view + if ( view && view->isFollowActive() ) + view = m_currentView; + + if ( !view && !req.newTab ) + view = m_currentView; /* Note, this can be 0L, e.g. on startup */ + else if ( !view && req.newTab ) { + view = m_pViewManager->addTab(TQString::null, + TQString::null, + false, + req.openAfterCurrentPage); + if (view) { + view->setCaption( _url.host() ); + view->setLocationBarURL( _url ); + if ( !req.args.frameName.isEmpty() ) + view->setViewName( req.args.frameName ); // #44961 + + if ( req.newTabInFront ) + m_pViewManager->showTab( view ); + + updateViewActions(); //A new tab created -- we may need to enable the "remove tab" button (#56318) + } + else + req.newTab = false; + } + + const TQString oldLocationBarURL = m_combo->currentText(); + if ( view ) + { + if ( view == m_currentView ) + { + //will do all the stuff below plus GUI stuff + abortLoading(); + } + else + { + view->stop(); + // Don't change location bar if not current view + } + } + + // Fast mode for local files: do the stat ourselves instead of letting KRun do it. + if ( serviceType.isEmpty() && url.isLocalFile() ) + { + TQCString _path( TQFile::encodeName(url.path())); + KDE_struct_stat buff; + if ( KDE_stat( _path.data(), &buff ) != -1 ) + serviceType = KMimeType::findByURL( url, buff.st_mode )->name(); + } + + kdDebug(1202) << "trying openView for " << url << " (serviceType " << serviceType << ")" << endl; + if ( ( !serviceType.isEmpty() && serviceType != "application/octet-stream") || + url.url().startsWith("about:konqueror") || url.url() == "about:plugins" ) + { + KService::Ptr offer = KServiceTypeProfile::preferredService(serviceType, "Application"); + // If the associated app is konqueror itself, then make sure we try to embed before bailing out. + if ( isMimeTypeAssociatedWithSelf( serviceType, offer ) ) + req.forceAutoEmbed = true; + + // Built-in view ? + if ( !openView( serviceType, url, view /* can be 0L */, req ) ) + { + //kdDebug(1202) << "KonqMainWindow::openURL : openView returned false" << endl; + // Are we following another view ? Then forget about this URL. Otherwise fire app. + if ( !req.followMode ) + { + //kdDebug(1202) << "KonqMainWindow::openURL : we were not following. Fire app." << endl; + // We know the servicetype, let's try its preferred service + if ( isMimeTypeAssociatedWithSelf( serviceType, offer ) ) { + KMessageBox::error( this, i18n("There appears to be a configuration error. You have associated Konqueror with %1, but it cannot handle this file type.").arg(serviceType)); + return; + } + if ( !url.isLocalFile() && KonqRun::isTextExecutable( serviceType ) ) + serviceType = "text/plain"; // view, don't execute + // Remote URL: save or open ? + TQString protClass = KProtocolInfo::protocolClass(url.protocol()); + bool open = url.isLocalFile() || protClass==":local"; + if ( !open ) { + KParts::BrowserRun::AskSaveResult res = KonqRun::askSave( url, offer, serviceType ); + if ( res == KParts::BrowserRun::Save ) + KParts::BrowserRun::simpleSave( url, TQString::null, this ); + open = ( res == KParts::BrowserRun::Open ); + } + if ( open ) + { + KURL::List lst; + lst.append(url); + //kdDebug(1202) << "Got offer " << (offer ? offer->name().latin1() : "0") << endl; + if ( ( trustedSource || KonqRun::allowExecution( serviceType, url ) ) && + ( KonqRun::isExecutable( serviceType ) || !offer || !KRun::run( *offer, lst ) ) ) + { + setLocationBarURL( oldLocationBarURL ); // Revert to previous locationbar URL + (void)new KRun( url, this ); + } + } + } + } + } + else // no known serviceType, use KonqRun + { + if ( ( !view || view->url().isEmpty() ) && !req.newTab ) // startup with argument + { + // Show it for now in the location bar, but we'll need to store it in the view + // later on (can't do it yet since either view == 0 or updateHistoryEntry will be called). + kdDebug(1202) << "setLocationBarURL (startup) : url = " << url << endl; + setLocationBarURL( url ); + } + + kdDebug(1202) << "Creating new konqrun for " << url << " req.typedURL=" << req.typedURL << endl; + + KonqRun * run = new KonqRun( this, view /* can be 0L */, url, req, trustedSource ); + + // Never start in external browser + run->setEnableExternalBrowser(false); + + if ( view ) + view->setRun( run ); + else if ( !req.newTab ) + { + // there can be only one :) (when not a new tab) + delete m_initialKonqRun; + m_initialKonqRun = run; + } + + if ( view == m_currentView ) + startAnimation(); + + connect( run, TQT_SIGNAL( finished() ), this, TQT_SLOT( slotRunFinished() ) ); + } +} + +bool KonqMainWindow::openView( TQString serviceType, const KURL &_url, KonqView *childView, KonqOpenURLRequest& req ) +{ + // Second argument is referring URL + if ( !kapp->authorizeURLAction("open", childView ? childView->url() : KURL(), _url) ) + { + TQString msg = TDEIO::buildErrorString(TDEIO::ERR_ACCESS_DENIED, _url.prettyURL()); + KMessageBox::queuedMessageBox( this, KMessageBox::Error, msg ); + return true; // Nothing else to do. + } + + if ( KonqRun::isExecutable( serviceType ) ) + return false; // execute, don't open + // Contract: the caller of this method should ensure the view is stopped first. + +#ifndef NDEBUG + kdDebug(1202) << "KonqMainWindow::openView " << serviceType << " " << _url << " " << childView << " req:" << req.debug() << endl; +#endif + bool bOthersFollowed = false; + + if ( childView ) + { + // If we're not already following another view (and if we are not reloading) + if ( !req.followMode && !req.args.reload && !m_pViewManager->isLoadingProfile() ) + { + // When clicking a 'follow active' view (e.g. childView is the sidebar), + // open the URL in the active view + // (it won't do anything itself, since it's locked to its location) + if ( childView->isFollowActive() && childView != m_currentView ) + { + abortLoading(); + setLocationBarURL( _url ); + KonqOpenURLRequest newreq; + newreq.followMode = true; + newreq.args = req.args; + bOthersFollowed = openView( serviceType, _url, m_currentView, newreq ); + } + // "link views" feature, and "sidebar follows active view" feature + bOthersFollowed = makeViewsFollow(_url, req.args, serviceType, childView) || bOthersFollowed; + } + if ( childView->isLockedLocation() && !req.args.reload /* allow to reload a locked view*/ ) + return bOthersFollowed; + } + + TQString indexFile; + + KURL url( _url ); + + // Generic mechanism for redirecting to tar:// when clicking on a tar file, + // zip:// when clicking on a zip file, etc. + // The name of the protocol to redirect to, is read from the mimetype's .desktop file + if ( url.isLocalFile() ) + { + KServiceType::Ptr ptr = KServiceType::serviceType( serviceType ); + if ( ptr ) + { + const TQString protocol = ptr->property("X-TDE-LocalProtocol").toString(); + if ( !protocol.isEmpty() && KonqFMSettings::settings()->shouldEmbed( serviceType ) ) + { + url.setProtocol( protocol ); + if ( serviceType == "application/x-webarchive" ) + { + url.setPath( url.path() + "/index.html" ); + serviceType = "text/html"; + } + else + { + url.setPath( url.path() + '/' ); + serviceType = "inode/directory"; + } + } + } + } + + /////////// + + // In case we open an index.html, we want the location bar + // to still display the original URL (so that 'up' uses that URL, + // and since that's what the user entered). + // changeViewMode will take care of setting and storing that url. + TQString originalURL = url.pathOrURL(); + if ( !req.nameFilter.isEmpty() ) // keep filter in location bar + { + if (!originalURL.endsWith("/")) + originalURL += '/'; + originalURL += req.nameFilter; + } + + TQString serviceName; // default: none provided + + if ( url.url().startsWith("about:konqueror") || url.url() == "about:plugins" ) + { + serviceType = "KonqAboutPage"; // not KParts/ReadOnlyPart, it fills the Location menu ! :) + serviceName = "konq_aboutpage"; + originalURL = req.typedURL.isEmpty() ? TQString::null : url.url(); + // empty if from profile, about:konqueror if the user typed it (not req.typedURL, it could be "about:") + } + else if ( url.url() == "about:blank" && req.typedURL.isEmpty() ) + { + originalURL = TQString::null; + } + + // Look for which view mode to use, if a directory - not if view locked + if ( ( !childView || (!childView->isLockedViewMode()) ) + && serviceType == "inode/directory" ) + { // Phew ! + + // Set view mode if necessary (current view doesn't support directories) + if ( !childView || !childView->supportsServiceType( serviceType ) ) + serviceName = KonqSettings::mainViewViewMode(); + + if ( url.isLocalFile() ) // local, we can do better (.directory) + { + // Read it in the .directory file, default to m_bHTMLAllowed + KURL urlDotDir( url ); + urlDotDir.addPath(".directory"); + bool HTMLAllowed = m_bHTMLAllowed; + TQFile f( urlDotDir.path() ); + if ( f.open(IO_ReadOnly) ) + { + f.close(); + KSimpleConfig config( urlDotDir.path(), true ); + config.setGroup( "URL properties" ); + HTMLAllowed = config.readBoolEntry( "HTMLAllowed", m_bHTMLAllowed ); + serviceName = config.readEntry( "ViewMode", serviceName ); + kdDebug(1202) << "serviceName=" << serviceName << endl; + } + if ( HTMLAllowed && + ( ( indexFile = findIndexFile( url.path() ) ) != TQString::null ) ) + { + serviceType = "text/html"; + url = KURL(); + url.setPath( indexFile ); + serviceName = TQString::null; // cancel what we just set, this is not a dir finally + } + + // Reflect this setting in the menu + m_ptaUseHTML->setChecked( HTMLAllowed ); + } + } + + bool ok = true; + if ( !childView ) + { + if (req.newTab) + { + KonqFrameTabs* tabContainer = 0L; + int index = 0; + if ( m_pViewManager->docContainer() && m_pViewManager->docContainer()->frameType() == "Tabs") + { + tabContainer = static_cast(m_pViewManager->docContainer()); + index = tabContainer->currentPageIndex(); + } + childView = m_pViewManager->addTab( serviceType, serviceName, false, req.openAfterCurrentPage ); + + if (req.newTabInFront && childView) + { + if ( !tabContainer ) + tabContainer = static_cast(m_pViewManager->docContainer()); + if ( req.openAfterCurrentPage ) + tabContainer->setCurrentPage( index + 1 ); + else + tabContainer->setCurrentPage( tabContainer->count()-1 ); + } + } + + else + { + // Create a new view + // Initialize always uses force auto-embed even if user setting is "separate viewer", + // since this window has no view yet - we don't want to keep an empty mainwindow. + // This can happen with e.g. application/pdf from a target="_blank" link, or window.open. + childView = m_pViewManager->Initialize( serviceType, serviceName ); + + if ( childView ) + { + enableAllActions( true ); + m_currentView = childView; + } + } + + if ( !childView ) + return false; // It didn't work out. + + childView->setViewName( m_initialFrameName.isEmpty() ? req.args.frameName : m_initialFrameName ); + m_initialFrameName = TQString::null; + } + else // We know the child view + { + if ( !childView->isLockedViewMode() ) + { + bool forceAutoEmbed = req.forceAutoEmbed || req.newTab || req.userRequestedReload; + if ( !req.typedURL.isEmpty() ) // the user _typed_ the URL, he wants it in Konq. + forceAutoEmbed = true; + if ( url.protocol() == "about" ) + forceAutoEmbed = true; + // Related to KonqFactory::createView + if ( !forceAutoEmbed && !KonqFMSettings::settings()->shouldEmbed( serviceType ) ) + { + kdDebug(1202) << "openView: KonqFMSettings says: don't embed this servicetype" << endl; + ok = false; + } + + // If the protocol doesn't support writing (e.g. HTTP) then we might want to save instead of just embedding. + // So (if embedding would succeed, hence the checks above) we ask the user + // Otherwise the user will get asked 'open or save' in openURL anyway. + if ( ok && !forceAutoEmbed && !KProtocolInfo::supportsWriting( url ) ) { + TQString suggestedFilename; + + KonqRun* run = childView->run(); + int attachment = 0; + if (run) { + suggestedFilename = run->suggestedFilename(); + attachment = (run->serverSuggestsSave()) ? KParts::BrowserRun::AttachmentDisposition : KParts::BrowserRun::InlineDisposition; + } + + KParts::BrowserRun::AskSaveResult res = KParts::BrowserRun::askEmbedOrSave( + url, serviceType, suggestedFilename, attachment ); + if ( res == KParts::BrowserRun::Open ) + forceAutoEmbed = true; + else if ( res == KParts::BrowserRun::Cancel ) + return true; // handled, don't do anything else + else { // Save + KParts::BrowserRun::simpleSave( url, suggestedFilename, this ); + return true; // handled + } + } + if ( ok ) + ok = childView->changeViewMode( serviceType, serviceName, forceAutoEmbed ); + } + } + + if (ok) + { + //kdDebug(1202) << "req.nameFilter= " << req.nameFilter << endl; + //kdDebug(1202) << "req.typedURL= " << req.typedURL << endl; + //kdDebug(1202) << "Browser extension? " << (childView->browserExtension() ? "YES" : "NO") << endl; + //kdDebug(1202) << "Referrer: " << req.args.metaData()["referrer"] << endl; + childView->setTypedURL( req.typedURL ); + if ( childView->browserExtension() ) + childView->browserExtension()->setURLArgs( req.args ); + if ( childView->part()->inherits("KonqDirPart") ) + static_cast(childView->part())->setFilesToSelect( req.filesToSelect ); + if ( !url.isEmpty() ) + childView->openURL( url, originalURL, req.nameFilter, req.tempFile ); + } + kdDebug(1202) << "KonqMainWindow::openView ok=" << ok << " bOthersFollowed=" << bOthersFollowed << " returning " + << (ok || bOthersFollowed) + << endl; + return ok || bOthersFollowed; +} + +void KonqMainWindow::slotOpenURLRequest( const KURL &url, const KParts::URLArgs &args ) +{ + kdDebug(1202) << "KonqMainWindow::slotOpenURLRequest frameName=" << args.frameName << endl; + + KParts::ReadOnlyPart *callingPart = static_cast( TQT_TQOBJECT_CONST(sender())->parent() ); + TQString frameName = args.frameName; + + if ( !frameName.isEmpty() ) + { + static TQString _top = TQString::fromLatin1( "_top" ); + static TQString _self = TQString::fromLatin1( "_self" ); + static TQString _parent = TQString::fromLatin1( "_parent" ); + static TQString _blank = TQString::fromLatin1( "_blank" ); + + if ( frameName.lower() == _blank ) + { + slotCreateNewWindow( url, args ); + return; + } + + if ( frameName.lower() != _top && + frameName.lower() != _self && + frameName.lower() != _parent ) + { + KParts::BrowserHostExtension *hostExtension = 0; + KonqView *view = childView( callingPart, frameName, &hostExtension, 0 ); + if ( !view ) + { + KonqMainWindow *mainWindow = 0; + view = findChildView( callingPart, frameName, &mainWindow, &hostExtension, 0 ); + + if ( !view || !mainWindow ) + { + slotCreateNewWindow( url, args ); + return; + } + + if ( hostExtension ) + hostExtension->openURLInFrame( url, args ); + else + mainWindow->openURL( view, url, args ); + return; + } + + if ( hostExtension ) + hostExtension->openURLInFrame( url, args ); + else + openURL( view, url, args ); + return; + } + } + + KonqView *view = childView( callingPart ); + openURL( view, url, args ); +} + +//Called by slotOpenURLRequest +void KonqMainWindow::openURL( KonqView *childView, const KURL &url, const KParts::URLArgs &args ) +{ + kdDebug(1202) << "KonqMainWindow::openURL (from slotOpenURLRequest) url=" << url.prettyURL() << endl; + KonqOpenURLRequest req; + req.args = args; + + // Clicking on a link that points to the page itself (e.g. anchor) + if ( !args.doPost() && !args.reload && + childView && urlcmp( url.url(), childView->url().url(), true, true ) ) + { + TQString serviceType = args.serviceType; + if ( serviceType.isEmpty() ) + serviceType = childView->serviceType(); + + childView->stop(); + req.forceAutoEmbed = true; + + req.openAfterCurrentPage = KonqSettings::openAfterCurrentPage(); + openView( serviceType, url, childView, req ); + return; + } + + openURL( childView, url, args.serviceType, req, args.trustedSource ); +} + +TQObject *KonqMainWindow::lastFrame( KonqView *view ) +{ + TQObject *nextFrame, *viewFrame; + nextFrame = TQT_TQOBJECT(view->frame()); + viewFrame = 0; + while ( nextFrame != 0 && ! nextFrame->inherits( TQWIDGETSTACK_OBJECT_NAME_STRING ) ) { + viewFrame = nextFrame; + nextFrame = nextFrame->parent(); + } + return nextFrame ? viewFrame : 0L; +} + +// Linked-views feature, plus "sidebar follows URL opened in the active view" feature +bool KonqMainWindow::makeViewsFollow( const KURL & url, const KParts::URLArgs &args, + const TQString & serviceType, KonqView * senderView ) +{ + if ( !senderView->isLinkedView() && senderView != m_currentView ) + return false; // none of those features apply -> return + + bool res = false; + //kdDebug(1202) << "makeViewsFollow " << senderView->className() << " url=" << url << " serviceType=" << serviceType << endl; + KonqOpenURLRequest req; + req.followMode = true; + req.args = args; + // We can't iterate over the map here, and openURL for each, because the map can get modified + // (e.g. by part changes). Better copy the views into a list. + TQPtrList listViews; + MapViews::ConstIterator it = m_mapViews.begin(); + MapViews::ConstIterator end = m_mapViews.end(); + for (; it != end; ++it ) + listViews.append( it.data() ); + + TQObject *senderFrame = lastFrame( senderView ); + + for ( KonqView * view = listViews.first() ; view ; view = listViews.next()) + { + bool followed = false; + // Views that should follow this URL as both views are linked + if ( (view != senderView) && view->isLinkedView() && senderView->isLinkedView() ) + { + TQObject *viewFrame = lastFrame( view ); + + // Only views in the same tab of the sender will follow + if ( senderFrame && viewFrame && viewFrame != senderFrame ) + continue; + + kdDebug(1202) << "makeViewsFollow: Sending openURL to view " << view->part()->className() << " url=" << url << endl; + + // XXX duplicate code from ::openURL + if ( view == m_currentView ) + { + abortLoading(); + setLocationBarURL( url ); + } + else + view->stop(); + + followed = openView( serviceType, url, view, req ); + } + else + { + // Make the sidebar follow the URLs opened in the active view + if ((view!=senderView) && view->isFollowActive() && senderView == m_currentView) + { + followed = openView(serviceType, url, view, req); + } + } + + // Ignore return value if the view followed but doesn't really + // show the file contents. We still want to see that + // file, e.g. in a separate viewer. + // This happens in views locked to a directory mode, + // like sidebar and konsolepart (#52161). + bool ignore = view->isLockedViewMode() && view->supportsServiceType("inode/directory"); + //kdDebug(1202) << "View " << view->service()->name() + // << " supports dirs: " << view->supportsServiceType( "inode/directory" ) + // << " is locked-view-mode:" << view->isLockedViewMode() + // << " ignore=" << ignore << endl; + if ( !ignore ) + res = followed || res; + } + + return res; +} + +void KonqMainWindow::abortLoading() +{ + //kdDebug(1202) << "KonqMainWindow::abortLoading()" << endl; + if ( m_currentView ) + { + m_currentView->stop(); // will take care of the statusbar + stopAnimation(); + } +} + +void KonqMainWindow::slotCreateNewWindow( const KURL &url, const KParts::URLArgs &args ) +{ + kdDebug(1202) << "KonqMainWindow::slotCreateNewWindow url=" << url.prettyURL() << endl; + + if ( args.newTab() || ( KonqSettings::mmbOpensTab() && + (const_cast(&args)->metaData()["forcenewwindow"]).isEmpty()) ) { + KonqOpenURLRequest req; + req.newTab = true; + req.newTabInFront = KonqSettings::newTabsInFront(); + req.openAfterCurrentPage = KonqSettings::openAfterCurrentPage(); + + if (TDEApplication::keyboardMouseState() & TQt::ShiftButton) + req.newTabInFront = !req.newTabInFront; + req.args = args; + openURL( 0L, url, TQString::null, req ); + } + else + { + KonqMisc::createNewWindow( url, args ); + } +} + +// This is mostly for the JS window.open call +void KonqMainWindow::slotCreateNewWindow( const KURL &url, const KParts::URLArgs &args, + const KParts::WindowArgs &windowArgs, KParts::ReadOnlyPart *&part ) +{ + kdDebug(1202) << "KonqMainWindow::slotCreateNewWindow(4 args) url=" << url.prettyURL() + << " args.serviceType=" << args.serviceType + << " args.frameName=" << args.frameName << endl; + + part = 0; // Make sure to be initialized in case of failure... + + KonqMainWindow *mainWindow = 0L; + if ( !args.frameName.isEmpty() && args.frameName.lower() != "_blank" ) + { + KParts::BrowserHostExtension *hostExtension = 0; + KParts::ReadOnlyPart *ro_part = 0L; + KParts::BrowserExtension *be = ::tqqt_cast(sender()); + if (be) + ro_part = ::tqqt_cast(be->parent()); + if ( findChildView( ro_part, args.frameName, &mainWindow, &hostExtension, &part ) ) + { + // Found a view. If url isn't empty, we should open it - but this never happens currently + // findChildView put the resulting part in 'part', so we can just return now + //kdDebug() << " frame=" << args.frameName << " -> found part=" << part << " " << part->name() << endl; + return; + } + } + + if ( KonqSettings::popupsWithinTabs() || ( KonqSettings::mmbOpensTab() && windowArgs.lowerWindow ) ) { + bool aftercurrentpage = KonqSettings::openAfterCurrentPage(); + bool newtabsinfront = KonqSettings::newTabsInFront(); + if ( windowArgs.lowerWindow ) + newtabsinfront =! newtabsinfront; + + KonqView* newView = m_pViewManager->addTab(TQString::null, TQString::null, false, aftercurrentpage); + if (newView == 0L) return; + + if (newtabsinfront) + m_pViewManager->showTab( newView ); + + openURL( newView, url.isEmpty() ? KURL("about:blank") : url, TQString::null); + newView->setViewName( args.frameName ); + part=newView->part(); + + return; + } + + mainWindow = new KonqMainWindow( KURL(), false ); + mainWindow->setInitialFrameName( args.frameName ); + mainWindow->resetAutoSaveSettings(); // Don't autosave + + KonqOpenURLRequest req; + req.args = args; + + if ( args.serviceType.isEmpty() ) + mainWindow->openURL( 0L, url, TQString::null, req ); + else if ( !mainWindow->openView( args.serviceType, url, 0L, req ) ) + { + // we have problems. abort. + delete mainWindow; + part = 0; + return; + } + + KonqView * view = 0L; + // cannot use activePart/currentView, because the activation through the partmanager + // is delayed by a singleshot timer (see KonqViewManager::setActivePart) + if ( mainWindow->viewMap().count() ) + { + MapViews::ConstIterator it = mainWindow->viewMap().begin(); + view = it.data(); + part = it.key(); + } + + // activate the view _now_ in order to make the menuBar() hide call work + if ( part ) { + mainWindow->viewManager()->setActivePart( part, true ); + } + + TQString profileName = TQString::fromLatin1( url.isLocalFile() ? "konqueror/profiles/filemanagement" : "konqueror/profiles/webbrowsing" ); + KSimpleConfig cfg( locate( "data", profileName ), true ); + cfg.setGroup( "Profile" ); + + if ( windowArgs.x != -1 ) + mainWindow->move( windowArgs.x, mainWindow->y() ); + if ( windowArgs.y != -1 ) + mainWindow->move( mainWindow->x(), windowArgs.y ); + + TQSize size = KonqViewManager::readConfigSize( cfg, mainWindow ); + + int width; + if ( windowArgs.width != -1 ) + width = windowArgs.width; + else + width = size.isValid() ? size.width() : mainWindow->width(); + + int height; + if ( windowArgs.height != -1 ) + height = windowArgs.height; + else + height = size.isValid() ? size.height() : mainWindow->height(); + + mainWindow->resize( width, height ); + + // process the window args + + if ( !windowArgs.menuBarVisible ) + { + mainWindow->menuBar()->hide(); + mainWindow->m_paShowMenuBar->setChecked( false ); + } + + if ( !windowArgs.toolBarsVisible ) + { + for ( TQPtrListIterator it( mainWindow->toolBarIterator() ); it.current(); ++it ) + { + (*it)->hide(); + } + } + + if ( view ) { + if ( !windowArgs.scrollBarsVisible ) + view->disableScrolling(); + if ( !windowArgs.statusBarVisible ) + view->frame()->statusbar()->hide(); + } + + if ( !windowArgs.resizable ) + // ### this doesn't seem to work :-( + mainWindow->setSizePolicy( TQSizePolicy( TQSizePolicy::Fixed, TQSizePolicy::Fixed ) ); + +// Trying to show the window initially behind the current window is a bit tricky, +// as this involves the window manager, which may see things differently. +// Many WMs raise and activate new windows, which means without WM support this won't work very +// well. If the WM has support for _NET_WM_USER_TIME, it will be just set to 0 (=don't focus on show), +// and the WM should take care of it itself. + bool wm_usertime_support = false; + Time saved_last_input_time = GET_QT_X_USER_TIME(); + if ( windowArgs.lowerWindow ) + { + NETRootInfo wm_info( tqt_xdisplay(), NET::Supported ); + wm_usertime_support = wm_info.isSupported( NET::WM2UserTime ); + if( wm_usertime_support ) + { + // *sigh*, and I thought nobody would need TQWidget::dontFocusOnShow(). + // Avoid Qt's support for user time by setting it to 0, and + // set the property ourselves. + SET_QT_X_USER_TIME(0); + KWin::setUserTime( mainWindow->winId(), 0 ); + } + // Put below the current window before showing, in case that actually works with the WM. + // First do complete lower(), then stackUnder(), because the latter may not work with many WMs. + mainWindow->lower(); + mainWindow->stackUnder( this ); + } + + mainWindow->show(); + + if ( windowArgs.lowerWindow ) + { + SET_QT_X_USER_TIME(saved_last_input_time); + if( !wm_usertime_support ) + { // No WM support. Let's try ugly tricks. + mainWindow->lower(); + mainWindow->stackUnder( this ); + if( this->isActiveWindow()) + this->setActiveWindow(); + } + } + + if ( windowArgs.fullscreen ) + mainWindow->action( "fullscreen" )->activate(); +} + +void KonqMainWindow::slotNewWindow() +{ + // Use profile from current window, if set + TQString profile = m_pViewManager->currentProfile(); + if ( profile.isEmpty() ) + { + if ( m_currentView && m_currentView->url().protocol().startsWith( "http" ) ) + profile = TQString::fromLatin1("webbrowsing"); + else + profile = TQString::fromLatin1("filemanagement"); + } + KonqMisc::createBrowserWindowFromProfile( + locate( "data", TQString::fromLatin1("konqueror/profiles/")+profile ), + profile ); +} + +void KonqMainWindow::slotDuplicateWindow() +{ + KTempFile tempFile; + tempFile.setAutoDelete( true ); + TDEConfig config( tempFile.name() ); + config.setGroup( "View Profile" ); + m_pViewManager->saveViewProfile( config, true, true ); + + KonqMainWindow *mainWindow = new KonqMainWindow( KURL(), false, 0, xmlFile()); + mainWindow->viewManager()->loadViewProfile( config, m_pViewManager->currentProfile() ); + if (mainWindow->currentView()) + { + mainWindow->copyHistory( childFrame() ); + } + mainWindow->activateChild(); + mainWindow->show(); +#ifndef NDEBUG + mainWindow->viewManager()->printFullHierarchy( this ); +#endif +} + +void KonqMainWindow::slotSendURL() +{ + KURL::List lst = currentURLs(); + TQString body; + TQString fileNameList; + for ( KURL::List::Iterator it = lst.begin() ; it != lst.end() ; ++it ) + { + if ( !body.isEmpty() ) body += '\n'; + body += (*it).prettyURL(); + if ( !fileNameList.isEmpty() ) fileNameList += ", "; + fileNameList += (*it).fileName(); + } + TQString subject; + if ( m_currentView && !m_currentView->part()->inherits("KonqDirPart") ) + subject = m_currentView->caption(); + else + subject = fileNameList; + kapp->invokeMailer(TQString::null,TQString::null,TQString::null, + subject, body); +} + +void KonqMainWindow::slotSendFile() +{ + KURL::List lst = currentURLs(); + TQStringList urls; + TQString fileNameList; + for ( KURL::List::Iterator it = lst.begin() ; it != lst.end() ; ++it ) + { + if ( !fileNameList.isEmpty() ) fileNameList += ", "; + if ( (*it).isLocalFile() && TQFileInfo((*it).path()).isDir() ) + { + // Create a temp dir, so that we can put the ZIP file in it with a proper name + KTempFile zipFile; + TQString zipFileName = zipFile.name(); + zipFile.unlink(); + + TQDir().mkdir(zipFileName,true); + zipFileName = zipFileName+"/"+(*it).fileName()+".zip"; + KZip zip( zipFileName ); + if ( !zip.open( IO_WriteOnly ) ) + continue; // TODO error message + zip.addLocalDirectory( (*it).path(), TQString::null ); + zip.close(); + fileNameList += (*it).fileName()+".zip"; + urls.append( zipFileName ); + } + else + { + fileNameList += (*it).fileName(); + urls.append( (*it).url() ); + } + } + TQString subject; + if ( m_currentView && !m_currentView->part()->inherits("KonqDirPart") ) + subject = m_currentView->caption(); + else + subject = fileNameList; + kapp->invokeMailer(TQString::null, TQString::null, TQString::null, subject, + TQString::null, //body + TQString::null, + urls); // attachments +} + +void KonqMainWindow::slotOpenTerminal() +{ + TQString term = KonqSettings::terminalApplication(); + + TQString dir ( TQDir::homeDirPath() ); + + //Try to get the directory of the current view + if ( m_currentView ) + { + KURL u( m_currentView->url() ); + + // If the given directory is not local, it can still be the URL of an + // ioslave using UDS_LOCAL_PATH which to be converted first. + u = TDEIO::NetAccess::mostLocalURL(u, this); + + //If the URL is local after the above conversion, set the directory. + if ( u.isLocalFile() ) + { + TQString mime = m_currentView->serviceType(); + if ( KMimeType::mimeType(mime)->is("inode/directory") ) + dir = u.path(); + else + dir = u.directory(); + } + } + + TDEProcess cmd; + cmd.setWorkingDirectory(dir); + + // Compensate for terminal having arguments. + TQStringList args = TQStringList::split(' ', term); + for ( TQStringList::iterator it = args.begin(); it != args.end(); ++it ) + cmd << *it; + + kdDebug(1202) << "slotOpenTerminal: directory " << dir + << ", terminal:" << term << endl; + cmd.start(TDEProcess::DontCare); +} + +void KonqMainWindow::slotOpenLocation() +{ + // Don't pre-fill the url, as it is auto-selected and thus overwrites the + // X clipboard, making it impossible to paste in the url you really wanted. + // Another example of why the X clipboard sux + KURLRequesterDlg dlg( TQString::null, this, 0, true); + dlg.setCaption( i18n("Open Location") ); + // Set current directory for relative paths. + // Testcase: konqueror www.kde.org; Ctrl+O; file in $HOME; would open http://$file + TQString currentDir; + if (m_currentView && m_currentView->url().isLocalFile()) + currentDir = m_currentView->url().path(1); + dlg.urlRequester()->completionObject()->setDir( currentDir ); + dlg.urlRequester()->setMode( KFile::File | KFile::Directory | KFile::ExistingOnly ); + dlg.exec(); + const KURL& url = dlg.selectedURL(); + if (!url.isEmpty()) + openFilteredURL( url.url().stripWhiteSpace() ); +} + +void KonqMainWindow::slotToolFind() +{ + kdDebug(1202) << "KonqMainWindow::slotToolFind sender:" << TQT_TQOBJECT_CONST(sender())->className() << endl; + + if ( m_currentView && m_currentView->part()->inherits("KonqDirPart") ) + { + KonqDirPart* dirPart = static_cast(m_currentView->part()); + + if (!m_paFindFiles->isChecked()) + { + dirPart->slotFindClosed(); + return; + } + + KonqViewFactory factory = KonqFactory::createView( "Konqueror/FindPart" ); + if ( factory.isNull() ) + { + KMessageBox::error( this, i18n("Cannot create the find part, check your installation.") ); + m_paFindFiles->setChecked(false); + return; + } + + KParts::ReadOnlyPart* findPart = factory.create( m_currentView->frame(), "findPartWidget", dirPart, "findPart" ); + dirPart->setFindPart( findPart ); + + m_currentView->frame()->insertTopWidget( findPart->widget() ); + findPart->widget()->show(); + findPart->widget()->setFocus(); + + connect( dirPart, TQT_SIGNAL( findClosed(KonqDirPart *) ), + this, TQT_SLOT( slotFindClosed(KonqDirPart *) ) ); + } + else if ( TQT_TQOBJECT_CONST(sender())->inherits( "TDEAction" ) ) // don't go there if called by the singleShot below + { + KURL url; + if ( m_currentView && m_currentView->url().isLocalFile() ) + url = m_currentView->locationBarURL(); + else + url.setPath( TQDir::homeDirPath() ); + KonqMainWindow * mw = KonqMisc::createBrowserWindowFromProfile( + locate( "data", TQString::fromLatin1("konqueror/profiles/filemanagement") ), + "filemanagement", url, KParts::URLArgs(), true /* forbid "use html"*/ ); + mw->m_paFindFiles->setChecked(true); + // Delay it after the openURL call (hacky!) + TQTimer::singleShot( 1, mw, TQT_SLOT(slotToolFind())); + m_paFindFiles->setChecked(false); + } +} + +void KonqMainWindow::slotFindOpen( KonqDirPart * dirPart ) +{ + kdDebug(1202) << "KonqMainWindow::slotFindOpen " << dirPart << endl; + Q_ASSERT( m_currentView ); + Q_ASSERT( m_currentView->part() == dirPart ); + slotToolFind(); // lazy me +} + +void KonqMainWindow::slotFindClosed( KonqDirPart * dirPart ) +{ + kdDebug(1202) << "KonqMainWindow::slotFindClosed " << dirPart << endl; + KonqView * dirView = m_mapViews.find( dirPart ).data(); + Q_ASSERT(dirView); + kdDebug(1202) << "dirView=" << dirView << endl; + if ( dirView && dirView == m_currentView ) + m_paFindFiles->setEnabled( true ); + m_paFindFiles->setChecked(false); +} + +void KonqMainWindow::slotIconsChanged() +{ + //kdDebug(1202) << "KonqMainWindow::slotIconsChanged" << endl; + m_combo->updatePixmaps(); + m_pViewManager->updatePixmaps(); + setIcon( KonqPixmapProvider::self()->pixmapFor( m_combo->currentText() )); +} + +void KonqMainWindow::slotOpenWith() +{ + KURL::List lst; + lst.append( m_currentView->url() ); + + TQString serviceName = TQT_TQOBJECT_CONST(sender())->name(); + + TDETrader::OfferList offers = m_currentView->appServiceOffers(); + TDETrader::OfferList::ConstIterator it = offers.begin(); + TDETrader::OfferList::ConstIterator end = offers.end(); + for (; it != end; ++it ) + if ( (*it)->desktopEntryName() == serviceName ) + { + KRun::run( **it, lst ); + return; + } +} + +void KonqMainWindow::slotViewModeToggle( bool toggle ) +{ + if ( !toggle ) + return; + + TQString modeName = TQT_TQOBJECT_CONST(sender())->name(); + + if ( m_currentView->service()->desktopEntryName() == modeName ) + return; + + m_bViewModeToggled = true; + + m_currentView->stop(); + m_currentView->lockHistory(); + + // Save those, because changeViewMode will lose them + KURL url = m_currentView->url(); + TQString locationBarURL = m_currentView->locationBarURL(); + TQStringList filesToSelect; + if( m_currentView->part()->inherits( "KonqDirPart" ) ) { + KFileItemList fileItemsToSelect = static_cast(m_currentView->part())->selectedFileItems(); + KFileItemListIterator it( fileItemsToSelect ); + while( it.current() ){ + filesToSelect += it.current()->name(); + ++it; + } + } + + + bool bQuickViewModeChange = false; + + // iterate over all services, update the toolbar service map + // and check if we can do a quick property-based viewmode change + const TDETrader::OfferList offers = m_currentView->partServiceOffers(); + TDETrader::OfferList::ConstIterator oIt = offers.begin(); + TDETrader::OfferList::ConstIterator oEnd = offers.end(); + const TQString currentServiceKey = viewModeActionKey( m_currentView->service() ); + for (; oIt != oEnd; ++oIt ) + { + KService::Ptr service = *oIt; + + if ( service->desktopEntryName() == modeName ) + { + // we changed the viewmode of either iconview or listview + // -> update the service in the corresponding map, so that + // we can set the correct text, icon, etc. properties to the + // KonqViewModeAction when rebuilding the view-mode actions in + // updateViewModeActions + // (I'm saying iconview/listview here, but theoretically it could be + // any view :) + const TQString serviceKey = viewModeActionKey( service ); + m_viewModeToolBarServices[ serviceKey ] = service; + + if ( serviceKey == currentServiceKey ) + { + TQVariant modeProp = service->property( "X-TDE-BrowserView-ModeProperty" ); + TQVariant modePropValue = service->property( "X-TDE-BrowserView-ModePropertyValue" ); + if ( !modeProp.isValid() || !modePropValue.isValid() ) + break; + + m_currentView->part()->setProperty( modeProp.toString().latin1(), modePropValue ); + + KService::Ptr oldService = m_currentView->service(); + + // we aren't going to re-build the viewmode actions but instead of a + // quick viewmode change (iconview) -> find the iconview-konqviewmode + // action and set new text,icon,etc. properties, to show the new + // current viewmode + TQPtrListIterator it( m_toolBarViewModeActions ); + for (; it.current(); ++it ) + if ( TQString::fromLatin1( it.current()->name() ) == oldService->desktopEntryName() ) + { + assert( it.current()->inherits( "KonqViewModeAction" ) ); + + KonqViewModeAction *action = static_cast( it.current() ); + + action->setChecked( true ); + TQString servicename = service->genericName(); + if (servicename.isEmpty()) + servicename = service->name(); + action->setText( servicename ); + action->setIcon( service->icon() ); + action->setName( service->desktopEntryName().ascii() ); + + break; + } + + m_currentView->setService( service ); + + bQuickViewModeChange = true; + break; + } + } + } + + if ( !bQuickViewModeChange ) + { + m_currentView->changeViewMode( m_currentView->serviceType(), modeName ); + KURL locURL = KURL::fromPathOrURL( locationBarURL ); + TQString nameFilter = detectNameFilter( locURL ); + if( m_currentView->part()->inherits( "KonqDirPart" ) ) + static_cast( m_currentView->part() )->setFilesToSelect( filesToSelect ); + m_currentView->openURL( locURL, locationBarURL, nameFilter ); + } + + // Now save this setting, either locally or globally (for directories only) + // (We don't have views with viewmodes other than for dirs currently; + // once we do, we might want to implement per-mimetype global-saving) + if ( m_bSaveViewPropertiesLocally && m_currentView->supportsServiceType( "inode/directory" ) ) + { + KURL u ( m_currentView->url() ); + u.addPath(".directory"); + if ( u.isLocalFile() ) + { + KSimpleConfig config( u.path() ); // if we have no write access, just drop it + config.setGroup( "URL properties" ); + config.writeEntry( "ViewMode", modeName ); + config.sync(); + } + } else + { + // We save the global view mode only if the view is a built-in view + if ( m_currentView->isBuiltinView() ) + { + KonqSettings::setMainViewViewMode( modeName ); + KonqSettings::writeConfig(); + } + } +} + +void KonqMainWindow::showHTML( KonqView * _view, bool b, bool _activateView ) +{ + // Save this setting, either locally or globally + // This has to be done before calling openView since it relies on it + if ( m_bSaveViewPropertiesLocally ) + { + KURL u ( b ? _view->url() : KURL( _view->url().directory() ) ); + u.addPath(".directory"); + if ( u.isLocalFile() ) + { + KSimpleConfig config( u.path() ); // No checks for access + config.setGroup( "URL properties" ); + config.writeEntry( "HTMLAllowed", b ); + config.sync(); + } + } else + { + KonqSettings::setHtmlAllowed( b ); + KonqSettings::writeConfig(); + if ( _activateView ) + m_bHTMLAllowed = b; + } + + if ( b && _view->supportsServiceType( "inode/directory" ) ) + { + _view->lockHistory(); + openView( "inode/directory", _view->url(), _view ); + } + else if ( !b && _view->supportsServiceType( "text/html" ) ) + { + KURL u( _view->url() ); + TQString fileName = u.fileName().lower(); + if ( KProtocolInfo::supportsListing( u ) && fileName.startsWith("index.htm") ) { + _view->lockHistory(); + u.setPath( u.directory() ); + openView( "inode/directory", u, _view ); + } + } +} + +void KonqMainWindow::slotShowHTML() +{ + bool b = !m_currentView->allowHTML(); + + m_currentView->stop(); + m_currentView->setAllowHTML( b ); + showHTML( m_currentView, b, true ); //current view + m_pViewManager->showHTML(b ); + +} + +void KonqMainWindow::setShowHTML( bool b ) +{ + m_bHTMLAllowed = b; + if ( m_currentView ) + m_currentView->setAllowHTML( b ); + m_ptaUseHTML->setChecked( b ); +} + +void KonqMainWindow::slotLockView() +{ + m_currentView->setLockedLocation( m_paLockView->isChecked() ); +} + +void KonqMainWindow::slotStop() +{ + abortLoading(); + if ( m_currentView ) + { + m_currentView->frame()->statusbar()->message( i18n("Canceled.") ); + } +} + +void KonqMainWindow::slotLinkView() +{ + // Can't access this action in passive mode anyway + assert(!m_currentView->isPassiveMode()); + bool mode = !m_currentView->isLinkedView(); + + if (linkableViewsCount() == 2) + { + // Exactly two linkable views : link both + KonqMainWindow::MapViews::ConstIterator it = viewMap().begin(); + if( (*it)->isFollowActive() ) // skip sidebar + ++it; + (*it)->setLinkedView( mode ); + ++it; + if( (*it)->isFollowActive() ) // skip sidebar + ++it; + (*it)->setLinkedView( mode ); + } + else // Normal case : just this view + m_currentView->setLinkedView( mode ); +} + +void KonqMainWindow::slotReload( KonqView* reloadView ) +{ + if ( !reloadView ) + reloadView = m_currentView; + + if ( !reloadView || reloadView->url().isEmpty() ) + return; + + if ( reloadView->part() && (reloadView->part()->metaObject()->findProperty("modified") != -1) ) { + TQVariant prop = reloadView->part()->property("modified"); + if (prop.isValid() && prop.toBool()) + if ( KMessageBox::warningContinueCancel( this, + i18n("This page contains changes that have not been submitted.\nReloading the page will discard these changes."), + i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"reload"), "discardchangesreload") != KMessageBox::Continue ) + return; + } + + KonqOpenURLRequest req( reloadView->typedURL() ); + req.userRequestedReload = true; + if ( reloadView->prepareReload( req.args ) ) + { + reloadView->lockHistory(); + // Reuse current servicetype for local files, but not for remote files (it could have changed, e.g. over HTTP) + TQString serviceType = reloadView->url().isLocalFile() ? reloadView->serviceType() : TQString::null; + openURL( reloadView, reloadView->url(), serviceType, req ); + } +} + +void KonqMainWindow::slotReloadStop() { + if (m_paReloadStop->icon() == "reload") { + slotReload(); + toggleReloadStopButton(true); + } else { + slotStop(); + toggleReloadStopButton(false); + } +} + +void KonqMainWindow::toggleReloadStopButton(bool isReload) { + //m_paStop = new TDEAction( i18n( "&Stop" ), "process-stop", Key_Escape, this, TQT_SLOT( slotStop() ), actionCollection(), "stop" ); + if (isReload) { + m_paReloadStop->setIcon("process-stop"); + m_paReloadStop->setWhatsThis( i18n( "Stop loading the document

" + "All network transfers will be stopped and Konqueror will display the content " + "that has been received so far." ) ); + m_paReloadStop->setToolTip( i18n( "Stop loading the document" ) ); + //m_paReloadStop = new TDEAction( i18n( "&Reload" ), "reload", reloadShortcut, this, TQT_SLOT( slotReloadStop() ), actionCollection(), "reload" ); + } else { + m_paReloadStop->setIcon("reload"); + m_paReloadStop->setWhatsThis( i18n( "Reload the currently displayed document

" + "This may, for example, be needed to refresh webpages that have been " + "modified since they were loaded, in order to make the changes visible." ) ); + m_paReloadStop->setToolTip( i18n( "Reload the currently displayed document" ) ); + } +} + +void KonqMainWindow::slotReloadPopup() +{ + if (m_pWorkingTab) + slotReload( m_pWorkingTab->activeChildView() ); +} + +void KonqMainWindow::slotHome(TDEAction::ActivationReason, TQt::ButtonState state) +{ + TQString homeURL = m_pViewManager->profileHomeURL(); + + if (homeURL.isEmpty()) + homeURL = KonqFMSettings::settings()->homeURL(); + + KonqOpenURLRequest req; + req.newTab = true; + req.newTabInFront = KonqSettings::newTabsInFront(); + + if (state & TQt::ShiftButton) + req.newTabInFront = !req.newTabInFront; + + if( state & TQt::ControlButton ) // Ctrl Left/MMB + openFilteredURL( homeURL, req); + else if( state & Qt::MidButton ) + { + if(KonqSettings::mmbOpensTab()) + openFilteredURL( homeURL, req); + else + { + KURL finalURL = KonqMisc::konqFilteredURL( this, homeURL ); + KonqMisc::createNewWindow( finalURL.url() ); + } + } + else + openFilteredURL( homeURL, false ); +} + + +void KonqMainWindow::slotHome() +{ + slotHome(TDEAction::UnknownActivation, Qt::LeftButton); +} + +void KonqMainWindow::slotGoSystem() +{ + openURL( 0L, KURL( "system:/" ) ); +} + +void KonqMainWindow::slotGoApplications() +{ + openURL( 0L, KURL( "programs:/" ) ); +} + +void KonqMainWindow::slotGoMedia() +{ + openURL( 0L, KURL( "media:/" ) ); +} + +void KonqMainWindow::slotGoNetworkFolders() +{ + openURL( 0L, KURL( "remote:/" ) ); +} + +void KonqMainWindow::slotGoSettings() +{ + openURL( 0L, KURL( "settings:/" ) ); +} + +void KonqMainWindow::slotGoDirTree() +{ + KURL u; + u.setPath( locateLocal( "data", "konqueror/dirtree/" ) ); + openURL( 0L, u ); +} + +void KonqMainWindow::slotGoTrash() +{ + openURL( 0L, KURL( "trash:/" ) ); +} + +void KonqMainWindow::slotGoAutostart() +{ + KURL u; + u.setPath( TDEGlobalSettings::autostartPath() ); + openURL( 0L, u ); +} + +void KonqMainWindow::slotGoHistory() +{ + TDEAction *a = m_toggleViewGUIClient->action("konq_sidebartng"); + if (!a) { + KMessageBox::sorry(0L, i18n("Your sidebar is not functional or unavailable."), i18n("Show History Sidebar")); + return; + } + + // Show the sidebar + if (!static_cast(a)->isChecked()) { + a->activate(); + TQTimer::singleShot( 0, this, TQT_SLOT(slotGoHistory())); + return; + } + + // Tell it to show the history plugin + MapViews::ConstIterator it; + for (it = viewMap().begin(); it != viewMap().end(); ++it) { + KonqView *view = it.data(); + if (view) { + KService::Ptr svc = view->service(); + if (svc->desktopEntryName() == "konq_sidebartng") { + if (!view->part()->openURL("sidebar:history.desktop")) + KMessageBox::sorry(0L, i18n("Cannot find running history plugin in your sidebar."), i18n("Show History Sidebar")); + break; + } + } + } +} + +TQStringList KonqMainWindow::configModules() const +{ + return m_configureModules; +} + +void KonqMainWindow::slotConfigureExtensions() +{ + KonqExtensionManager extensionManager(0, this, m_currentView ? m_currentView->part() : 0); + extensionManager.exec(); +} + +void KonqMainWindow::slotConfigure() +{ + if( !m_configureDialog ) + { + m_configureDialog = new KCMultiDialog( this, "configureDialog" ); + + TQStringList modules = configModules(); + TQStringList::ConstIterator end( modules.end() ); + + for( TQStringList::ConstIterator it = modules.begin(); + it != end; ++it ) + { + if ( kapp->authorizeControlModule( *it ) ) + { + m_configureDialog->addModule( *it ); + } + } + + } + + m_configureDialog->show(); + +} + +void KonqMainWindow::slotConfigureSpellChecking() +{ + TDEApplication::startServiceByDesktopName("spellchecking"); +} + +void KonqMainWindow::slotConfigureToolbars() +{ + if ( autoSaveSettings() ) + saveMainWindowSettings( TDEGlobal::config(), "KonqMainWindow" ); + KEditToolbar dlg(factory()); + connect(&dlg,TQT_SIGNAL(newToolbarConfig()),this,TQT_SLOT(slotNewToolbarConfig())); + connect(&dlg,TQT_SIGNAL(newToolbarConfig()),this,TQT_SLOT(initBookmarkBar())); + dlg.exec(); +} + +void KonqMainWindow::slotNewToolbarConfig() // This is called when OK or Apply is clicked +{ + if ( m_toggleViewGUIClient ) + plugActionList( TQString::fromLatin1( "toggleview" ), m_toggleViewGUIClient->actions() ); + if ( m_currentView && m_currentView->appServiceOffers().count() > 0 ) + plugActionList( "openwith", m_openWithActions ); + + plugViewModeActions(); + + applyMainWindowSettings( TDEGlobal::config(), "KonqMainWindow" ); +} + +void KonqMainWindow::slotUndoAvailable( bool avail ) +{ + bool enable = false; + + if ( avail && m_currentView && m_currentView->part() ) + { + // Avoid tqWarning from TQObject::property if it doesn't exist + if ( m_currentView->part()->metaObject()->findProperty( "supportsUndo" ) != -1 ) + { + TQVariant prop = m_currentView->part()->property( "supportsUndo" ); + if ( prop.isValid() && prop.toBool() ) + enable = true; + } + } + + m_paUndo->setEnabled( enable ); +} + +void KonqMainWindow::slotPartChanged( KonqView *childView, KParts::ReadOnlyPart *oldPart, KParts::ReadOnlyPart *newPart ) +{ + kdDebug(1202) << "KonqMainWindow::slotPartChanged" << endl; + m_mapViews.remove( oldPart ); + m_mapViews.insert( newPart, childView ); + + // Remove the old part, and add the new part to the manager + // Note: this makes the new part active... so it calls slotPartActivated + + m_pViewManager->replacePart( oldPart, newPart, false ); + // Set active immediately + m_pViewManager->setActivePart( newPart, true ); + + viewsChanged(); +} + + +void KonqMainWindow::slotRunFinished() +{ + kdDebug(1202) << "KonqMainWindow::slotRunFinished()" << endl; + const KonqRun *run = static_cast( sender() ); + + if ( run == m_initialKonqRun ) + m_initialKonqRun = 0L; + + if ( !run->mailtoURL().isEmpty() ) + { + kapp->invokeMailer( run->mailtoURL() ); + } + + if ( run->hasError() ) { // we had an error + TQByteArray data; + TQDataStream s( data, IO_WriteOnly ); + s << run->url().prettyURL() << kapp->dcopClient()->defaultObject(); + kapp->dcopClient()->send( "konqueror*", "KonquerorIface", + "removeFromCombo(TQString,TQCString)", data); + } + + KonqView *childView = run->childView(); + + // Check if we found a mimetype _and_ we got no error (example: cancel in openwith dialog) + if ( run->foundMimeType() && !run->hasError() ) + { + + // We do this here and not in the constructor, because + // we are waiting for the first view to be set up before doing this... + // Note: this is only used when konqueror is started from command line..... + if ( m_bNeedApplyKonqMainWindowSettings ) + { + m_bNeedApplyKonqMainWindowSettings = false; // only once + applyKonqMainWindowSettings(); + } + + return; + } + + if ( childView ) + { + childView->setLoading( false ); + + if ( childView == m_currentView ) + { + stopAnimation(); + + // Revert to working URL - unless the URL was typed manually + kdDebug(1202) << " typed URL = " << run->typedURL() << endl; + if ( run->typedURL().isEmpty() && childView->history().current() ) // not typed + childView->setLocationBarURL( childView->history().current()->locationBarURL ); + } + } + else // No view, e.g. empty webbrowsing profile + stopAnimation(); +} + +void KonqMainWindow::applyKonqMainWindowSettings() +{ + TQStringList toggableViewsShown = KonqSettings::toggableViewsShown(); + TQStringList::ConstIterator togIt = toggableViewsShown.begin(); + TQStringList::ConstIterator togEnd = toggableViewsShown.end(); + for ( ; togIt != togEnd ; ++togIt ) + { + // Find the action by name + // TDEAction * act = m_toggleViewGUIClient->actionCollection()->action( (*togIt).latin1() ); + TDEAction *act = m_toggleViewGUIClient->action( *togIt ); + if ( act ) + act->activate(); + else + kdWarning(1202) << "Unknown toggable view in ToggableViewsShown " << *togIt << endl; + } +} + +void KonqMainWindow::slotSetStatusBarText( const TQString & ) +{ + // Reimplemented to disable KParts::MainWindow default behaviour + // Does nothing here, see konq_frame.cpp +} + +void KonqMainWindow::slotViewCompleted( KonqView * view ) +{ + assert( view ); + + // Need to update the current working directory + // of the completion object every time the user + // changes the directory!! (DA) + if( m_pURLCompletion ) + { + KURL u( view->locationBarURL() ); + if( u.isLocalFile() ) + m_pURLCompletion->setDir( u.path() ); + else + m_pURLCompletion->setDir( u.url() ); //needs work!! (DA) + } +} + +void KonqMainWindow::slotPartActivated( KParts::Part *part ) +{ + kdDebug(1202) << "KonqMainWindow::slotPartActivated " << part << " " + << ( part && part->instance() && part->instance()->aboutData() ? part->instance()->aboutData()->appName() : "" ) << endl; + + KonqView *newView = 0; + KonqView *oldView = m_currentView; + + if ( part ) + { + newView = m_mapViews.find( static_cast( part ) ).data(); + + if ( newView->isPassiveMode() ) + { + // Passive view. Don't connect anything, don't change m_currentView + // Another view will become the current view very soon + kdDebug(1202) << "KonqMainWindow::slotPartActivated: Passive mode - return" << endl; + return; + } + } + + KParts::BrowserExtension *ext = 0; + + if ( oldView ) + { + ext = oldView->browserExtension(); + if ( ext ) + { + //kdDebug(1202) << "Disconnecting extension for view " << oldView << endl; + disconnectExtension( ext ); + } + + if ( oldView->part() ) + { + TDEActionCollection *coll = oldView->part()->actionCollection(); + if ( coll ) + disconnectActionCollection( coll ); + } + } + + kdDebug(1202) << "KonqMainWindow::slotPartActivated: New current view " << newView << endl; + m_currentView = newView; + if ( !part ) + { + kdDebug(1202) << "KonqMainWindow::slotPartActivated: No part activated - returning" << endl; + unplugViewModeActions(); + createGUI( 0L ); + KParts::MainWindow::setCaption( "" ); + KParts::MainWindow::setIcon( kapp->icon()); + return; + } + + ext = m_currentView->browserExtension(); + + if ( ext ) + { + connectExtension( ext ); + } + else + { + kdDebug(1202) << "KonqMainWindow::slotPartActivated: No Browser Extension for the new part" << endl; + // Disable all browser-extension actions + + KParts::BrowserExtension::ActionSlotMap * actionSlotMap = KParts::BrowserExtension::actionSlotMapPtr(); + KParts::BrowserExtension::ActionSlotMap::ConstIterator it = actionSlotMap->begin(); + KParts::BrowserExtension::ActionSlotMap::ConstIterator itEnd = actionSlotMap->end(); + + for ( ; it != itEnd ; ++it ) + { + TDEAction * act = actionCollection()->action( static_cast(it.key()) ); + Q_ASSERT(act); + if (act) + act->setEnabled( false ); + } + + m_paCopyFiles->setEnabled( false ); + m_paMoveFiles->setEnabled( false ); + m_paNewDir->setEnabled( false ); + } + createGUI( part ); + + TDEActionCollection *coll = m_currentView->part()->actionCollection(); + if ( coll ) + connectActionCollection( coll ); + + // View-dependent GUI + + KParts::MainWindow::setCaption( m_currentView->caption() ); + m_currentView->frame()->setTitle( m_currentView->caption() , 0L); + updateOpenWithActions(); + updateLocalPropsActions(); + updateViewActions(); // undo, lock, link and other view-dependent actions + + if ( m_bViewModeToggled ) + { + // if we just toggled the view mode via the view mode actions, then + // we don't need to do all the time-taking stuff below (Simon) + const TQString currentServiceDesktopEntryName = m_currentView->service()->desktopEntryName(); + TQPtrListIterator it( m_viewModeActions ); + for (; it.current(); ++it ) { + if ( it.current()->name() == currentServiceDesktopEntryName ) { + it.current()->setChecked( true ); + break; + } + } + const TQString currentServiceLibrary = viewModeActionKey( m_currentView->service() ); + TQPtrListIterator ittb( m_toolBarViewModeActions ); + for (; ittb.current(); ++ittb ) { + KService::Ptr serv = KService::serviceByDesktopName( ittb.current()->name() ); + if ( serv && viewModeActionKey( serv ) == currentServiceLibrary ) { + TDEToggleAction* ta = static_cast( ittb.current() ); + ta->setChecked( false ); + TQString servicename = m_currentView->service()->genericName(); + if (servicename.isEmpty()) + servicename = m_currentView->service()->name(); + ta->setText( servicename ); + ta->setIcon( m_currentView->service()->icon() ); + ta->setName( m_currentView->service()->desktopEntryName().ascii() ) ; + break; + } + } + } + else + { + updateViewModeActions(); + } + + m_bViewModeToggled = false; + + + m_pMenuNew->setEnabled( m_currentView->supportsServiceType( "inode/directory" ) ); + + m_currentView->frame()->statusbar()->updateActiveStatus(); + + if ( oldView && oldView->frame() ) + oldView->frame()->statusbar()->updateActiveStatus(); + + //kdDebug(1202) << "KonqMainWindow::slotPartActivated: setting location bar url to " + // << m_currentView->locationBarURL() << " m_currentView=" << m_currentView << endl; + m_currentView->setLocationBarURL( m_currentView->locationBarURL() ); + + updateToolBarActions(); + + m_currentView->setActiveInstance(); +} + +void KonqMainWindow::insertChildView( KonqView *childView ) +{ + kdDebug(1202) << "KonqMainWindow::insertChildView " << childView << endl; + m_mapViews.insert( childView->part(), childView ); + + connect( childView, TQT_SIGNAL( viewCompleted( KonqView * ) ), + this, TQT_SLOT( slotViewCompleted( KonqView * ) ) ); + + if ( !m_pViewManager->isLoadingProfile() ) // see KonqViewManager::loadViewProfile + viewCountChanged(); + emit viewAdded( childView ); +} + +// Called by KonqViewManager, internal +void KonqMainWindow::removeChildView( KonqView *childView ) +{ + kdDebug(1202) << "KonqMainWindow::removeChildView childView " << childView << endl; + + disconnect( childView, TQT_SIGNAL( viewCompleted( KonqView * ) ), + this, TQT_SLOT( slotViewCompleted( KonqView * ) ) ); + +#ifndef NDEBUG + dumpViewList(); +#endif + + MapViews::Iterator it = m_mapViews.begin(); + MapViews::Iterator end = m_mapViews.end(); + + // find it in the map - can't use the key since childView->part() might be 0L + + kdDebug(1202) << "Searching map" << endl; + + while ( it != end && it.data() != childView ) + ++it; + + kdDebug(1202) << "Verifying search results" << endl; + + if ( it == m_mapViews.end() ) + { + kdWarning(1202) << "KonqMainWindow::removeChildView childView " << childView << " not in map !" << endl; + return; + } + + kdDebug(1202) << "Removing view " << childView << endl; + + m_mapViews.remove( it ); + + kdDebug(1202) << "View " << childView << " removed from map" << endl; + + viewCountChanged(); + emit viewRemoved( childView ); + +#ifndef NDEBUG + dumpViewList(); +#endif + + // KonqViewManager takes care of m_currentView +} + +void KonqMainWindow::viewCountChanged() +{ + // This is called when the number of views changes. + kdDebug(1202) << "KonqMainWindow::viewCountChanged" << endl; + + int lvc = linkableViewsCount(); + m_paLinkView->setEnabled( lvc > 1 ); + + // Only one view (or one view + sidebar) -> make it/them unlinked + if ( lvc == 1 ) { + MapViews::Iterator it = m_mapViews.begin(); + MapViews::Iterator end = m_mapViews.end(); + for (; it != end; ++it ) + it.data()->setLinkedView( false ); + } + + viewsChanged(); + + m_pViewManager->viewCountChanged(); +} + +void KonqMainWindow::viewsChanged() +{ + // This is called when the number of views changes OR when + // the type of some view changes. + + // Nothing here anymore, but don't cleanup, some might come back later. + + updateViewActions(); // undo, lock, link and other view-dependent actions +} + +KonqView * KonqMainWindow::childView( KParts::ReadOnlyPart *view ) +{ + MapViews::ConstIterator it = m_mapViews.find( view ); + if ( it != m_mapViews.end() ) + return it.data(); + else + return 0L; +} + +KonqView * KonqMainWindow::childView( KParts::ReadOnlyPart *callingPart, const TQString &name, KParts::BrowserHostExtension **hostExtension, KParts::ReadOnlyPart **part ) +{ + kdDebug() << "KonqMainWindow::childView this=" << this << " looking for " << name << endl; + + MapViews::ConstIterator it = m_mapViews.begin(); + MapViews::ConstIterator end = m_mapViews.end(); + for (; it != end; ++it ) + { + KonqView* view = it.data(); + TQString viewName = view->viewName(); + kdDebug() << " - viewName=" << viewName << " " + << "frame names:" << view->frameNames().join( "," ) << endl; + + // First look for a hostextension containing this frame name + KParts::BrowserHostExtension *ext = KParts::BrowserHostExtension::childObject( view->part() ); + if ( ext ) + { + ext = ext->findFrameParent(callingPart, name); + kdDebug() << "BrowserHostExtension found part " << ext << endl; + if (!ext) + continue; // Don't use this window + } + + if ( !viewName.isEmpty() && viewName == name ) + { + kdDebug() << "found existing view by name: " << view << endl; + if ( hostExtension ) + *hostExtension = 0; + if ( part ) + *part = view->part(); + return view; + } + +// KParts::BrowserHostExtension* ext = KonqView::hostExtension( view->part(), name ); + + if ( ext ) + { + TQPtrList frames = ext->frames(); + TQPtrListIterator frameIt( frames ); + for ( ; frameIt.current() ; ++frameIt ) + { + if ( frameIt.current()->name() == name ) + { + kdDebug() << "found a frame of name " << name << " : " << frameIt.current() << endl; + if ( hostExtension ) + *hostExtension = ext; + if ( part ) + *part = frameIt.current(); + return view; + } + } + } + } + + return 0; +} + +// static +KonqView * KonqMainWindow::findChildView( KParts::ReadOnlyPart *callingPart, const TQString &name, KonqMainWindow **mainWindow, KParts::BrowserHostExtension **hostExtension, KParts::ReadOnlyPart **part ) +{ + if ( !s_lstViews ) + return 0; + + TQPtrListIterator it( *s_lstViews ); + for (; it.current(); ++it ) + { + KonqView *res = it.current()->childView( callingPart, name, hostExtension, part ); + if ( res ) + { + if ( mainWindow ) + *mainWindow = it.current(); + return res; + } + } + + return 0; +} + +int KonqMainWindow::activeViewsCount() const +{ + int res = 0; + MapViews::ConstIterator it = m_mapViews.begin(); + MapViews::ConstIterator end = m_mapViews.end(); + for (; it != end; ++it ) + if ( !it.data()->isPassiveMode() ) + ++res; + + return res; +} + +int KonqMainWindow::linkableViewsCount() const +{ + int res = 0; + MapViews::ConstIterator it = m_mapViews.begin(); + MapViews::ConstIterator end = m_mapViews.end(); + for (; it != end; ++it ) + if ( !it.data()->isFollowActive() ) + ++res; + + return res; +} + +int KonqMainWindow::mainViewsCount() const +{ + int res = 0; + MapViews::ConstIterator it = m_mapViews.begin(); + MapViews::ConstIterator end = m_mapViews.end(); + for (; it != end; ++it ) + if ( !it.data()->isPassiveMode() && !it.data()->isToggleView() ) + { + //kdDebug(1202) << "KonqMainWindow::mainViewsCount " << res << " " << it.data() << " " << it.data()->part()->widget() << endl; + ++res; + } + + return res; +} + +KParts::ReadOnlyPart * KonqMainWindow::currentPart() const +{ + /// ### This is currently unused. Check in the final version (!) if still unused. + if ( m_currentView ) + return m_currentView->part(); + else + return 0L; +} + +void KonqMainWindow::customEvent( TQCustomEvent *event ) +{ + KParts::MainWindow::customEvent( event ); + + if ( KonqFileSelectionEvent::test( event ) || + KonqFileMouseOverEvent::test( event ) ) + { + // Forward the event to all views + MapViews::ConstIterator it = m_mapViews.begin(); + MapViews::ConstIterator end = m_mapViews.end(); + for (; it != end; ++it ) + TQApplication::sendEvent( (*it)->part(), event ); + return; + } + if ( KParts::OpenURLEvent::test( event ) ) + { + KParts::OpenURLEvent * ev = static_cast(event); + KonqView * senderChildView = childView(ev->part()); + + // Enable/disable local properties actions if current view + if ( senderChildView == m_currentView ) + updateLocalPropsActions(); + + // Forward the event to all views + MapViews::ConstIterator it = m_mapViews.begin(); + MapViews::ConstIterator end = m_mapViews.end(); + for (; it != end; ++it ) + { + // Don't resend to sender + if (it.key() != ev->part()) + { + //kdDebug(1202) << "Sending event to view " << it.key()->className() << endl; + TQApplication::sendEvent( it.key(), event ); + + } + } + } +} + +void KonqMainWindow::updateLocalPropsActions() +{ + bool canWrite = false; + if ( m_currentView && m_currentView->url().isLocalFile() ) + { + // Can we write ? + TQFileInfo info( m_currentView->url().path() ); + canWrite = info.isDir() && info.isWritable(); + } + m_paSaveViewPropertiesLocally->setEnabled( canWrite ); + m_paRemoveLocalProperties->setEnabled( canWrite ); +} + +void KonqMainWindow::slotURLEntered( const TQString &text, int state ) +{ + if ( m_bURLEnterLock || text.isEmpty() ) + return; + + m_bURLEnterLock = true; + + if (state & ControlButton || state & AltButton) + { + m_combo->setURL( m_currentView ? m_currentView->url().prettyURL() : TQString::null ); + openFilteredURL( text.stripWhiteSpace(), true ); + } + else + openFilteredURL( text.stripWhiteSpace() ); + + m_bURLEnterLock = false; +} + +void KonqMainWindow::slotFileNewAboutToShow() +{ + // As requested by KNewMenu : + m_pMenuNew->slotCheckUpToDate(); + // And set the files that the menu apply on : + m_pMenuNew->setPopupFiles( KURL( m_currentView->url().url() ) ); +} + +void KonqMainWindow::slotSplitViewHorizontal() +{ + KonqView * newView = m_pViewManager->splitView( Qt::Horizontal ); + if (newView == 0L) return; + newView->openURL( m_currentView->url(), m_currentView->locationBarURL() ); +} + +void KonqMainWindow::slotSplitViewVertical() +{ + KonqView * newView = m_pViewManager->splitView( Qt::Vertical ); + if (newView == 0L) return; + newView->openURL( m_currentView->url(), m_currentView->locationBarURL() ); +} + +void KonqMainWindow::slotAddTab() +{ + KonqView* newView = m_pViewManager->addTab(TQString("text/html"), // this is what about:blank will use anyway + TQString::null, + false, + KonqSettings::openAfterCurrentPage()); + if (newView == 0L) return; + openURL( newView, KURL("about:blank"),TQString::null); + m_pViewManager->showTab( newView ); + focusLocationBar(); + m_pWorkingTab = 0L; +} + +void KonqMainWindow::slotDuplicateTab() +{ + m_pViewManager->duplicateTab( 0, KonqSettings::openAfterCurrentPage() ); +} + +void KonqMainWindow::slotDuplicateTabPopup() +{ + m_pViewManager->duplicateTab( m_pWorkingTab, KonqSettings::openAfterCurrentPage() ); +} + +void KonqMainWindow::slotBreakOffTab() +{ + if (m_currentView && m_currentView->part() && + (m_currentView->part()->metaObject()->findProperty("modified") != -1) ) { + TQVariant prop = m_currentView->part()->property("modified"); + if (prop.isValid() && prop.toBool()) + if ( KMessageBox::warningContinueCancel( this, + i18n("This tab contains changes that have not been submitted.\nDetaching the tab will discard these changes."), + i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"tab_breakoff"), "discardchangesdetach") != KMessageBox::Continue ) + return; + } + + m_pViewManager->breakOffTab(); + updateViewActions(); +} + +void KonqMainWindow::slotBreakOffTabPopup() +{ + KonqView* originalView = m_currentView; + KonqView *view = m_pWorkingTab->activeChildView(); + if (view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1) ) { + TQVariant prop = view->part()->property("modified"); + if (prop.isValid() && prop.toBool()) { + m_pViewManager->showTab( view ); + if ( KMessageBox::warningContinueCancel( this, + i18n("This tab contains changes that have not been submitted.\nDetaching the tab will discard these changes."), + i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"tab_breakoff"), "discardchangesdetach") != KMessageBox::Continue ) + { + m_pViewManager->showTab( originalView ); + return; + } + } + } + m_pViewManager->showTab( originalView ); + + //Can't do this safely here as the tabbar may disappear and we're + //hanging off here. + TQTimer::singleShot(0, this, TQT_SLOT( slotBreakOffTabPopupDelayed() ) ); +} + +void KonqMainWindow::slotBreakOffTabPopupDelayed() +{ + m_pViewManager->breakOffTab( m_pWorkingTab ); + updateViewActions(); +} + +void KonqMainWindow::slotPopupNewWindow() +{ + kdDebug(1202) << "KonqMainWindow::slotPopupNewWindow()" << endl; + + KFileItemListIterator it ( popupItems ); + for ( ; it.current(); ++it ) + { + KonqMisc::createNewWindow( (*it)->url(), popupUrlArgs ); + } +} + +void KonqMainWindow::slotPopupThisWindow() +{ + kdDebug(1202) << "KonqMainWindow::slotPopupThisWindow()" << endl; + + openURL( 0L, popupItems.getFirst()->url() ); +} + +void KonqMainWindow::slotPopupNewTabAtFront() +{ + TDEConfig *config = TDEGlobal::config(); + TDEConfigGroupSaver cs( config, TQString::fromLatin1("FMSettings") ); + bool openAfterCurrentPage = config->readBoolEntry( "OpenAfterCurrentPage", false ); + popupNewTab(true, openAfterCurrentPage); +} + +void KonqMainWindow::slotPopupNewTab() +{ + bool openAfterCurrentPage = KonqSettings::openAfterCurrentPage(); + bool newTabsInFront = KonqSettings::newTabsInFront(); + + if (TDEApplication::keyboardMouseState() & TQt::ShiftButton) + newTabsInFront = !newTabsInFront; + + popupNewTab(newTabsInFront, openAfterCurrentPage); +} + +void KonqMainWindow::slotPopupNewTabRight() +{ + bool newTabsInFront = KonqSettings::newTabsInFront(); + + if (TDEApplication::keyboardMouseState() & ShiftButton) + newTabsInFront = !newTabsInFront; + + popupNewTab(newTabsInFront, false); +} + +void KonqMainWindow::popupNewTab(bool infront, bool openAfterCurrentPage) +{ + kdDebug(1202) << "KonqMainWindow::popupNewTab()" << endl; + + KFileItemListIterator it ( popupItems ); + KonqOpenURLRequest req; + req.newTab = true; + req.newTabInFront = false; + req.openAfterCurrentPage = openAfterCurrentPage; + req.args = popupUrlArgs; + + for ( ; it.current(); ++it ) + { + if ( infront && it.atLast() ) + { + req.newTabInFront = true; + } + openURL( 0L, (*it)->url(), TQString::null, req ); + } +} + +void KonqMainWindow::openMultiURL( KURL::List url ) +{ + KURL::List::ConstIterator it = url.begin(); + KURL::List::ConstIterator end = url.end(); + for (; it != end; ++it ) + { + KonqView* newView = m_pViewManager->addTab(); + Q_ASSERT( newView ); + if (newView == 0L) continue; + openURL( newView, *it,TQString::null); + m_pViewManager->showTab( newView ); + focusLocationBar(); + m_pWorkingTab = 0L; + } +} + +void KonqMainWindow::slotRemoveView() +{ + if (m_currentView && m_currentView->part() && + (m_currentView->part()->metaObject()->findProperty("modified") != -1) ) { + TQVariant prop = m_currentView->part()->property("modified"); + if (prop.isValid() && prop.toBool()) + if ( KMessageBox::warningContinueCancel( this, + i18n("This view contains changes that have not been submitted.\nClosing the view will discard these changes."), + i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"view_remove"), "discardchangesclose") != KMessageBox::Continue ) + return; + } + + // takes care of choosing the new active view + m_pViewManager->removeView( m_currentView ); +} + +void KonqMainWindow::slotRemoveTab() +{ + if (m_currentView && m_currentView->part() && + (m_currentView->part()->metaObject()->findProperty("modified") != -1) ) { + TQVariant prop = m_currentView->part()->property("modified"); + if (prop.isValid() && prop.toBool()) + if ( KMessageBox::warningContinueCancel( this, + i18n("This tab contains changes that have not been submitted.\nClosing the tab will discard these changes."), + i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"tab_remove"), "discardchangesclose") != KMessageBox::Continue ) + return; + } + + m_pViewManager->removeTab(); +} + +void KonqMainWindow::slotRemoveTabPopup() +{ + KonqView *originalView = m_currentView; + KonqView *view = m_pWorkingTab->activeChildView(); + if (view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1) ) { + TQVariant prop = view->part()->property("modified"); + if (prop.isValid() && prop.toBool()) { + m_pViewManager->showTab( view ); + if ( KMessageBox::warningContinueCancel( this, + i18n("This tab contains changes that have not been submitted.\nClosing the tab will discard these changes."), + i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"tab_remove"), "discardchangesclose") != KMessageBox::Continue ) + { + m_pViewManager->showTab( originalView ); + return; + } + } + m_pViewManager->showTab( originalView ); + } + + //Can't do immediately - may kill the tabbar, and we're in an event path down from it + TQTimer::singleShot( 0, this, TQT_SLOT( slotRemoveTabPopupDelayed() ) ); +} + +void KonqMainWindow::slotRemoveTabPopupDelayed() +{ + m_pViewManager->removeTab( m_pWorkingTab ); +} + +void KonqMainWindow::slotRemoveOtherTabsPopup() +{ + if ( KMessageBox::warningContinueCancel( this, + i18n("Do you really want to close all other tabs?"), + i18n("Close Other Tabs Confirmation"), KGuiItem(i18n("Close &Other Tabs"),"tab_remove_other"), + "CloseOtherTabConfirm") != KMessageBox::Continue ) + return; + + KonqView *originalView = m_currentView; + MapViews::ConstIterator it = m_mapViews.begin(); + MapViews::ConstIterator end = m_mapViews.end(); + for (; it != end; ++it ) { + KonqView *view = it.data(); + if ( view != originalView && view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1) ) { + TQVariant prop = view->part()->property("modified"); + if (prop.isValid() && prop.toBool()) { + m_pViewManager->showTab( view ); + if ( KMessageBox::warningContinueCancel( this, + i18n("This tab contains changes that have not been submitted.\nClosing other tabs will discard these changes."), + i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"tab_remove"), "discardchangescloseother") != KMessageBox::Continue ) + { + m_pViewManager->showTab( originalView ); + return; + } + } + } + } + m_pViewManager->showTab( originalView ); + + //Can't do immediately - kills the tabbar, and we're in an event path down from it + TQTimer::singleShot( 0, this, TQT_SLOT( slotRemoveOtherTabsPopupDelayed() ) ); +} + +void KonqMainWindow::slotRemoveOtherTabsPopupDelayed() +{ + m_pViewManager->removeOtherTabs( m_pWorkingTab ); + updateViewActions(); +} + +void KonqMainWindow::slotReloadAllTabs() +{ + KonqView *originalView = m_currentView; + MapViews::ConstIterator it = m_mapViews.begin(); + MapViews::ConstIterator end = m_mapViews.end(); + for (; it != end; ++it ) { + KonqView *view = it.data(); + if (view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1) ) { + TQVariant prop = view->part()->property("modified"); + if (prop.isValid() && prop.toBool()) { + m_pViewManager->showTab( view ); + if ( KMessageBox::warningContinueCancel( this, + i18n("This tab contains changes that have not been submitted.\nReloading all tabs will discard these changes."), + i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"reload"), "discardchangesreload") != KMessageBox::Continue ) + { + m_pViewManager->showTab( originalView ); + return; + } + } + } + } + m_pViewManager->showTab( originalView ); + + m_pViewManager->reloadAllTabs(); + updateViewActions(); +} + + +void KonqMainWindow::slotActivateNextTab() +{ + m_pViewManager->activateNextTab(); +} + +void KonqMainWindow::slotActivatePrevTab() +{ + m_pViewManager->activatePrevTab(); +} + +void KonqMainWindow::slotActivateTab() +{ + m_pViewManager->activateTab( TQString( TQT_TQOBJECT_CONST(sender())->name() ).right( 2 ).toInt() -1 ); +} + +void KonqMainWindow::slotDumpDebugInfo() +{ +#ifndef NDEBUG + dumpViewList(); + m_pViewManager->printFullHierarchy( 0L ); +#endif +} + +void KonqMainWindow::slotSaveViewPropertiesLocally() +{ + m_bSaveViewPropertiesLocally = !m_bSaveViewPropertiesLocally; + // And this is a main-view setting, so save it + KonqSettings::setSaveViewPropertiesLocally( m_bSaveViewPropertiesLocally ); + KonqSettings::writeConfig(); + // Now tell the views + MapViews::ConstIterator it = m_mapViews.begin(); + MapViews::ConstIterator end = m_mapViews.end(); + for (; it != end; ++it ) + (*it)->callExtensionBoolMethod( "setSaveViewPropertiesLocally(bool)", m_bSaveViewPropertiesLocally ); +} + +void KonqMainWindow::slotRemoveLocalProperties() +{ + assert( m_currentView ); + KURL u ( m_currentView->url() ); + u.addPath(".directory"); + if ( u.isLocalFile() ) + { + TQFile f( u.path() ); + if ( f.open(IO_ReadWrite) ) + { + f.close(); + KSimpleConfig config( u.path() ); + config.deleteGroup( "URL properties" ); // Bye bye + config.sync(); + // TODO: Notify the view... + // Or the hard way: (and hoping it doesn't cache the values!) + slotReload(); + } else + { + Q_ASSERT( TQFile::exists(u.path()) ); // The action shouldn't be enabled, otherwise. + KMessageBox::sorry( this, i18n("No permissions to write to %1").arg(u.path()) ); + } + } +} + +bool KonqMainWindow::askForTarget(const TQString& text, KURL& url) +{ + const KURL initialUrl = (viewCount()==2) ? otherView(m_currentView)->url() : m_currentView->url(); + TQString label = text.arg( m_currentView->url().pathOrURL() ); + KURLRequesterDlg dlg(initialUrl.pathOrURL(), label, this, "urlrequester", true); + dlg.setCaption(i18n("Enter Target")); + dlg.urlRequester()->setMode( KFile::File | KFile::ExistingOnly | KFile::Directory ); + if (dlg.exec()) + { + url = dlg.selectedURL(); + if ( url.isValid() ) + return true; + else + { + KMessageBox::error( this, i18n("%1 is not valid").arg(url.url())); + return false; + } + } + return false; +} + +void KonqMainWindow::slotRequesterClicked( KURLRequester *req ) +{ + req->fileDialog()->setMode(KFile::Directory|KFile::ExistingOnly); +} + +void KonqMainWindow::slotCopyFiles() +{ + //kdDebug(1202) << "KonqMainWindow::slotCopyFiles()" << endl; + KURL dest; + if (!askForTarget(i18n("Copy selected files from %1 to:"),dest)) + return; + + KonqOperations::copy(this,KonqOperations::COPY,currentURLs(),dest); +} + +void KonqMainWindow::slotMoveFiles() +{ + //kdDebug(1202) << "KonqMainWindow::slotMoveFiles()" << endl; + KURL dest; + if (!askForTarget(i18n("Move selected files from %1 to:"),dest)) + return; + + KonqOperations::copy(this,KonqOperations::MOVE,currentURLs(),dest); +} + +void KonqMainWindow::slotNewDir() +{ + Q_ASSERT( m_currentView ); + if ( m_currentView ) + KonqOperations::newDir(this, m_currentView->url()); +} + +KURL::List KonqMainWindow::currentURLs() const +{ + KURL::List urls; + if ( m_currentView ) + { + urls.append( m_currentView->url() ); + if ( m_currentView->part()->inherits("KonqDirPart") ) + { + KFileItemList tmpList= static_cast(m_currentView->part())->selectedFileItems(); + KFileItem *item=tmpList.first(); + if (item) // Return list of selected items only if we have a selection + { + urls.clear(); + for (; item!=0; item=tmpList.next()) + urls.append(item->url()); + } + } + } + return urls; +} + +// Only valid if there are one or two views +KonqView * KonqMainWindow::otherView( KonqView * view ) const +{ + assert( viewCount() <= 2 ); + MapViews::ConstIterator it = m_mapViews.begin(); + if ( (*it) == view ) + ++it; + if ( it != m_mapViews.end() ) + return (*it); + return 0L; +} + +void KonqMainWindow::slotSaveViewProfile() +{ +#if 0 + if ( m_pViewManager->currentProfile().isEmpty() ) + { + // The action should be disabled........... + kdWarning(1202) << "No known profile. Use the Save Profile dialog box" << endl; + } else { + + m_pViewManager->saveViewProfile( m_pViewManager->currentProfile(), + m_pViewManager->currentProfileText(), + false /* URLs */, true /* size */ ); + + } +#endif + m_pViewManager->showProfileDlg( m_pViewManager->currentProfile() ); +} + +void KonqMainWindow::slotUpAboutToShow() +{ + TQPopupMenu *popup = m_paUp->popupMenu(); + + popup->clear(); + + uint i = 0; + + // Use the location bar URL, because in case we display a index.html + // we want to go up from the dir, not from the index.html + KURL u( m_currentView->locationBarURL() ); + u = u.upURL(); + while ( u.hasPath() ) + { + popup->insertItem( KonqPixmapProvider::self()->pixmapFor( u.url() ), + u.pathOrURL() ); + + if ( u.path() == "/" ) + break; + + if ( ++i > 10 ) + break; + + u = u.upURL(); + } +} + +void KonqMainWindow::slotUp(TDEAction::ActivationReason, TQt::ButtonState state) +{ + m_goState = state; + TQTimer::singleShot( 0, this, TQT_SLOT( slotUpDelayed() ) ); +} + +void KonqMainWindow::slotUp() +{ + m_goState = Qt::LeftButton; + TQTimer::singleShot( 0, this, TQT_SLOT( slotUpDelayed() ) ); +} + +void KonqMainWindow::slotUpDelayed() +{ + KonqOpenURLRequest req; + req.newTab = true; + + req.openAfterCurrentPage = KonqSettings::openAfterCurrentPage(); + req.newTabInFront = KonqSettings::newTabsInFront(); + + if (m_goState & TQt::ShiftButton) + req.newTabInFront = !req.newTabInFront; + + const TQString& url = m_currentView->upURL().url(); + if(m_goState & TQt::ControlButton) + openFilteredURL(url, req ); + else if(m_goState & Qt::MidButton) + { + if(KonqSettings::mmbOpensTab()) + openFilteredURL( url, req); + else + KonqMisc::createNewWindow( url ); + } + else + openFilteredURL( url, false ); + m_goState = Qt::LeftButton; +} + +void KonqMainWindow::slotUpActivated( int id ) +{ + KURL u( m_currentView->locationBarURL() ); + kdDebug(1202) << "slotUpActivated. Start URL is " << u << endl; + for ( int i = 0 ; i < m_paUp->popupMenu()->indexOf( id ) + 1 ; i ++ ) + u = u.upURL(); + openURL( 0L, u ); +} + +void KonqMainWindow::slotGoMenuAboutToShow() +{ + kdDebug(1202) << "KonqMainWindow::slotGoMenuAboutToShow" << endl; + if ( m_paHistory && m_currentView ) // (maybe this is before initialisation) + m_paHistory->fillGoMenu( m_currentView->history() ); +} + +void KonqMainWindow::slotGoHistoryActivated( int steps ) +{ + slotGoHistoryActivated( steps, Qt::LeftButton ); +} + +void KonqMainWindow::slotGoHistoryActivated( int steps, TQt::ButtonState state ) +{ + kdDebug() <<"slotGoHistoryActivated( "<addTabFromHistory( m_goBuffer, openAfterCurrentPage ); + if (newView && inFront) + m_pViewManager->showTab( newView ); + } + else if(m_goState & Qt::MidButton) + { + if(mmbOpensTab) + { + KonqView * newView = m_pViewManager->addTabFromHistory( m_goBuffer, openAfterCurrentPage ); + if (newView && inFront) + m_pViewManager->showTab( newView ); + } + else + KonqMisc::newWindowFromHistory(this->currentView(), m_goBuffer); + } + else + { + m_currentView->go( m_goBuffer ); + makeViewsFollow(m_currentView->url(), KParts::URLArgs(),m_currentView->serviceType(),m_currentView); + } + + m_goBuffer = 0; + m_goState = Qt::LeftButton; +} + + +void KonqMainWindow::slotBackAboutToShow() +{ + m_paBack->popupMenu()->clear(); + if ( m_currentView ) + KonqBidiHistoryAction::fillHistoryPopup( m_currentView->history(), m_paBack->popupMenu(), true, false ); +} + +void KonqMainWindow::slotBack() +{ + slotGoHistoryActivated(-1); +} + +void KonqMainWindow::slotBack(TDEAction::ActivationReason, TQt::ButtonState state) +{ + slotGoHistoryActivated( -1, state ); +} + +void KonqMainWindow::slotBackActivated( int id ) +{ + slotGoHistoryActivated( -(m_paBack->popupMenu()->indexOf( id ) + 1), m_paBack->popupMenu()->state()); +} + +void KonqMainWindow::slotForwardAboutToShow() +{ + m_paForward->popupMenu()->clear(); + if ( m_currentView ) + KonqBidiHistoryAction::fillHistoryPopup( m_currentView->history(), m_paForward->popupMenu(), false, true ); +} + +void KonqMainWindow::slotForward() +{ + slotGoHistoryActivated( 1 ); +} + +void KonqMainWindow::slotForward(TDEAction::ActivationReason, TQt::ButtonState state) +{ + slotGoHistoryActivated( 1, state ); +} + +void KonqMainWindow::slotForwardActivated( int id ) +{ + slotGoHistoryActivated( m_paForward->popupMenu()->indexOf( id ) + 1, m_paForward->popupMenu()->state() ); +} + +void KonqMainWindow::initCombo() +{ + m_combo = new KonqCombo( 0L, "history combo"); + + m_combo->init( s_pCompletion ); + + connect( m_combo, TQT_SIGNAL(activated(const TQString&,int)), + this, TQT_SLOT(slotURLEntered(const TQString&,int)) ); + connect( m_combo, TQT_SIGNAL(showPageSecurity()), + this, TQT_SLOT(showPageSecurity()) ); + + m_pURLCompletion = new KURLCompletion(); + m_pURLCompletion->setCompletionMode( s_pCompletion->completionMode() ); + + // This only turns completion off. ~ is still there in the result + // We do want completion of user names, right? + //m_pURLCompletion->setReplaceHome( false ); // Leave ~ alone! Will be taken care of by filters!! + + connect( m_combo, TQT_SIGNAL(completionModeChanged(TDEGlobalSettings::Completion)), + TQT_SLOT( slotCompletionModeChanged( TDEGlobalSettings::Completion ))); + connect( m_combo, TQT_SIGNAL( completion( const TQString& )), + TQT_SLOT( slotMakeCompletion( const TQString& ))); + connect( m_combo, TQT_SIGNAL( substringCompletion( const TQString& )), + TQT_SLOT( slotSubstringcompletion( const TQString& ))); + connect( m_combo, TQT_SIGNAL( textRotation( TDECompletionBase::KeyBindingType) ), + TQT_SLOT( slotRotation( TDECompletionBase::KeyBindingType ))); + connect( m_combo, TQT_SIGNAL( cleared() ), + TQT_SLOT ( slotClearHistory() ) ); + connect( m_pURLCompletion, TQT_SIGNAL( match(const TQString&) ), + TQT_SLOT( slotMatch(const TQString&) )); + + m_combo->lineEdit()->installEventFilter(this); + + static bool bookmarkCompletionInitialized = false; + if ( !bookmarkCompletionInitialized ) + { + bookmarkCompletionInitialized = true; + DelayedInitializer *initializer = new DelayedInitializer( TQEvent::KeyPress, TQT_TQOBJECT(m_combo->lineEdit()) ); + connect( initializer, TQT_SIGNAL( initialize() ), this, TQT_SLOT( bookmarksIntoCompletion() ) ); + } +} + +void KonqMainWindow::bookmarksIntoCompletion() +{ + // add all bookmarks to the completion list for easy access + bookmarksIntoCompletion( KonqBookmarkManager::self()->root() ); +} + +// the user changed the completion mode in the combo +void KonqMainWindow::slotCompletionModeChanged( TDEGlobalSettings::Completion m ) +{ + s_pCompletion->setCompletionMode( m ); + + KonqSettings::setSettingsCompletionMode( (int)m_combo->completionMode() ); + KonqSettings::writeConfig(); + + // tell the other windows too (only this instance currently) + KonqMainWindow *window = s_lstViews->first(); + while ( window ) { + if ( window->m_combo ) { + window->m_combo->setCompletionMode( m ); + window->m_pURLCompletion->setCompletionMode( m ); + } + window = s_lstViews->next(); + } +} + +// at first, try to find a completion in the current view, then use the global +// completion (history) +void KonqMainWindow::slotMakeCompletion( const TQString& text ) +{ + if( m_pURLCompletion ) + { + m_urlCompletionStarted = true; // flag for slotMatch() + + // kdDebug(1202) << "Local Completion object found!" << endl; + TQString completion = m_pURLCompletion->makeCompletion( text ); + m_currentDir = TQString::null; + + if ( completion.isNull() && !m_pURLCompletion->isRunning() ) + { + // No match() signal will come from m_pURLCompletion + // ask the global one + // tell the static completion object about the current completion mode + completion = s_pCompletion->makeCompletion( text ); + + // some special handling necessary for CompletionPopup + if ( m_combo->completionMode() == TDEGlobalSettings::CompletionPopup || + m_combo->completionMode() == TDEGlobalSettings::CompletionPopupAuto ) + m_combo->setCompletedItems( historyPopupCompletionItems( text ) ); + + else if ( !completion.isNull() ) + m_combo->setCompletedText( completion ); + } + else + { + // To be continued in slotMatch()... + if( !m_pURLCompletion->dir().isEmpty() ) + m_currentDir = m_pURLCompletion->dir(); + } + } + // kdDebug(1202) << "Current dir: " << m_currentDir << " Current text: " << text << endl; +} + +void KonqMainWindow::slotSubstringcompletion( const TQString& text ) +{ + bool filesFirst = currentURL().startsWith( "/" ) || + currentURL().startsWith( "file:/" ); + TQStringList items; + if ( filesFirst && m_pURLCompletion ) + items = m_pURLCompletion->substringCompletion( text ); + + items += s_pCompletion->substringCompletion( text ); + if ( !filesFirst && m_pURLCompletion ) + items += m_pURLCompletion->substringCompletion( text ); + + m_combo->setCompletedItems( items ); +} + +void KonqMainWindow::slotRotation( TDECompletionBase::KeyBindingType type ) +{ + // Tell slotMatch() to do nothing + m_urlCompletionStarted = false; + + bool prev = (type == TDECompletionBase::PrevCompletionMatch); + if ( prev || type == TDECompletionBase::NextCompletionMatch ) { + TQString completion = prev ? m_pURLCompletion->previousMatch() : + m_pURLCompletion->nextMatch(); + + if( completion.isNull() ) { // try the history TDECompletion object + completion = prev ? s_pCompletion->previousMatch() : + s_pCompletion->nextMatch(); + } + if ( completion.isEmpty() || completion == m_combo->currentText() ) + return; + + m_combo->setCompletedText( completion ); + } +} + +// Handle match() from m_pURLCompletion +void KonqMainWindow::slotMatch( const TQString &match ) +{ + if ( match.isEmpty() ) // this case is handled directly + return; + + // Check flag to avoid match() raised by rotation + if ( m_urlCompletionStarted ) { + m_urlCompletionStarted = false; + + // some special handling necessary for CompletionPopup + if ( m_combo->completionMode() == TDEGlobalSettings::CompletionPopup || + m_combo->completionMode() == TDEGlobalSettings::CompletionPopupAuto ) { + TQStringList items = m_pURLCompletion->allMatches(); + items += historyPopupCompletionItems( m_combo->currentText() ); + // items.sort(); // should we? + m_combo->setCompletedItems( items ); + } + else if ( !match.isNull() ) + m_combo->setCompletedText( match ); + } +} + +void KonqMainWindow::slotCtrlTabPressed() +{ + KonqView * view = m_pViewManager->chooseNextView( m_currentView ); + if ( view ) + m_pViewManager->setActivePart( view->part() ); +} + +void KonqMainWindow::slotClearHistory() +{ + KonqHistoryManager::kself()->emitClear(); +} + +void KonqMainWindow::slotClearComboHistory() +{ + if (m_combo && m_combo->count()) + m_combo->clearHistory(); +} + +bool KonqMainWindow::eventFilter(TQObject*obj,TQEvent *ev) +{ + if ( ( ev->type()==TQEvent::FocusIn || ev->type()==TQEvent::FocusOut ) && + m_combo && TQT_BASE_OBJECT(m_combo->lineEdit()) == TQT_BASE_OBJECT(obj) ) + { + //kdDebug(1202) << "KonqMainWindow::eventFilter " << obj << " " << obj->className() << " " << obj->name() << endl; + + TQFocusEvent * focusEv = TQT_TQFOCUSEVENT(ev); + if (focusEv->reason() == TQFocusEvent::Popup) + { + return KParts::MainWindow::eventFilter( obj, ev ); + } + + KParts::BrowserExtension * ext = 0; + if ( m_currentView ) + ext = m_currentView->browserExtension(); + TQStrList slotNames; + if (ext) + slotNames = ext->metaObject()->slotNames(); + + //for ( char * s = slotNames.first() ; s ; s = slotNames.next() ) + //{ + // kdDebug(1202) << "slotNames=" << s << endl; + //} + + + if (ev->type()==TQEvent::FocusIn) + { + //kdDebug(1202) << "ComboBox got the focus..." << endl; + if (m_bLocationBarConnected) + { + //kdDebug(1202) << "Was already connected..." << endl; + return KParts::MainWindow::eventFilter( obj, ev ); + } + m_bLocationBarConnected = true; + + // Workaround for Qt issue: usually, TQLineEdit reacts on Ctrl-D, + // but the duplicate_window action also has Ctrl-D as accel and + // prevents the lineedit from getting this event. IMHO the accel + // should be disabled in favor of the focus-widget. + TDEAction *duplicate = actionCollection()->action("duplicate_window"); + if ( duplicate->shortcut() == TQKeySequence(CTRL+Key_D) ) + duplicate->setEnabled( false ); + + if (slotNames.contains("cut()")) + disconnect( m_paCut, TQT_SIGNAL( activated() ), ext, TQT_SLOT( cut() ) ); + if (slotNames.contains("copy()")) + disconnect( m_paCopy, TQT_SIGNAL( activated() ), ext, TQT_SLOT( copy() ) ); + if (slotNames.contains("paste()")) + disconnect( m_paPaste, TQT_SIGNAL( activated() ), ext, TQT_SLOT( paste() ) ); + if (slotNames.contains("del()")) + disconnect( m_paDelete, TQT_SIGNAL( activated() ), ext, TQT_SLOT( del() ) ); + disconnect( m_paTrash, TQT_SIGNAL( activated( TDEAction::ActivationReason, TQt::ButtonState ) ), + this, TQT_SLOT( slotTrashActivated( TDEAction::ActivationReason, TQt::ButtonState ) ) ); + + connect( m_paCut, TQT_SIGNAL( activated() ), m_combo->lineEdit(), TQT_SLOT( cut() ) ); + connect( m_paCopy, TQT_SIGNAL( activated() ), m_combo->lineEdit(), TQT_SLOT( copy() ) ); + connect( m_paPaste, TQT_SIGNAL( activated() ), m_combo->lineEdit(), TQT_SLOT( paste() ) ); + connect( TQApplication::clipboard(), TQT_SIGNAL(dataChanged()), this, TQT_SLOT(slotClipboardDataChanged()) ); + connect( m_combo->lineEdit(), TQT_SIGNAL(textChanged(const TQString &)), this, TQT_SLOT(slotCheckComboSelection()) ); + connect( m_combo->lineEdit(), TQT_SIGNAL(selectionChanged()), this, TQT_SLOT(slotCheckComboSelection()) ); + + m_paTrash->setEnabled(false); + m_paDelete->setEnabled(false); + + slotClipboardDataChanged(); + + } + else if ( ev->type()==TQEvent::FocusOut) + { + //kdDebug(1202) << "ComboBox lost focus..." << endl; + if (!m_bLocationBarConnected) + { + //kdDebug(1202) << "Was already disconnected..." << endl; + return KParts::MainWindow::eventFilter( obj, ev ); + } + m_bLocationBarConnected = false; + + // see above in FocusIn for explanation + // we use new_window as reference, as it's always in the same state + // as duplicate_window + TDEAction *duplicate = actionCollection()->action("duplicate_window"); + if ( duplicate->shortcut() == TQKeySequence(CTRL+Key_D) ) + duplicate->setEnabled( actionCollection()->action("new_window")->isEnabled() ); + + if (slotNames.contains("cut()")) + connect( m_paCut, TQT_SIGNAL( activated() ), ext, TQT_SLOT( cut() ) ); + if (slotNames.contains("copy()")) + connect( m_paCopy, TQT_SIGNAL( activated() ), ext, TQT_SLOT( copy() ) ); + if (slotNames.contains("paste()")) + connect( m_paPaste, TQT_SIGNAL( activated() ), ext, TQT_SLOT( paste() ) ); + if (slotNames.contains("del()")) + connect( m_paDelete, TQT_SIGNAL( activated() ), ext, TQT_SLOT( del() ) ); + connect( m_paTrash, TQT_SIGNAL( activated( TDEAction::ActivationReason, TQt::ButtonState ) ), + this, TQT_SLOT( slotTrashActivated( TDEAction::ActivationReason, TQt::ButtonState ) ) ); + + disconnect( m_paCut, TQT_SIGNAL( activated() ), m_combo->lineEdit(), TQT_SLOT( cut() ) ); + disconnect( m_paCopy, TQT_SIGNAL( activated() ), m_combo->lineEdit(), TQT_SLOT( copy() ) ); + disconnect( m_paPaste, TQT_SIGNAL( activated() ), m_combo->lineEdit(), TQT_SLOT( paste() ) ); + disconnect( TQApplication::clipboard(), TQT_SIGNAL(dataChanged()), this, TQT_SLOT(slotClipboardDataChanged()) ); + disconnect( m_combo->lineEdit(), TQT_SIGNAL(textChanged(const TQString &)), this, TQT_SLOT(slotCheckComboSelection()) ); + disconnect( m_combo->lineEdit(), TQT_SIGNAL(selectionChanged()), this, TQT_SLOT(slotCheckComboSelection()) ); + + if ( ext ) + { + m_paCut->setEnabled( ext->isActionEnabled( "cut" ) ); + m_paCopy->setEnabled( ext->isActionEnabled( "copy" ) ); + m_paPaste->setEnabled( ext->isActionEnabled( "paste" ) ); + m_paDelete->setEnabled( ext->isActionEnabled( "delete" ) ); + m_paTrash->setEnabled( ext->isActionEnabled( "trash" ) ); + } + else + { + m_paCut->setEnabled( false ); + m_paCopy->setEnabled( false ); + m_paPaste->setEnabled( false ); + m_paDelete->setEnabled( false ); + m_paTrash->setEnabled( false ); + } + } + } + return KParts::MainWindow::eventFilter( obj, ev ); +} + +void KonqMainWindow::slotClipboardDataChanged() +{ + //kdDebug(1202) << "KonqMainWindow::slotClipboardDataChanged()" << endl; + TQMimeSource *data = TQApplication::clipboard()->data(); + m_paPaste->setEnabled( data->provides( "text/plain" ) ); + slotCheckComboSelection(); +} + +void KonqMainWindow::slotCheckComboSelection() +{ + //kdDebug(1202) << "m_combo->lineEdit()->hasMarkedText() : " << hasSelection << endl; + bool hasSelection = m_combo->lineEdit()->hasSelectedText(); + m_paCopy->setEnabled( hasSelection ); + m_paCut->setEnabled( hasSelection ); +} + +void KonqMainWindow::slotClearLocationBar( TDEAction::ActivationReason, TQt::ButtonState state ) +{ + kdDebug(1202) << "slotClearLocationBar" << endl; + slotStop(); + m_combo->clearTemporary(); + focusLocationBar(); + if ( state & Qt::MidButton ) + m_combo->setURL( TQApplication::clipboard()->text( TQClipboard::Selection ) ); +} + +void KonqMainWindow::slotForceSaveMainWindowSettings() +{ +// kdDebug(1202)<<"slotForceSaveMainWindowSettings()"<sync(); + } +} + +void KonqMainWindow::slotShowMenuBar() +{ + if (menuBar()->isVisible()) + menuBar()->hide(); + else + menuBar()->show(); + slotForceSaveMainWindowSettings(); +} + +void KonqMainWindow::slotUpdateFullScreen( bool set ) +{ + if( set ) + { + showFullScreen(); + // Create toolbar button for exiting from full-screen mode + // ...but only if there isn't one already... + + bool haveFullScreenButton = false; + + //Walk over the toolbars and check whether there is a show fullscreen button in any of them + TQPtrListIterator barIt = toolBarIterator(); + for (; barIt.current(); ++barIt ) + { + //Are we plugged here, in a visible toolbar? + if (barIt.current()->isVisible() && + action( "fullscreen" )->isPlugged(barIt.current())) + { + haveFullScreenButton = true; + break; + } + } + + if (!haveFullScreenButton) + { + TQPtrList lst; + lst.append( m_ptaFullScreen ); + plugActionList( "fullscreen", lst ); + } + + m_prevMenuBarVisible = menuBar()->isVisible(); + menuBar()->hide(); + m_paShowMenuBar->setChecked( false ); + + // Qt bug, the flags are lost. They know about it. + // happens only with the hackish non-_NET_WM_STATE_FULLSCREEN way + setWFlags( WDestructiveClose ); + // Qt bug (see below) + setAcceptDrops( FALSE ); + topData()->dnd = 0; + setAcceptDrops( TRUE ); + } + else + { +#if TQT_VERSION >= 0x030300 + setWindowState( windowState() & ~WindowFullScreen ); +#else + if( isMaximized()) + { + showNormal(); + showMaximized(); // showNormal() would reset maximize state + } + else + showNormal(); +#endif + unplugActionList( "fullscreen" ); + + if (m_prevMenuBarVisible) + { + menuBar()->show(); + m_paShowMenuBar->setChecked( true ); + } + + // Qt bug, the flags aren't restored. They know about it. + setWFlags( WType_TopLevel | WDestructiveClose ); + // Other Qt bug + setAcceptDrops( FALSE ); + topData()->dnd = 0; + setAcceptDrops( TRUE ); + } +} + +void KonqMainWindow::setLocationBarURL( const KURL &url ) +{ + setLocationBarURL( url.pathOrURL() ); +} + +void KonqMainWindow::setLocationBarURL( const TQString &url ) +{ + kdDebug(1202) << "KonqMainWindow::setLocationBarURL: url = " << url << endl; + + m_combo->setURL( url ); + + setIcon( KonqPixmapProvider::self()->pixmapFor( url ) ); +} + +void KonqMainWindow::setPageSecurity( PageSecurity pageSecurity ) +{ + m_combo->setPageSecurity( pageSecurity ); +} + +void KonqMainWindow::showPageSecurity() +{ + if ( m_currentView && m_currentView->part() ) { + TDEAction *act = m_currentView->part()->action( "security" ); + if ( act ) + act->activate(); + } +} + +// called via DCOP from KonquerorIface +void KonqMainWindow::comboAction( int action, const TQString& url, const TQCString& objId ) +{ + if (!s_lstViews) // this happens in "konqueror --silent" + return; + + KonqCombo *combo = 0L; + KonqMainWindow *window = s_lstViews->first(); + while ( window ) { + if ( window->m_combo ) { + combo = window->m_combo; + + switch ( action ) { + case ComboAdd: + combo->insertPermanent( url ); + break; + case ComboClear: + combo->clearHistory(); + break; + case ComboRemove: + combo->removeURL( url ); + break; + default: + break; + } + } + window = s_lstViews->next(); + } + + // only one instance should save... + if ( combo && objId == kapp->dcopClient()->defaultObject() ) + combo->saveItems(); +} + +TQString KonqMainWindow::locationBarURL() const +{ + return m_combo->currentText(); +} + +void KonqMainWindow::focusLocationBar() +{ + if ( m_combo->isVisible() || !isVisible() ) + m_combo->setFocus(); +} + +void KonqMainWindow::startAnimation() +{ + //kdDebug(1202) << "KonqMainWindow::startAnimation" << endl; + m_paAnimatedLogo->start(); + m_paStop->setEnabled( true ); + toggleReloadStopButton( true ); +} + +void KonqMainWindow::stopAnimation() +{ + //kdDebug(1202) << "KonqMainWindow::stopAnimation" << endl; + m_paAnimatedLogo->stop(); + m_paStop->setEnabled( false ); + toggleReloadStopButton( false ); +} + +void KonqMainWindow::setUpEnabled( const KURL &url ) +{ + //kdDebug(1202) << "KonqMainWindow::setUpEnabled(" << url << ")" << endl; + //kdDebug(1202) << "hasPath=" << url.hasPath() << endl; + bool bHasUpURL = false; + + bHasUpURL = ( ( url.hasPath() && url.path() != "/" && ( url.path()[0]=='/' ) ) + || !url.query().isEmpty() /*e.g. lists.kde.org*/ ); + if ( !bHasUpURL ) + bHasUpURL = url.hasSubURL(); + + m_paUp->setEnabled( bHasUpURL ); +} + +void KonqMainWindow::initActions() +{ + actionCollection()->setHighlightingEnabled( true ); + connectActionCollection( actionCollection() ); + + + // Note about this method : don't call setEnabled() on any of the actions. + // They are all disabled then re-enabled with enableAllActions + // If any one needs to be initially disabled, put that code in enableAllActions + + // File menu + m_pMenuNew = new KNewMenu ( actionCollection(), this, "new_menu" ); + TQObject::connect( m_pMenuNew->popupMenu(), TQT_SIGNAL(aboutToShow()), + this, TQT_SLOT(slotFileNewAboutToShow()) ); + + (void) new TDEAction( i18n( "&Edit File Type..." ), 0, actionCollection(), "editMimeType" ); + (void) new TDEAction( i18n( "Properties" ), ALT+Key_Return, actionCollection(), "properties" ); + (void) new TDEAction( i18n( "New &Window" ), "window-new", TDEStdAccel::shortcut(TDEStdAccel::New), TQT_TQOBJECT(this), TQT_SLOT( slotNewWindow() ), actionCollection(), "new_window" ); + (void) new TDEAction( i18n( "&Duplicate Window" ), "window_duplicate", CTRL+Key_D, TQT_TQOBJECT(this), TQT_SLOT( slotDuplicateWindow() ), actionCollection(), "duplicate_window" ); + (void) new TDEAction( i18n( "Send &Link Address..." ), "mail_generic", 0, TQT_TQOBJECT(this), TQT_SLOT( slotSendURL() ), actionCollection(), "sendURL" ); + (void) new TDEAction( i18n( "S&end File..." ), "mail_generic", 0, TQT_TQOBJECT(this), TQT_SLOT( slotSendFile() ), actionCollection(), "sendPage" ); + if (kapp->authorize("shell_access")) + { + (void) new TDEAction( i18n( "Open &Terminal" ), "openterm", Key_F4, TQT_TQOBJECT(this), TQT_SLOT( slotOpenTerminal() ), actionCollection(), "open_terminal" ); + } + (void) new TDEAction( i18n( "&Open Location..." ), "document-open", TDEStdAccel::shortcut(TDEStdAccel::Open), TQT_TQOBJECT(this), TQT_SLOT( slotOpenLocation() ), actionCollection(), "open_location" ); + + m_paFindFiles = new TDEToggleAction( i18n( "&Find File..." ), "filefind", TDEStdAccel::shortcut(TDEStdAccel::Find), TQT_TQOBJECT(this), TQT_SLOT( slotToolFind() ), actionCollection(), "findfile" ); + + m_paPrint = KStdAction::print( 0, 0, actionCollection(), "print" ); + (void) KStdAction::quit( TQT_TQOBJECT(this), TQT_SLOT( close() ), actionCollection(), "quit" ); + + m_ptaUseHTML = new TDEToggleAction( i18n( "&Use index.html" ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotShowHTML() ), actionCollection(), "usehtml" ); + m_paLockView = new TDEToggleAction( i18n( "Lock to Current Location"), 0, TQT_TQOBJECT(this), TQT_SLOT( slotLockView() ), actionCollection(), "lock" ); + m_paLinkView = new TDEToggleAction( i18n( "Lin&k View"), 0, TQT_TQOBJECT(this), TQT_SLOT( slotLinkView() ), actionCollection(), "link" ); + + // Go menu + m_paUp = new TDEToolBarPopupAction( i18n( "&Up" ), "go-up", TDEStdAccel::shortcut(TDEStdAccel::Up), actionCollection(), "up" ); + connect( m_paUp, TQT_SIGNAL( activated( TDEAction::ActivationReason, TQt::ButtonState) ), TQT_TQOBJECT(this), + TQT_SLOT( slotUp(TDEAction::ActivationReason, TQt::ButtonState) ) ); + connect( m_paUp->popupMenu(), TQT_SIGNAL( aboutToShow() ), TQT_TQOBJECT(this), TQT_SLOT( slotUpAboutToShow() ) ); + connect( m_paUp->popupMenu(), TQT_SIGNAL( activated( int ) ), TQT_TQOBJECT(this), TQT_SLOT( slotUpActivated( int ) ) ); + + TQPair< KGuiItem, KGuiItem > backForward = KStdGuiItem::backAndForward(); + m_paBack = new TDEToolBarPopupAction( backForward.first, TDEStdAccel::shortcut(TDEStdAccel::Back), 0, "", actionCollection(), "back" ); + connect( m_paBack, TQT_SIGNAL( activated( TDEAction::ActivationReason, TQt::ButtonState) ), TQT_TQOBJECT(this), + TQT_SLOT( slotBack(TDEAction::ActivationReason, TQt::ButtonState) ) ); + connect( m_paBack->popupMenu(), TQT_SIGNAL( aboutToShow() ), TQT_TQOBJECT(this), TQT_SLOT( slotBackAboutToShow() ) ); + connect( m_paBack->popupMenu(), TQT_SIGNAL( activated( int ) ), TQT_TQOBJECT(this), TQT_SLOT( slotBackActivated( int ) ) ); + + m_paForward = new TDEToolBarPopupAction( backForward.second, TDEStdAccel::shortcut(TDEStdAccel::Forward), 0, "", actionCollection(), "forward" ); + connect( m_paForward, TQT_SIGNAL( activated( TDEAction::ActivationReason, TQt::ButtonState) ), TQT_TQOBJECT(this), + TQT_SLOT( slotForward(TDEAction::ActivationReason, TQt::ButtonState) ) ); + connect( m_paForward->popupMenu(), TQT_SIGNAL( aboutToShow() ), TQT_TQOBJECT(this), TQT_SLOT( slotForwardAboutToShow() ) ); + connect( m_paForward->popupMenu(), TQT_SIGNAL( activated( int ) ), TQT_TQOBJECT(this), TQT_SLOT( slotForwardActivated( int ) ) ); + + m_paHistory = new KonqBidiHistoryAction( i18n("History"), actionCollection(), "history" ); + connect( m_paHistory, TQT_SIGNAL( menuAboutToShow() ), TQT_TQOBJECT(this), TQT_SLOT( slotGoMenuAboutToShow() ) ); + connect( m_paHistory, TQT_SIGNAL( activated( int ) ), TQT_TQOBJECT(this), TQT_SLOT( slotGoHistoryActivated( int ) ) ); + + m_paHome = new TDEAction( i18n( "Home" ), "go-home", TDEStdAccel::shortcut(TDEStdAccel::Home), actionCollection(), "home" ); + connect( m_paHome, TQT_SIGNAL( activated( TDEAction::ActivationReason, TQt::ButtonState) ), TQT_TQOBJECT(this), + TQT_SLOT( slotHome(TDEAction::ActivationReason, TQt::ButtonState) ) ); + + (void) new TDEAction( i18n( "S&ystem" ), "computer", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoSystem() ), actionCollection(), "go_system" ); + (void) new TDEAction( i18n( "App&lications" ), "kmenu", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoApplications() ), actionCollection(), "go_applications" ); + (void) new TDEAction( i18n( "&Storage Media" ), "computer", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoMedia() ), actionCollection(), "go_media" ); + (void) new TDEAction( i18n( "&Network Folders" ), "network", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoNetworkFolders() ), actionCollection(), "go_network_folders" ); + (void) new TDEAction( i18n( "Sett&ings" ), "kcontrol", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoSettings() ), actionCollection(), "go_settings" ); + //(void) new TDEAction( i18n( "Sidebar Configuration" ), 0, this, TQT_SLOT( slotGoDirTree() ), actionCollection(), "go_dirtree" ); + (void) new TDEAction( i18n( "Trash" ), "trashcan_full", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoTrash() ), actionCollection(), "go_trash" ); + (void) new TDEAction( i18n( "Autostart" ), "launch", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoAutostart() ), actionCollection(), "go_autostart" ); + KonqMostOftenURLSAction *mostOften = new KonqMostOftenURLSAction( i18n("Most Often Visited"), actionCollection(), "go_most_often" ); + connect( mostOften, TQT_SIGNAL( activated( const KURL& )), + TQT_SLOT( slotOpenURL( const KURL& ))); + (void) new TDEAction( i18n( "History" ), "history", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoHistory() ), actionCollection(), "go_history" ); + + // Settings menu + + m_paSaveViewProfile = new TDEAction( i18n( "&Save View Profile..." ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotSaveViewProfile() ), actionCollection(), "saveviewprofile" ); + m_paSaveViewPropertiesLocally = new TDEToggleAction( i18n( "Save View Changes per &Folder" ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotSaveViewPropertiesLocally() ), actionCollection(), "saveViewPropertiesLocally" ); + // "Remove" ? "Reset" ? The former is more correct, the latter is more kcontrol-like... + m_paRemoveLocalProperties = new TDEAction( i18n( "Remove Folder Properties" ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotRemoveLocalProperties() ), actionCollection(), "removeLocalProperties" ); + + + m_configureModules << "tde-filebehavior.desktop" << "tde-fileappearance.desktop" << + "tde-filepreviews.desktop" << "tde-filetypes.desktop" << + "tde-tdehtml_behavior.desktop" << "tde-tdehtml_userinterface.desktop" << + "tde-tdehtml_java_js.desktop" << "tde-tdehtml_filter.desktop" << + "tde-tdehtml_fonts.desktop" << "tde-ebrowsing.desktop" << + "tde-kcmhistory.desktop" << "tde-cookies.desktop" << + "tde-cache.desktop" << "tde-proxy.desktop" << "tde-kcmcss.desktop" << + "tde-kcmcgi.desktop" << "tde-crypto.desktop" << "tde-useragent.desktop" << + "tde-tdehtml_plugins.desktop" << "tde-kcmkonqyperformance.desktop"; + + + if (!kapp->authorizeControlModules(configModules()).isEmpty()) + KStdAction::preferences (TQT_TQOBJECT(this), TQT_SLOT (slotConfigure()), actionCollection() ); + + KStdAction::keyBindings( guiFactory(), TQT_SLOT( configureShortcuts() ), actionCollection() ); + KStdAction::configureToolbars( TQT_TQOBJECT(this), TQT_SLOT( slotConfigureToolbars() ), actionCollection() ); + + m_paConfigureExtensions = new TDEAction( i18n("Configure Extensions..."), 0, TQT_TQOBJECT(this), TQT_SLOT( slotConfigureExtensions()), actionCollection(), "options_configure_extensions"); + m_paConfigureSpellChecking = new TDEAction( i18n("Configure Spell Checking..."), "tools-check-spelling", 0,TQT_TQOBJECT(this), TQT_SLOT( slotConfigureSpellChecking()), actionCollection(), "configurespellcheck"); + + // Window menu + m_paSplitViewHor = new TDEAction( i18n( "Split View &Left/Right" ), "view_left_right", CTRL+SHIFT+Key_L, TQT_TQOBJECT(this), TQT_SLOT( slotSplitViewHorizontal() ), actionCollection(), "splitviewh" ); + m_paSplitViewVer = new TDEAction( i18n( "Split View &Top/Bottom" ), "view_top_bottom", CTRL+SHIFT+Key_T, TQT_TQOBJECT(this), TQT_SLOT( slotSplitViewVertical() ), actionCollection(), "splitviewv" ); + m_paAddTab = new TDEAction( i18n( "&New Tab" ), "tab_new", "CTRL+SHIFT+N;CTRL+T", TQT_TQOBJECT(this), TQT_SLOT( slotAddTab() ), actionCollection(), "newtab" ); + m_paDuplicateTab = new TDEAction( i18n( "&Duplicate Current Tab" ), "tab_duplicate", CTRL+SHIFT+Key_D, TQT_TQOBJECT(this), TQT_SLOT( slotDuplicateTab() ), actionCollection(), "duplicatecurrenttab" ); + m_paBreakOffTab = new TDEAction( i18n( "Detach Current Tab" ), "tab_breakoff", CTRL+SHIFT+Key_B, TQT_TQOBJECT(this), TQT_SLOT( slotBreakOffTab() ), actionCollection(), "breakoffcurrenttab" ); + m_paRemoveView = new TDEAction( i18n( "&Close Active View" ),"view_remove", CTRL+SHIFT+Key_R, TQT_TQOBJECT(this), TQT_SLOT( slotRemoveView() ), actionCollection(), "removeview" ); + m_paRemoveTab = new TDEAction( i18n( "Close Current Tab" ), "tab_remove", CTRL+Key_W, TQT_TQOBJECT(this), TQT_SLOT( slotRemoveTab() ), actionCollection(), "removecurrenttab" ); + m_paRemoveOtherTabs = new TDEAction( i18n( "Close &Other Tabs" ), "tab_remove_other", 0, TQT_TQOBJECT(this), TQT_SLOT( slotRemoveOtherTabsPopup() ), actionCollection(), "removeothertabs" ); + + m_paActivateNextTab = new TDEAction( i18n( "Activate Next Tab" ), "tab_next", TQApplication::reverseLayout() ? TDEStdAccel::tabPrev() : TDEStdAccel::tabNext(), TQT_TQOBJECT(this), TQT_SLOT( slotActivateNextTab() ), actionCollection(), "activatenexttab" ); + m_paActivatePrevTab = new TDEAction( i18n( "Activate Previous Tab" ), "tab_previous", TQApplication::reverseLayout() ? TDEStdAccel::tabNext() : TDEStdAccel::tabPrev(), TQT_TQOBJECT(this), TQT_SLOT( slotActivatePrevTab() ), actionCollection(), "activateprevtab" ); + + TQCString actionname; + for (int i=1;i<13;i++) { + actionname.sprintf("activate_tab_%02d", i); + new TDEAction(i18n("Activate Tab %1").arg(i), 0, TQT_TQOBJECT(this), TQT_SLOT(slotActivateTab()), actionCollection(), actionname); + } + + m_paMoveTabLeft = new TDEAction( i18n("Move Tab Left"), 0 , CTRL+SHIFT+Key_Left,TQT_TQOBJECT(this), TQT_SLOT( slotMoveTabLeft()),actionCollection(),"tab_move_left"); + m_paMoveTabRight = new TDEAction( i18n("Move Tab Right"), 0 , CTRL+SHIFT+Key_Right,TQT_TQOBJECT(this), TQT_SLOT( slotMoveTabRight()),actionCollection(),"tab_move_right"); + +#ifndef NDEBUG + (void) new TDEAction( i18n( "Dump Debug Info" ), "view_dump_debug_info", 0, TQT_TQOBJECT(this), TQT_SLOT( slotDumpDebugInfo() ), actionCollection(), "dumpdebuginfo" ); +#endif + + m_paSaveRemoveViewProfile = new TDEAction( i18n( "C&onfigure View Profiles..." ), 0, m_pViewManager, TQT_SLOT( slotProfileDlg() ), actionCollection(), "saveremoveviewprofile" ); + m_pamLoadViewProfile = new TDEActionMenu( i18n( "Load &View Profile" ), actionCollection(), "loadviewprofile" ); + + m_pViewManager->setProfiles( m_pamLoadViewProfile ); + + m_ptaFullScreen = KStdAction::fullScreen( 0, 0, actionCollection(), this ); + TDEShortcut fullScreenShortcut = m_ptaFullScreen->shortcut(); + fullScreenShortcut.append( KKey( Key_F11 ) ); + m_ptaFullScreen->setShortcut( fullScreenShortcut ); + connect( m_ptaFullScreen, TQT_SIGNAL( toggled( bool )), TQT_TQOBJECT(this), TQT_SLOT( slotUpdateFullScreen( bool ))); + + TDEShortcut reloadShortcut = TDEStdAccel::shortcut(TDEStdAccel::Reload); + reloadShortcut.append(KKey(CTRL + Key_R)); + m_paReload = new TDEAction( i18n( "&Reload" ), "reload", reloadShortcut, TQT_TQOBJECT(this), TQT_SLOT( slotReload() ), actionCollection(), "reload" ); + m_paReloadAllTabs = new TDEAction( i18n( "&Reload All Tabs" ), "reload_all_tabs", SHIFT+Key_F5, TQT_TQOBJECT(this), TQT_SLOT( slotReloadAllTabs() ), actionCollection(), "reload_all_tabs" ); + + m_paReloadStop = new TDEAction( i18n( "&Reload/Stop" ), "reload", 0, TQT_TQOBJECT(this), TQT_SLOT( slotReloadStop() ), actionCollection(), "reload_stop" ); + + m_paUndo = KStdAction::undo( KonqUndoManager::self(), TQT_SLOT( undo() ), actionCollection(), "undo" ); + //m_paUndo->setEnabled( KonqUndoManager::self()->undoAvailable() ); + connect( KonqUndoManager::self(), TQT_SIGNAL( undoTextChanged( const TQString & ) ), + m_paUndo, TQT_SLOT( setText( const TQString & ) ) ); + + // Those are connected to the browserextension directly + m_paCut = KStdAction::cut( 0, 0, actionCollection(), "cut" ); + TDEShortcut cutShortCut = m_paCut->shortcut(); + cutShortCut.remove( KKey( SHIFT + Key_Delete ) ); // used for deleting files + m_paCut->setShortcut( cutShortCut ); + + m_paCopy = KStdAction::copy( 0, 0, actionCollection(), "copy" ); + m_paPaste = KStdAction::paste( 0, 0, actionCollection(), "paste" ); + m_paStop = new TDEAction( i18n( "&Stop" ), "process-stop", Key_Escape, TQT_TQOBJECT(this), TQT_SLOT( slotStop() ), actionCollection(), "stop" ); + + m_paRename = new TDEAction( i18n( "&Rename" ), /*"editrename",*/ Key_F2, actionCollection(), "rename" ); + m_paTrash = new TDEAction( i18n( "&Move to Trash" ), "edittrash", Key_Delete, actionCollection(), "trash" ); + connect( m_paTrash, TQT_SIGNAL( activated( TDEAction::ActivationReason, TQt::ButtonState ) ), + TQT_TQOBJECT(this), TQT_SLOT( slotTrashActivated( TDEAction::ActivationReason, TQt::ButtonState ) ) ); + + m_paDelete = new TDEAction( i18n( "&Delete" ), "edit-delete", SHIFT+Key_Delete, actionCollection(), "del" ); + // F5 is the default key binding for Reload.... a la Windows. mc users want F5 for Copy and F6 for move, but I can't make that default. + m_paCopyFiles = new TDEAction( i18n("Copy &Files..."), "copyfiles", Key_F7, TQT_TQOBJECT(this), TQT_SLOT( slotCopyFiles() ), actionCollection(), "copyfiles" ); + m_paMoveFiles = new TDEAction( i18n("M&ove Files..."), "movefiles", Key_F8, TQT_TQOBJECT(this), TQT_SLOT( slotMoveFiles() ), actionCollection(), "movefiles" ); + // This action doesn't appear in the GUI, it's for the shortcut only. KNewMenu takes care of the GUI stuff. + m_paNewDir = new TDEAction( i18n("Create Folder..." ), "konq_create_dir", Key_F10, TQT_TQOBJECT(this), TQT_SLOT( slotNewDir() ), actionCollection(), "konq_create_dir" ); + m_paAnimatedLogo = new KonqLogoAction( i18n("Animated Logo"), 0, TQT_TQOBJECT(this), TQT_SLOT( slotDuplicateWindow() ), actionCollection(), "animated_logo" ); + + // Location bar + m_locationLabel = new KonqDraggableLabel( this, i18n("L&ocation: ") ); + (void) new KWidgetAction( m_locationLabel, i18n("L&ocation: "), Key_F6, TQT_TQOBJECT(this), TQT_SLOT( slotLocationLabelActivated() ), actionCollection(), "location_label" ); + m_locationLabel->setBuddy( m_combo ); + + KWidgetAction* comboAction = new KWidgetAction( m_combo, i18n( "Location Bar" ), 0, + 0, 0, actionCollection(), "toolbar_url_combo" ); + comboAction->setShortcutConfigurable( false ); + comboAction->setAutoSized( true ); + + TQWhatsThis::add( m_combo, i18n( "Location Bar

" + "Enter a web address or search term." ) ); + + TDEAction *clearLocation = new TDEAction( i18n( "Clear Location Bar" ), + TQApplication::reverseLayout() ? "clear_left" : "locationbar_erase", + CTRL+Key_L, actionCollection(), "clear_location" ); + connect( clearLocation, TQT_SIGNAL( activated( TDEAction::ActivationReason, TQt::ButtonState ) ), + TQT_SLOT( slotClearLocationBar( TDEAction::ActivationReason, TQt::ButtonState ) ) ); + clearLocation->setWhatsThis( i18n( "Clear Location bar

" + "Clears the content of the location bar." ) ); + + // Bookmarks menu + m_pamBookmarks = new TDEActionMenu( i18n( "&Bookmarks" ), "bookmark", actionCollection(), "bookmarks" ); + m_pamBookmarks->setDelayed( false ); + + // The actual menu needs a different action collection, so that the bookmarks + // don't appear in kedittoolbar + m_bookmarksActionCollection = new TDEActionCollection( this ); + m_bookmarksActionCollection->setHighlightingEnabled( true ); + connectActionCollection( m_bookmarksActionCollection ); + + m_pBookmarkMenu = new KBookmarkMenu( KonqBookmarkManager::self(), m_pBookmarksOwner, m_pamBookmarks->popupMenu(), m_bookmarksActionCollection, true ); + connect( m_pBookmarkMenu, + TQT_SIGNAL( aboutToShowContextMenu(const KBookmark &, TQPopupMenu*) ), + this, TQT_SLOT( slotFillContextMenu(const KBookmark &, TQPopupMenu*) )); + connect( m_pBookmarkMenu, + TQT_SIGNAL( openBookmark(const TQString &, TQt::ButtonState) ), + this, TQT_SLOT( slotOpenBookmarkURL(const TQString &, TQt::ButtonState) )); + + TDEAction *addBookmark = actionCollection()->action("add_bookmark"); + if (addBookmark) + addBookmark->setText(i18n("Bookmark This Location")); + + m_paShowMenuBar = KStdAction::showMenubar( TQT_TQOBJECT(this), TQT_SLOT( slotShowMenuBar() ), actionCollection() ); + + (void) new TDEAction( i18n( "Kon&queror Introduction" ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotIntro() ), actionCollection(), "konqintro" ); + + TDEAction *goUrl = new TDEAction( i18n( "Go" ), "key_enter", 0, TQT_TQOBJECT(this), TQT_SLOT( goURL() ), actionCollection(), "go_url" ); + goUrl->setWhatsThis( i18n( "Go

" + "Goes to the page that has been entered into the location bar." ) ); + + enableAllActions( false ); + + // help stuff + m_paUp->setWhatsThis( i18n( "Enter the parent folder

" + "For instance, if the current location is file:/home/%1 clicking this " + "button will take you to file:/home." ).arg( KUser().loginName() ) ); + m_paUp->setToolTip( i18n( "Enter the parent folder" ) ); + + m_paBack->setWhatsThis( i18n( "Move backwards one step in the browsing history

" ) ); + m_paBack->setToolTip( i18n( "Move backwards one step in the browsing history" ) ); + + m_paForward->setWhatsThis( i18n( "Move forward one step in the browsing history

" ) ); + m_paForward->setToolTip( i18n( "Move forward one step in the browsing history" ) ); + + m_paHome->setWhatsThis( i18n( "Navigate to your 'Home Location'

" + "You can configure the location this button takes you to in the " + "Trinity Control Center, under File Manager/Behavior." ) ); + m_paHome->setToolTip( i18n( "Navigate to your 'Home Location'" ) ); + + m_paReload->setWhatsThis( i18n( "Reload the currently displayed document

" + "This may, for example, be needed to refresh webpages that have been " + "modified since they were loaded, in order to make the changes visible." ) ); + m_paReload->setToolTip( i18n( "Reload the currently displayed document" ) ); + + m_paReloadAllTabs->setWhatsThis( i18n( "Reload all currently displayed documents in tabs

" + "This may, for example, be needed to refresh webpages that have been " + "modified since they were loaded, in order to make the changes visible." ) ); + m_paReloadAllTabs->setToolTip( i18n( "Reload all currently displayed document in tabs" ) ); + + m_paStop->setWhatsThis( i18n( "Stop loading the document

" + "All network transfers will be stopped and Konqueror will display the content " + "that has been received so far." ) ); + m_paStop->setToolTip( i18n( "Stop loading the document" ) ); + + m_paCut->setWhatsThis( i18n( "Cut the currently selected text or item(s) and move it " + "to the system clipboard

" + "This makes it available to the Paste command in Konqueror " + "and other TDE applications." ) ); + m_paCut->setToolTip( i18n( "Move the selected text or item(s) to the clipboard" ) ); + + m_paCopy->setWhatsThis( i18n( "Copy the currently selected text or item(s) to the " + "system clipboard

" + "This makes it available to the Paste command in Konqueror " + "and other TDE applications." ) ); + m_paCopy->setToolTip( i18n( "Copy the selected text or item(s) to the clipboard" ) ); + + m_paPaste->setWhatsThis( i18n( "Paste the previously cut or copied clipboard " + "contents

" + "This also works for text copied or cut from other TDE applications." ) ); + m_paPaste->setToolTip( i18n( "Paste the clipboard contents" ) ); + + m_paPrint->setWhatsThis( i18n( "Print the currently displayed document

" + "You will be presented with a dialog where you can set various " + "options, such as the number of copies to print and which printer " + "to use.

" + "This dialog also provides access to special TDE printing " + "services such as creating a PDF file from the current document." ) ); + m_paPrint->setToolTip( i18n( "Print the current document" ) ); + + + + // Please proof-read those (David) + + m_ptaUseHTML->setToolTip( i18n("If present, open index.html when entering a folder.") ); + m_paLockView->setToolTip( i18n("A locked view cannot change folders. Use in combination with 'link view' to explore many files from one folder") ); + m_paLinkView->setToolTip( i18n("Sets the view as 'linked'. A linked view follows folder changes made in other linked views.") ); +} + +void KonqMainWindow::slotFillContextMenu( const KBookmark &bk, TQPopupMenu * pm ) +{ + kdDebug() << "KonqMainWindow::slotFillContextMenu(bk, pm == " << pm << ")" << endl; + popupItems.clear(); + popupUrlArgs = KParts::URLArgs(); + + //Set tab_new_x to point to the correct icon based on NewTabsInFront + bool newtabsinfront = KonqSettings::newTabsInFront(); + TQString tab_new_x ; + if ( newtabsinfront ) + tab_new_x = "tab_new" ; + else + tab_new_x = "tab_new_bg" ; + + if ( bk.isGroup() ) + { + KBookmarkGroup grp = bk.toGroup(); + TQValueList list = grp.groupUrlList(); + TQValueList::Iterator it = list.begin(); + for (; it != list.end(); ++it ) + popupItems.append( new KFileItem( (*it), TQString::null, KFileItem::Unknown) ); + pm->insertItem( SmallIcon(tab_new_x), i18n( "Open Folder in Tabs" ), this, TQT_SLOT( slotPopupNewTabRight() ) ); + } + else + { + popupItems.append( new KFileItem( bk.url(), TQString::null, KFileItem::Unknown) ); + pm->insertItem( SmallIcon("window-new"), i18n( "Open in New Window" ), this, TQT_SLOT( slotPopupNewWindow() ) ); + pm->insertItem( SmallIcon(tab_new_x), i18n( "Open in New Tab" ), this, TQT_SLOT( slotPopupNewTabRight() ) ); + } +} + +void KonqMainWindow::slotOpenBookmarkURL( const TQString & url, TQt::ButtonState state) +{ + kdDebug(1202) << "KonqMainWindow::slotOpenBookmarkURL(" << url << ", " << state << ")" << endl; + + KonqOpenURLRequest req; + req.newTab = true; + req.newTabInFront = KonqSettings::newTabsInFront(); + + if (state & TQt::ShiftButton) + req.newTabInFront = !req.newTabInFront; + + if( state & TQt::ControlButton ) // Ctrl Left/MMB + openFilteredURL( url, req); + else if( state & Qt::MidButton ) + { + if(KonqSettings::mmbOpensTab()) + openFilteredURL( url, req); + else + { + KURL finalURL = KonqMisc::konqFilteredURL( this, url ); + KonqMisc::createNewWindow( finalURL.url() ); + } + } + else + openFilteredURL( url, false ); +} + +void KonqMainWindow::slotMoveTabLeft() +{ + if ( TQApplication::reverseLayout() ) + m_pViewManager->moveTabForward(); + else + m_pViewManager->moveTabBackward(); +} + +void KonqMainWindow::slotMoveTabRight() +{ + if ( TQApplication::reverseLayout() ) + m_pViewManager->moveTabBackward(); + else + m_pViewManager->moveTabForward(); +} + +void KonqMainWindow::updateToolBarActions( bool pendingAction /*=false*/) +{ + // Enables/disables actions that depend on the current view & url (mostly toolbar) + // Up, back, forward, the edit extension, stop button, wheel + setUpEnabled( m_currentView->url() ); + m_paBack->setEnabled( m_currentView->canGoBack() ); + m_paForward->setEnabled( m_currentView->canGoForward() ); + + if ( m_currentView->isLoading() ) + { + startAnimation(); // takes care of m_paStop + } + else + { + m_paAnimatedLogo->stop(); + m_paStop->setEnabled( pendingAction ); //enable/disable based on any pending actions... + toggleReloadStopButton( pendingAction ); + } + + if ( m_currentView && m_currentView->url().isLocalFile() && + !m_currentView->isLockedViewMode() ) { + if ( m_currentView->serviceTypes().contains( "inode/directory" ) ) + m_ptaUseHTML->setEnabled( true ); + else if ( m_currentView->serviceTypes().contains( "text/html" ) ) { + // Currently viewing an index.html file via this feature (i.e. url points to a dir) + TQString locPath = KURL( m_currentView->locationBarURL() ).path(); + m_ptaUseHTML->setEnabled( TQFileInfo( locPath ).isDir() ); + } else + m_ptaUseHTML->setEnabled( false ); + } + else + { + m_ptaUseHTML->setEnabled( false ); + } +} + +void KonqMainWindow::updateViewActions() +{ + // Update actions that depend on the current view and its mode, or on the number of views etc. + + // Don't do things in this method that depend on m_currentView->url(). + // When going 'back' in history this will be called before opening the url. + // Use updateToolBarActions instead. + + slotUndoAvailable( KonqUndoManager::self()->undoAvailable() ); + + // Can lock a view only if there is a next view + //m_paLockView->setEnabled( m_pViewManager->chooseNextView(m_currentView) != 0L && ); + //kdDebug(1202) << "KonqMainWindow::updateViewActions m_paLockView enabled ? " << m_paLockView->isEnabled() << endl; + + m_paLockView->setEnabled( viewCount() > 1 ); + m_paLockView->setChecked( m_currentView && m_currentView->isLockedLocation() ); + + // Can remove view if we'll still have a main view after that + m_paRemoveView->setEnabled( mainViewsCount() > 1 || + ( m_currentView && m_currentView->isToggleView() ) ); + + KonqFrameBase* docContainer = m_pViewManager->docContainer(); + + if ( docContainer == 0L && !(currentView() && currentView()->frame())) + { + m_paAddTab->setEnabled( false ); + m_paDuplicateTab->setEnabled( false ); + m_paRemoveTab->setEnabled( false ); + m_paRemoveOtherTabs->setEnabled( false ); + m_paBreakOffTab->setEnabled( false ); + m_paActivateNextTab->setEnabled( false ); + m_paActivatePrevTab->setEnabled( false ); + m_paMoveTabLeft->setEnabled( false ); + m_paMoveTabRight->setEnabled( false ); + } + else + { + m_paAddTab->setEnabled( true ); + m_paDuplicateTab->setEnabled( true ); + if ( docContainer && docContainer->frameType() == "Tabs" ) + { + KonqFrameTabs* tabContainer = static_cast(docContainer); + bool state = (tabContainer->count()>1); + m_paRemoveTab->setEnabled( state ); + m_paRemoveOtherTabs->setEnabled( state ); + m_paBreakOffTab->setEnabled( state ); + m_paActivateNextTab->setEnabled( state ); + m_paActivatePrevTab->setEnabled( state ); + + TQPtrList* childFrameList = tabContainer->childFrameList(); + m_paMoveTabLeft->setEnabled( currentView() ? currentView()->frame()!= + (TQApplication::reverseLayout() ? childFrameList->last() : childFrameList->first()) : false ); + m_paMoveTabRight->setEnabled( currentView() ? currentView()->frame()!= + (TQApplication::reverseLayout() ? childFrameList->first() : childFrameList->last()) : false ); + } + else + { + m_paRemoveTab->setEnabled( false ); + m_paRemoveOtherTabs->setEnabled( false ); + m_paBreakOffTab->setEnabled( false ); + m_paActivateNextTab->setEnabled( false ); + m_paActivatePrevTab->setEnabled( false ); + m_paMoveTabLeft->setEnabled( false ); + m_paMoveTabRight->setEnabled( false ); + + } + } + + // Can split a view if it's not a toggle view (because a toggle view can be here only once) + bool isNotToggle = m_currentView && !m_currentView->isToggleView(); + m_paSplitViewHor->setEnabled( isNotToggle ); + m_paSplitViewVer->setEnabled( isNotToggle ); + + m_paLinkView->setChecked( m_currentView && m_currentView->isLinkedView() ); + + if ( m_currentView && m_currentView->part() && + m_currentView->part()->inherits("KonqDirPart") ) + { + KonqDirPart * dirPart = static_cast(m_currentView->part()); + m_paFindFiles->setEnabled( dirPart->findPart() == 0 ); + + TQPtrList lst; + if (!m_paCopyFiles->isPlugged()) + lst.append( m_paCopyFiles ); + if (!m_paMoveFiles->isPlugged()) + lst.append( m_paMoveFiles ); + m_paCopyFiles->setEnabled( false ); + m_paMoveFiles->setEnabled( false ); + if (!lst.isEmpty()) + plugActionList( "operations", lst ); + } + else + { + m_paFindFiles->setEnabled( false ); + unplugActionList( "operations" ); + } +} + +TQString KonqMainWindow::findIndexFile( const TQString &dir ) +{ + TQDir d( dir ); + + TQString f = d.filePath( "index.html", false ); + if ( TQFile::exists( f ) ) + return f; + + f = d.filePath( "index.htm", false ); + if ( TQFile::exists( f ) ) + return f; + + f = d.filePath( "index.HTML", false ); + if ( TQFile::exists( f ) ) + return f; + + return TQString::null; +} + +void KonqMainWindow::connectExtension( KParts::BrowserExtension *ext ) +{ + //kdDebug(1202) << "Connecting extension " << ext << endl; + KParts::BrowserExtension::ActionSlotMap * actionSlotMap = KParts::BrowserExtension::actionSlotMapPtr(); + KParts::BrowserExtension::ActionSlotMap::ConstIterator it = actionSlotMap->begin(); + KParts::BrowserExtension::ActionSlotMap::ConstIterator itEnd = actionSlotMap->end(); + + TQStrList slotNames = ext->metaObject()->slotNames(); + + for ( ; it != itEnd ; ++it ) + { + TDEAction * act = actionCollection()->action( static_cast(it.key()) ); + //kdDebug(1202) << it.key() << endl; + if ( act ) + { + // Does the extension have a slot with the name of this action ? + if ( slotNames.contains( it.key()+"()" ) ) + { + if ( it.key() != "trash" ) + connect( act, TQT_SIGNAL( activated() ), ext, it.data() /* TQT_SLOT(slot name) */ ); + act->setEnabled( ext->isActionEnabled( it.key() ) ); + const TQString text = ext->actionText( it.key() ); + if ( !text.isEmpty() ) + act->setText( text ); + // TODO how to re-set the original action text, when switching to a part that didn't call setAction? + // Can't test with Paste... + } else + act->setEnabled(false); + + } else kdError(1202) << "Error in BrowserExtension::actionSlotMap(), unknown action : " << it.key() << endl; + } + +} + +void KonqMainWindow::disconnectExtension( KParts::BrowserExtension *ext ) +{ + //kdDebug(1202) << "Disconnecting extension " << ext << endl; + KParts::BrowserExtension::ActionSlotMap * actionSlotMap = KParts::BrowserExtension::actionSlotMapPtr(); + KParts::BrowserExtension::ActionSlotMap::ConstIterator it = actionSlotMap->begin(); + KParts::BrowserExtension::ActionSlotMap::ConstIterator itEnd = actionSlotMap->end(); + + TQStrList slotNames = ext->metaObject()->slotNames(); + + for ( ; it != itEnd ; ++it ) + { + TDEAction * act = actionCollection()->action( static_cast(it.key()) ); + //kdDebug(1202) << it.key() << endl; + if ( act && slotNames.contains( it.key()+"()" ) ) + { + //kdDebug(1202) << "disconnectExtension: " << act << " " << act->name() << endl; + act->disconnect( ext ); + } + } +} + +void KonqMainWindow::slotTrashActivated( TDEAction::ActivationReason reason, TQt::ButtonState state ) +{ + if ( !m_currentView ) + return; + if ( reason == TDEAction::PopupMenuActivation && ( state & TQt::ShiftButton ) ) + m_currentView->callExtensionMethod( "del()" ); + else + m_currentView->callExtensionMethod( "trash()" ); +} + +void KonqMainWindow::enableAction( const char * name, bool enabled ) +{ + TDEAction * act = actionCollection()->action( name ); + if (!act) + kdWarning(1202) << "Unknown action " << name << " - can't enable" << endl; + else + { + if ( m_bLocationBarConnected && ( + act==m_paCopy || act==m_paCut || act==m_paPaste || act==m_paDelete || act==m_paTrash ) ) + // Don't change action state while the location bar has focus. + return; + //kdDebug(1202) << "KonqMainWindow::enableAction " << name << " " << enabled << endl; + act->setEnabled( enabled ); + } + + // Update "copy files" and "move files" accordingly + if (m_paCopyFiles && !strcmp( name, "copy" )) + { + m_paCopyFiles->setEnabled( enabled ); + } + else if (m_paMoveFiles && !strcmp( name, "cut" )) + { + m_paMoveFiles->setEnabled( enabled ); + } +} + +void KonqMainWindow::setActionText( const char * name, const TQString& text ) +{ + TDEAction * act = actionCollection()->action( name ); + if (!act) + kdWarning(1202) << "Unknown action " << name << " - can't enable" << endl; + else + { + kdDebug(1202) << "KonqMainWindow::setActionText " << name << " " << text << endl; + act->setText( text ); + } +} + +void KonqMainWindow::currentProfileChanged() +{ + bool enabled = !m_pViewManager->currentProfile().isEmpty(); + m_paSaveViewProfile->setEnabled( enabled ); + m_paSaveViewProfile->setText( enabled ? i18n("&Save View Profile \"%1\"...").arg(m_pViewManager->currentProfileText()) + : i18n("&Save View Profile...") ); +} + +void KonqMainWindow::enableAllActions( bool enable ) +{ + kdDebug(1202) << "KonqMainWindow::enableAllActions " << enable << endl; + KParts::BrowserExtension::ActionSlotMap * actionSlotMap = KParts::BrowserExtension::actionSlotMapPtr(); + + TQValueList actions = actionCollection()->actions(); + TQValueList::Iterator it = actions.begin(); + TQValueList::Iterator end = actions.end(); + for (; it != end; ++it ) + { + TDEAction *act = *it; + if ( !TQString(act->name()).startsWith("options_configure") /* do not touch the configureblah actions */ + && ( !enable || !actionSlotMap->contains( act->name() ) ) ) /* don't enable BE actions */ + act->setEnabled( enable ); + } + // This method is called with enable=false on startup, and + // then only once with enable=true when the first view is setup. + // So the code below is where actions that should initially be disabled are disabled. + if (enable) + { + setUpEnabled( m_currentView ? m_currentView->url() : KURL() ); + // we surely don't have any history buffers at this time + m_paBack->setEnabled( false ); + m_paForward->setEnabled( false ); + + // Load profile submenu + m_pViewManager->profileListDirty( false ); + + currentProfileChanged(); + + updateViewActions(); // undo, lock, link and other view-dependent actions + + m_paStop->setEnabled( m_currentView && m_currentView->isLoading() ); + toggleReloadStopButton( m_currentView && m_currentView->isLoading() ); + + if (m_toggleViewGUIClient) + { + TQPtrList actions = m_toggleViewGUIClient->actions(); + for ( TDEAction * it = actions.first(); it ; it = actions.next() ) + it->setEnabled( true ); + } + + } + actionCollection()->action( "quit" )->setEnabled( true ); +} + +void KonqMainWindow::disableActionsNoView() +{ + // No view -> there are some things we can't do + m_paUp->setEnabled( false ); + m_paReload->setEnabled( false ); + m_paReloadAllTabs->setEnabled( false ); + m_paBack->setEnabled( false ); + m_paForward->setEnabled( false ); + m_ptaUseHTML->setEnabled( false ); + m_pMenuNew->setEnabled( false ); + m_paLockView->setEnabled( false ); + m_paLockView->setChecked( false ); + m_paSplitViewVer->setEnabled( false ); + m_paSplitViewHor->setEnabled( false ); + m_paRemoveView->setEnabled( false ); + m_paLinkView->setEnabled( false ); + if (m_toggleViewGUIClient) + { + TQPtrList actions = m_toggleViewGUIClient->actions(); + for ( TDEAction * it = actions.first(); it ; it = actions.next() ) + it->setEnabled( false ); + } + // There are things we can do, though : bookmarks, view profile, location bar, new window, + // settings, etc. + m_paHome->setEnabled( true ); + m_pamBookmarks->setEnabled( true ); + static const char* const s_enActions[] = { "new_window", "duplicate_window", "open_location", + "toolbar_url_combo", "clear_location", "animated_logo", + "konqintro", "go_most_often", "go_applications", "go_dirtree", + "go_trash", "go_settings", "go_network_folders", "go_autostart", + "go_url", "go_media", "go_history", "options_configure_extensions", 0 }; + for ( int i = 0 ; s_enActions[i] ; ++i ) + { + TDEAction * act = action(s_enActions[i]); + if (act) + act->setEnabled( true ); + } + m_pamLoadViewProfile->setEnabled( true ); + m_paSaveViewProfile->setEnabled( true ); + m_paSaveRemoveViewProfile->setEnabled( true ); + m_combo->clearTemporary(); + updateLocalPropsActions(); +} + +void KonqExtendedBookmarkOwner::openBookmarkURL( const TQString & /*url*/ ) +{ + // Do nothing, we catch the signal +} + +void KonqMainWindow::setCaption( const TQString &caption ) +{ + // KParts sends us empty captions when activating a brand new part + // We can't change it there (in case of apps removing all parts altogether) + // but here we never do that. + if ( !caption.isEmpty() && m_currentView ) + { + kdDebug(1202) << "KonqMainWindow::setCaption(" << caption << ")" << endl; + + // Keep an unmodified copy of the caption (before kapp->makeStdCaption is applied) + m_currentView->setCaption( caption ); + KParts::MainWindow::setCaption( m_currentView->caption() ); + } +} + +void KonqMainWindow::show() +{ + // We need to check if our toolbars are shown/hidden here, and set + // our menu items accordingly. We can't do it in the constructor because + // view profiles store toolbar info, and that info is read after + // construct time. + m_paShowMenuBar->setChecked( !menuBar()->isHidden() ); + updateBookmarkBar(); // hide if empty + + // Call parent method + KParts::MainWindow::show(); +} + +TQString KonqExtendedBookmarkOwner::currentURL() const +{ + return m_pKonqMainWindow->currentURL(); +} + +TQString KonqMainWindow::currentProfile() const +{ + return m_pViewManager->currentProfile(); +} + +TQString KonqMainWindow::currentURL() const +{ + if ( !m_currentView ) + return TQString::null; + TQString url = m_currentView->url().prettyURL(); + if ( m_currentView->part() && m_currentView->part()->inherits("KonqDirPart") ) + { + TQString nameFilter = static_cast(m_currentView->part())->nameFilter(); + if ( !nameFilter.isEmpty() ) + { + if (!url.endsWith("/")) + url += '/'; + url += nameFilter; + } + } + return url; +} + +void KonqExtendedBookmarkOwner::slotFillBookmarksList( KExtendedBookmarkOwner::QStringPairList & list ) +{ + KonqFrameBase *docContainer = m_pKonqMainWindow->viewManager()->docContainer(); + if (docContainer == 0L) return; + if (docContainer->frameType() != "Tabs") return; + + KonqFrameTabs* tabContainer = static_cast(docContainer); + + TQPtrList frameList = *tabContainer->childFrameList(); + TQPtrListIterator it( frameList ); + + for ( it.toFirst(); it != 0L; ++it ) + { + if ( !it.current()->activeChildView() ) + continue; + if( it.current()->activeChildView()->locationBarURL().isEmpty() ) + continue; + list << qMakePair( it.current()->activeChildView()->caption(), + it.current()->activeChildView()->url().url() ); + } +} + +TQString KonqExtendedBookmarkOwner::currentTitle() const +{ + return m_pKonqMainWindow->currentTitle(); +} + +TQString KonqMainWindow::currentTitle() const +{ + return m_currentView ? m_currentView->caption() : TQString::null; +} + +void KonqMainWindow::slotPopupMenu( const TQPoint &_global, const KURL &url, const TQString &_mimeType, mode_t _mode ) +{ + slotPopupMenu( 0L, _global, url, _mimeType, _mode ); +} + +void KonqMainWindow::slotPopupMenu( KXMLGUIClient *client, const TQPoint &_global, const KURL &url, const TQString &_mimeType, mode_t _mode ) +{ + KFileItem item( url, _mimeType, _mode ); + KFileItemList items; + items.append( &item ); + slotPopupMenu( client, _global, items, KParts::URLArgs(), KParts::BrowserExtension::DefaultPopupItems, false ); //BE CAREFUL WITH sender() ! +} + +void KonqMainWindow::slotPopupMenu( KXMLGUIClient *client, const TQPoint &_global, const KURL &url, const KParts::URLArgs &_args, KParts::BrowserExtension::PopupFlags f, mode_t _mode ) +{ + KFileItem item( url, _args.serviceType, _mode ); + KFileItemList items; + items.append( &item ); + slotPopupMenu( client, _global, items, _args, f, false ); //BE CAREFUL WITH sender() ! +} + +void KonqMainWindow::slotPopupMenu( const TQPoint &_global, const KFileItemList &_items ) +{ + slotPopupMenu( 0L, _global, _items ); +} + +void KonqMainWindow::slotPopupMenu( KXMLGUIClient *client, const TQPoint &_global, const KFileItemList &_items ) +{ + slotPopupMenu( client, _global, _items, KParts::URLArgs(), KParts::BrowserExtension::DefaultPopupItems, true ); +} + +void KonqMainWindow::slotPopupMenu( KXMLGUIClient *client, const TQPoint &_global, const KFileItemList &_items, const KParts::URLArgs &_args, KParts::BrowserExtension::PopupFlags _flags ) +{ + slotPopupMenu( client, _global, _items, _args, _flags, true ); +} + +void KonqMainWindow::slotPopupMenu( KXMLGUIClient *client, const TQPoint &_global, const KFileItemList &_items, const KParts::URLArgs &_args, KParts::BrowserExtension::PopupFlags itemFlags, bool showProperties ) +{ + KonqView * m_oldView = m_currentView; + + KonqView * currentView = childView( static_cast( TQT_TQOBJECT_CONST(sender())->parent() ) ); + + //kdDebug() << "KonqMainWindow::slotPopupMenu m_oldView=" << m_oldView << " new currentView=" << currentView << " passive:" << currentView->isPassiveMode() << endl; + + if ( (m_oldView != currentView) && currentView->isPassiveMode() ) + { + // Make this view active only temporarily (because it's passive) + m_currentView = currentView; + + if ( m_oldView && m_oldView->browserExtension() ) + disconnectExtension( m_oldView->browserExtension() ); + if ( m_currentView->browserExtension() ) + connectExtension( m_currentView->browserExtension() ); + } + // Note that if m_oldView!=currentView and currentView isn't passive, + // then the KParts mechanism has already noticed the click in it, + // but KonqViewManager delays the GUI-rebuilding with a single-shot timer. + // Right after the popup shows up, currentView _will_ be m_currentView. + + //kdDebug(1202) << "KonqMainWindow::slotPopupMenu( " << client << "...)" << " current view=" << m_currentView << " " << m_currentView->part()->className() << endl; + + // This action collection is used to pass actions to KonqPopupMenu. + // It has to be a TDEActionCollection instead of a TDEActionPtrList because we need + // the actionStatusText signal... + TDEActionCollection popupMenuCollection( (TQWidget*)0 ); + popupMenuCollection.insert( m_paBack ); + popupMenuCollection.insert( m_paForward ); + popupMenuCollection.insert( m_paUp ); + popupMenuCollection.insert( m_paReload ); + + popupMenuCollection.insert( m_paFindFiles ); + + popupMenuCollection.insert( m_paUndo ); + popupMenuCollection.insert( m_paCut ); + popupMenuCollection.insert( m_paCopy ); + popupMenuCollection.insert( m_paPaste ); + popupMenuCollection.insert( m_paTrash ); + popupMenuCollection.insert( m_paRename ); + popupMenuCollection.insert( m_paDelete ); + + // The pasteto action is used when clicking on a dir, to paste into it. + TDEAction *actPaste = KStdAction::paste( TQT_TQOBJECT(this), TQT_SLOT( slotPopupPasteTo() ), &popupMenuCollection, "pasteto" ); + actPaste->setEnabled( m_paPaste->isEnabled() ); + popupMenuCollection.insert( actPaste ); + + bool sReading = false; + if ( _items.count() > 0 ) + { + m_popupURL = _items.getFirst()->url(); + sReading = KProtocolInfo::supportsReading( m_popupURL ); + if (sReading) + m_popupServiceType = _items.getFirst()->mimetype(); + } + else + { + m_popupURL = KURL(); + m_popupServiceType = TQString::null; + } + + if ( (_items.count() == 1) && !m_popupServiceType.isEmpty() ) { + TQString currentServiceName = currentView->service()->desktopEntryName(); + + // List of services for the "Preview In" submenu. + m_popupEmbeddingServices = TDETrader::self()->query( + m_popupServiceType, + "KParts/ReadOnlyPart", + // Obey "HideFromMenus". It defaults to false so we want "absent or true" + // (wow, testing for 'true' if absent doesn't work, so order matters) + "(not exist [X-TDE-BrowserView-HideFromMenus] or not [X-TDE-BrowserView-HideFromMenus]) " + "and DesktopEntryName != '"+currentServiceName+"' " + // I had an old local dirtree.desktop without lib, no need for invalid entries + "and exist [Library]", + TQString::null ); + } + + + // Don't set the view URL for a toggle view. + // (This is a bit of a hack for the directory tree....) + // ## should use the new currentView->isHierarchicalView() instead? + // Would this be correct for the konqlistview tree view? + KURL viewURL = currentView->isToggleView() ? KURL() : currentView->url(); + + bool openedForViewURL = false; + //bool dirsSelected = false; + bool devicesFile = false; + + if ( _items.count() == 1 ) + { + KURL firstURL = _items.getFirst()->url(); + if ( !viewURL.isEmpty() ) + { + //firstURL.cleanPath(); + openedForViewURL = firstURL.equals( viewURL, true ); + } + devicesFile = firstURL.protocol().find("device", 0, false) == 0; + //dirsSelected = S_ISDIR( _items.getFirst()->mode() ); + } + //check if current url is trash + KURL url = viewURL; + url.cleanPath(); + bool isIntoTrash = url.protocol() == "trash" || url.url().startsWith( "system:/trash" ); + bool doTabHandling = !openedForViewURL && !isIntoTrash && sReading; + bool showEmbeddingServices = !isIntoTrash && !devicesFile && (itemFlags & KParts::BrowserExtension::ShowTextSelectionItems) == 0; + PopupMenuGUIClient *konqyMenuClient = new PopupMenuGUIClient( this, m_popupEmbeddingServices, + showEmbeddingServices, doTabHandling ); + + //kdDebug(1202) << "KonqMainWindow::slotPopupMenu " << viewURL.prettyURL() << endl; + + + // Those actions go into the PopupMenuGUIClient, since that's the one defining them. + TDEAction *actNewWindow = 0L; + if (doTabHandling) + { + if (_args.forcesNewWindow()) { + actNewWindow = new TDEAction( i18n( "Open in T&his Window" ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotPopupThisWindow() ), konqyMenuClient->actionCollection(), "sameview" ); + actNewWindow->setToolTip( i18n( "Open the document in current window" ) ); + } + actNewWindow = new TDEAction( i18n( "Open in New &Window" ), "window-new", 0, TQT_TQOBJECT(this), TQT_SLOT( slotPopupNewWindow() ), konqyMenuClient->actionCollection(), "newview" ); + actNewWindow->setToolTip( i18n( "Open the document in a new window" ) ); + + //Set tab_new_x to point to the correct icon based on NewTabsInFront + bool newtabsinfront = KonqSettings::newTabsInFront(); + TQString tab_new_x ; + if ( newtabsinfront ) + tab_new_x = "tab_new" ; + else + tab_new_x = "tab_new_bg" ; + + TDEAction *actNewTab = new TDEAction( i18n( "Open in &Background Tab" ), "tab_new_bg", 0, TQT_TQOBJECT(this), TQT_SLOT( slotPopupNewTab() ), actionCollection(), "openintab" ); + actNewTab->setStatusText( i18n( "Open the document in a new background tab" ) ); + TDEAction *actNewTabFront = new TDEAction( i18n( "Open in &New Tab" ), "tab_new", 0, TQT_TQOBJECT(this), TQT_SLOT( slotPopupNewTabAtFront() ), actionCollection(), "openintabfront" ); + actNewTabFront->setStatusText( i18n( "Open the document in a new foreground tab" ) ); + actNewTab = new TDEAction( i18n( "Open in &Background Tab" ), tab_new_x, 0, TQT_TQOBJECT(this), TQT_SLOT( slotPopupNewTab() ), konqyMenuClient->actionCollection(), "openintab" ); + actNewTabFront = new TDEAction( i18n( "Open in &New Tab" ), tab_new_x, 0, TQT_TQOBJECT(this), TQT_SLOT( slotPopupNewTabAtFront() ), konqyMenuClient->actionCollection(), "openintabfront" ); + actNewTab->setToolTip( i18n( "Open the document in a new background tab" ) ); + actNewTabFront->setToolTip( i18n( "Open the document in a new foreground tab" ) ); + doTabHandling = true; + } + + if (currentView->isHierarchicalView()) + itemFlags |= KParts::BrowserExtension::ShowCreateDirectory; + + KonqPopupMenu::KonqPopupFlags kpf = 0; + if ( showProperties ) + kpf |= KonqPopupMenu::ShowProperties; + else + kpf |= KonqPopupMenu::IsLink; // HACK + + TQGuardedPtr pPopupMenu = new KonqPopupMenu( + KonqBookmarkManager::self(), _items, + viewURL, + popupMenuCollection, + m_pMenuNew, + // This parent ensures that if the part destroys itself (e.g. TDEHTML redirection), + // it will close the popupmenu + currentView->part()->widget(), + kpf, + itemFlags ); + + if ( openedForViewURL && !viewURL.isLocalFile() ) + pPopupMenu->setURLTitle( currentView->caption() ); + + // We will need these if we call the newTab slot + popupItems = _items; + popupUrlArgs = _args; + popupUrlArgs.serviceType = TQString::null; // Reset so that Open in New Window/Tab does mimetype detection + + connectActionCollection( pPopupMenu->actionCollection() ); + + if (pPopupMenu->hasGroup("tabhandling")) + { + // "tabhandling" group in inserted in the popup menu if no encrypted media devices are part of "_items" + // see libkonq/konq_popupmenu.cpp KonqPopupMenu::setup() method + pPopupMenu->factory()->addClient( konqyMenuClient ); + } + + if ( client ) + pPopupMenu->factory()->addClient( client ); + + KParts::BrowserExtension *be = ::tqqt_cast(sender()); + + if ( be ) + { + TQObject::connect( this, TQT_SIGNAL(popupItemsDisturbed()), pPopupMenu, TQT_SLOT(close()) ); + TQObject::connect( be, TQT_SIGNAL(itemsRemoved(const KFileItemList &)), + this, TQT_SLOT(slotItemsRemoved(const KFileItemList &)) ); + } + + TQObject::disconnect( m_pMenuNew->popupMenu(), TQT_SIGNAL(aboutToShow()), + this, TQT_SLOT(slotFileNewAboutToShow()) ); + + TQGuardedPtr guard(TQT_TQOBJECT(this)); // #149736 + pPopupMenu->exec( _global ); + + delete pPopupMenu; + + // We're sort of misusing TDEActionCollection here, but we need it for the actionStatusText signal... + // Anyway. If the action belonged to the view, and the view got deleted, we don't want ~TDEActionCollection + // to iterate over those deleted actions + TDEActionPtrList lst = popupMenuCollection.actions(); + TDEActionPtrList::iterator it = lst.begin(); + for ( ; it != lst.end() ; ++it ) + popupMenuCollection.take( *it ); + + if (guard.isNull()) { // the placement of this test is very important, double-check #149736 if moving stuff around + return; + } + + TQObject::connect( m_pMenuNew->popupMenu(), TQT_SIGNAL(aboutToShow()), + this, TQT_SLOT(slotFileNewAboutToShow()) ); + + if ( be ) + { + TQObject::disconnect( be, TQT_SIGNAL(itemsRemoved(const KFileItemList &)), + this, TQT_SLOT(slotItemsRemoved(const KFileItemList &)) ); + } + + delete konqyMenuClient; + m_popupEmbeddingServices.clear(); + popupItems.clear(); + + // Deleted by konqyMenuClient's actioncollection + //delete actNewWindow; + + delete actPaste; + + + //kdDebug(1202) << "-------- KonqMainWindow::slotPopupMenu() - m_oldView = " << m_oldView << ", currentView = " << currentView + //<< ", m_currentView = " << m_currentView << endl; + + // Restore current view if current is passive + if ( (m_oldView != currentView) && (currentView == m_currentView) && currentView->isPassiveMode() ) + { + //kdDebug() << "KonqMainWindow::slotPopupMenu restoring active view " << m_oldView << endl; + if ( m_currentView->browserExtension() ) + disconnectExtension( m_currentView->browserExtension() ); + if ( m_oldView ) + { + if ( m_oldView->browserExtension() ) + { + connectExtension( m_oldView->browserExtension() ); + m_currentView = m_oldView; + } + // Special case: RMB + renaming in sidebar; setFocus would abort editing. + TQWidget* fw = focusWidget(); + if ( !fw || !::tqqt_cast( fw ) ) + m_oldView->part()->widget()->setFocus(); + } + } +} + +void KonqMainWindow::slotItemsRemoved( const KFileItemList &items ) +{ + TQPtrListIterator it( items ); + for ( ; it.current(); ++it ) + { + if ( popupItems.contains( it.current() ) ) + { + emit popupItemsDisturbed(); + return; + } + } +} + +void KonqMainWindow::slotOpenEmbedded() +{ + TQCString name = TQT_TQOBJECT_CONST(sender())->name(); + + m_popupService = m_popupEmbeddingServices[ name.toInt() ]->desktopEntryName(); + + m_popupEmbeddingServices.clear(); + + TQTimer::singleShot( 0, this, TQT_SLOT( slotOpenEmbeddedDoIt() ) ); +} + +void KonqMainWindow::slotOpenEmbeddedDoIt() +{ + m_currentView->stop(); + m_currentView->setLocationBarURL(m_popupURL); + m_currentView->setTypedURL(TQString::null); + if ( m_currentView->changeViewMode( m_popupServiceType, + m_popupService ) ) + m_currentView->openURL( m_popupURL, m_popupURL.pathOrURL() ); +} + +void KonqMainWindow::slotDatabaseChanged() +{ + if ( KSycoca::isChanged("mimetypes") ) + { + MapViews::ConstIterator it = m_mapViews.begin(); + MapViews::ConstIterator end = m_mapViews.end(); + for (; it != end; ++it ) + (*it)->callExtensionMethod( "refreshMimeTypes()" ); + } +} + +void KonqMainWindow::slotPopupPasteTo() +{ + if ( !m_currentView || m_popupURL.isEmpty() ) + return; + m_currentView->callExtensionURLMethod( "pasteTo(const KURL&)", m_popupURL ); +} + +void KonqMainWindow::slotReconfigure() +{ + reparseConfiguration(); +} + +void KonqMainWindow::reparseConfiguration() +{ + kdDebug(1202) << "KonqMainWindow::reparseConfiguration() !" << endl; + + KonqSettings::self()->readConfig(); + + m_bSaveViewPropertiesLocally = KonqSettings::saveViewPropertiesLocally(); + m_bHTMLAllowed = KonqSettings::htmlAllowed(); + + MapViews::ConstIterator it = m_mapViews.begin(); + MapViews::ConstIterator end = m_mapViews.end(); + for (; it != end; ++it ) + (*it)->reparseConfiguration(); + + // Push updates to KonqViewManager as well + viewManager()->reparseConfiguration(); +} + +void KonqMainWindow::saveProperties( TDEConfig *config ) +{ + m_pViewManager->saveViewProfile( *config, true /* save URLs */, false ); +} + +void KonqMainWindow::readProperties( TDEConfig *config ) +{ + kdDebug(1202) << "KonqMainWindow::readProperties( TDEConfig *config )" << endl; + m_pViewManager->loadViewProfile( *config, TQString::null /*no profile name*/ ); +} + +void KonqMainWindow::setInitialFrameName( const TQString &name ) +{ + m_initialFrameName = name; +} + +void KonqMainWindow::slotActionStatusText( const TQString &text ) +{ + if ( !m_currentView ) + return; + + KonqFrameStatusBar *statusBar = m_currentView->frame()->statusbar(); + + if ( !statusBar ) + return; + + statusBar->message( text ); +} + +void KonqMainWindow::slotClearStatusText() +{ + if ( !m_currentView ) + return; + + KonqFrameStatusBar *statusBar = m_currentView->frame()->statusbar(); + + if ( !statusBar ) + return; + + statusBar->slotClear(); +} + +void KonqMainWindow::updateOpenWithActions() +{ + unplugActionList( "openwith" ); + + m_openWithActions.clear(); + + if (!kapp->authorizeTDEAction("openwith")) + return; + + const TDETrader::OfferList & services = m_currentView->appServiceOffers(); + TDETrader::OfferList::ConstIterator it = services.begin(); + TDETrader::OfferList::ConstIterator end = services.end(); + for (; it != end; ++it ) + { + TDEAction *action = new TDEAction( i18n( "Open with %1" ).arg( (*it)->name() ), 0, 0, (*it)->desktopEntryName().latin1() ); + action->setIcon( (*it)->icon() ); + + connect( action, TQT_SIGNAL( activated() ), + this, TQT_SLOT( slotOpenWith() ) ); + + m_openWithActions.append( action ); + } + if ( services.count() > 0 ) + { + m_openWithActions.append( new TDEActionSeparator ); + plugActionList( "openwith", m_openWithActions ); + } +} + +TQString KonqMainWindow::viewModeActionKey( KService::Ptr service ) +{ + TQString library = service->library(); + // Group all non-builtin views together + TQVariant builtIntoProp = service->property( "X-TDE-BrowserView-Built-Into" ); + if ( !builtIntoProp.isValid() || builtIntoProp.toString() != "konqueror" ) + library = "external"; + return library; +} + +void KonqMainWindow::updateViewModeActions() +{ + unplugViewModeActions(); + if ( m_viewModeMenu ) + { + TQPtrListIterator it( m_viewModeActions ); + for (; it.current(); ++it ) + it.current()->unplugAll(); + delete m_viewModeMenu; + } + + m_viewModeMenu = 0; + m_toolBarViewModeActions.clear(); + m_viewModeActions.clear(); + + // if we changed the viewmode to something new, then we have to + // make sure to also clear our [libiconview,liblistview]->service-for-viewmode + // map + if ( m_viewModeToolBarServices.count() > 0 && + !m_viewModeToolBarServices.begin().data()->serviceTypes().contains( m_currentView->serviceType() ) ) + { + // Save the current map to the config file, for later reuse + saveToolBarServicesMap(); + + m_viewModeToolBarServices.clear(); + } + + TDETrader::OfferList services = m_currentView->partServiceOffers(); + + if ( services.count() <= 1 ) + return; + + m_viewModeMenu = new TDEActionMenu( i18n( "&View Mode" ), TQT_TQOBJECT(this) ); + + // a temporary map, just like the m_viewModeToolBarServices map, but + // mapping to a KonqViewModeAction object. It's just temporary as we + // of use it to group the viewmode actions (iconview,multicolumnview, + // treeview, etc.) into to two groups -> icon/list + // Although I wrote this now only of icon/listview it has to work for + // any view, that's why it's so general :) + TQMap groupedServiceMap; + + // Another temporary map, the preferred service for each library (2 entries in our example) + TQMap preferredServiceMap; + + TDEConfig * config = TDEGlobal::config(); + config->setGroup( "ModeToolBarServices" ); + + TDETrader::OfferList::ConstIterator it = services.begin(); + TDETrader::OfferList::ConstIterator end = services.end(); + for (; it != end; ++it ) + { + TQVariant prop = (*it)->property( "X-TDE-BrowserView-Toggable" ); + if ( prop.isValid() && prop.toBool() ) // No toggable views in view mode + continue; + + TDERadioAction *action; + + TQString itname = (*it)->genericName(); + if (itname.isEmpty()) + itname = (*it)->name(); + + TQString icon = (*it)->icon(); + if ( icon != TQString::fromLatin1( "unknown" ) ) + // we *have* to specify a parent qobject, otherwise the exclusive group stuff doesn't work!(Simon) + action = new TDERadioAction( itname, icon, 0, TQT_TQOBJECT(this), (*it)->desktopEntryName().ascii() ); + else + action = new TDERadioAction( itname, 0, TQT_TQOBJECT(this), (*it)->desktopEntryName().ascii() ); + + action->setExclusiveGroup( "KonqMainWindow_ViewModes" ); + + connect( action, TQT_SIGNAL( toggled( bool ) ), + this, TQT_SLOT( slotViewModeToggle( bool ) ) ); + + m_viewModeActions.append( action ); + action->plug( m_viewModeMenu->popupMenu() ); + + const TQString library = viewModeActionKey( *it ); + + // look if we already have a KonqViewModeAction (in the toolbar) + // for this component + TQMap::Iterator mapIt = groupedServiceMap.find( library ); + + // if we don't have -> create one + if ( mapIt == groupedServiceMap.end() ) + { + // default service on this action: the current one (i.e. the first one) + TQString text = itname; + TQString icon = (*it)->icon(); + TQCString name = (*it)->desktopEntryName().latin1(); + //kdDebug(1202) << " Creating action for " << library << ". Default service " << itname << endl; + + // if we previously changed the viewmode (see slotViewModeToggle!) + // then we will want to use the previously used settings (previous as + // in before the actions got deleted) + TQMap::ConstIterator serviceIt = m_viewModeToolBarServices.find( library ); + if ( serviceIt != m_viewModeToolBarServices.end() ) + { + kdDebug(1202) << " Setting action for " << library << " to " << (*serviceIt)->name() << endl; + text = (*serviceIt)->genericName(); + if (text.isEmpty()) + text = (*serviceIt)->name(); + icon = (*serviceIt)->icon(); + name = (*serviceIt)->desktopEntryName().ascii(); + } else + { + // if we don't have it in the map, we should look for a setting + // for this library in the config file. + TQString preferredService = config->readEntry( library ); + if ( !preferredService.isEmpty() && name != preferredService.latin1() ) + { + //kdDebug(1202) << " Inserting into preferredServiceMap(" << library << ") : " << preferredService << endl; + // The preferred service isn't the current one, so remember to set it later + preferredServiceMap[ library ] = preferredService; + } + } + + KonqViewModeAction *tbAction = new KonqViewModeAction( text, + icon, + TQT_TQOBJECT(this), + name ); + + tbAction->setExclusiveGroup( "KonqMainWindow_ToolBarViewModes" ); + + tbAction->setChecked( action->isChecked() ); + + connect( tbAction, TQT_SIGNAL( toggled( bool ) ), + this, TQT_SLOT( slotViewModeToggle( bool ) ) ); + + m_toolBarViewModeActions.append( tbAction ); + + mapIt = groupedServiceMap.insert( library, tbAction ); + } + + // Check the actions (toolbar button and menu item) if they correspond to the current view + bool bIsCurrentView = (*it)->desktopEntryName() == m_currentView->service()->desktopEntryName(); + if ( bIsCurrentView ) + { + action->setChecked( true ); + } + + // Set the contents of the button from the current service, either if it's the current view + // or if it's our preferred service for this button (library) + if ( bIsCurrentView + || ( preferredServiceMap.contains( library ) && (*it)->desktopEntryName() == preferredServiceMap[ library ] ) ) + { + //kdDebug(1202) << " Changing action for " << library << " into service " << (*it)->name() << endl; + + TQString mapitname = (*it)->genericName(); + if (mapitname.isEmpty()) + mapitname = (*it)->name(); + (*mapIt)->setText( mapitname ); + (*mapIt)->setIcon( (*it)->icon() ); + (*mapIt)->setName( (*it)->desktopEntryName().ascii() ); // tricky... + preferredServiceMap.remove( library ); // The current view has priority over the saved settings + } + + // plug action also into the delayed popupmenu of appropriate toolbar action + action->plug( (*mapIt)->popupMenu() ); + } + +#ifndef NDEBUG + // Note that this can happen (map not empty) when a inode/directory view is removed, + // and remains in the TDEConfig file. + Q_ASSERT( preferredServiceMap.isEmpty() ); + TQMap::Iterator debugIt = preferredServiceMap.begin(); + TQMap::Iterator debugEnd = preferredServiceMap.end(); + for ( ; debugIt != debugEnd ; ++debugIt ) + kdDebug(1202) << " STILL IN preferredServiceMap : " << debugIt.key() << " | " << debugIt.data() << endl; +#endif + + if ( !m_currentView->isToggleView() ) // No view mode for toggable views + // (The other way would be to enforce a better servicetype for them, than Browser/View) + if ( /* already tested: services.count() > 1 && */ m_viewModeMenu ) + plugViewModeActions(); +} + +void KonqMainWindow::saveToolBarServicesMap() +{ + TQMap::ConstIterator serviceIt = m_viewModeToolBarServices.begin(); + TQMap::ConstIterator serviceEnd = m_viewModeToolBarServices.end(); + TDEConfig * config = TDEGlobal::config(); + config->setGroup( "ModeToolBarServices" ); + for ( ; serviceIt != serviceEnd ; ++serviceIt ) + config->writeEntry( serviceIt.key(), serviceIt.data()->desktopEntryName() ); + config->sync(); +} + +void KonqMainWindow::plugViewModeActions() +{ + TQPtrList lst; + lst.append( m_viewModeMenu ); + plugActionList( "viewmode", lst ); + // display the toolbar viewmode icons only for inode/directory, as here we have dedicated icons + if ( m_currentView && m_currentView->supportsServiceType( "inode/directory" ) ) + plugActionList( "viewmode_toolbar", m_toolBarViewModeActions ); +} + +void KonqMainWindow::unplugViewModeActions() +{ + unplugActionList( "viewmode" ); + unplugActionList( "viewmode_toolbar" ); +} + +KonqMainWindowIface* KonqMainWindow::dcopObject() +{ + return m_dcopObject; +} + +void KonqMainWindow::updateBookmarkBar() +{ + TDEToolBar * bar = static_cast( TQT_TQWIDGET(child( "bookmarkToolBar", "TDEToolBar" )) ); + + if (!bar) return; + + // hide if empty + if (m_paBookmarkBar && bar->count() == 0 ) + bar->hide(); + +} + +void KonqMainWindow::closeEvent( TQCloseEvent *e ) +{ + kdDebug(1202) << "KonqMainWindow::closeEvent begin" << endl; + // This breaks session management (the window is withdrawn in twin) + // so let's do this only when closed by the user. + if ( static_cast(kapp)->closedByUser() ) + { + if ( viewManager()->docContainer() && viewManager()->docContainer()->frameType()=="Tabs" ) + { + KonqFrameTabs* tabContainer = static_cast(viewManager()->docContainer()); + if ( tabContainer->count() > 1 ) + { + TDEConfig *config = TDEGlobal::config(); + TDEConfigGroupSaver cs( config, TQString::fromLatin1("Notification Messages") ); + + if ( !config->hasKey( "MultipleTabConfirm" ) ) + { + switch ( + KMessageBox::warningYesNoCancel( + this, + i18n("You have multiple tabs open in this window, " + "are you sure you want to quit?"), + i18n("Confirmation"), + KStdGuiItem::quit(), + KGuiItem(i18n( "C&lose Current Tab" ), "tab_remove"), + "MultipleTabConfirm" + ) + ) { + case KMessageBox::Yes : + break; + case KMessageBox::No : + { + e->ignore(); + slotRemoveTab(); + return; + } + break; + case KMessageBox::Cancel : + { + e->ignore(); + return; + } + } + } + } + + KonqView *originalView = m_currentView; + MapViews::ConstIterator it = m_mapViews.begin(); + MapViews::ConstIterator end = m_mapViews.end(); + for (; it != end; ++it ) { + KonqView *view = it.data(); + if (view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1) ) { + TQVariant prop = view->part()->property("modified"); + if (prop.isValid() && prop.toBool()) { + m_pViewManager->showTab( view ); + if ( KMessageBox::warningContinueCancel( this, + i18n("This tab contains changes that have not been submitted.\nClosing the window will discard these changes."), + i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"system-log-out"), "discardchangesclose") != KMessageBox::Continue ) + { + e->ignore(); + m_pViewManager->showTab( originalView ); + return; + } + } + } + } +// m_pViewManager->showTab( originalView ); + } + else if ( m_currentView && m_currentView->part() && + (m_currentView->part()->metaObject()->findProperty("modified") != -1) ) + { + TQVariant prop = m_currentView->part()->property("modified"); + if (prop.isValid() && prop.toBool()) + if ( KMessageBox::warningContinueCancel( this, + i18n("This page contains changes that have not been submitted.\nClosing the window will discard these changes."), + i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"system-log-out"), "discardchangesclose") != KMessageBox::Continue ) + { + e->ignore(); + return; + } + } + + // save size to have something to restore if the profile does not contain size + saveWindowSize(); + + hide(); + tqApp->flushX(); + } + // We're going to close - tell the parts + MapViews::ConstIterator it = m_mapViews.begin(); + MapViews::ConstIterator end = m_mapViews.end(); + for (; it != end; ++it ) + { + if ( (*it)->part() && (*it)->part()->widget() ) + TQApplication::sendEvent( (*it)->part()->widget(), e ); + } + KParts::MainWindow::closeEvent( e ); + if( isPreloaded() && !kapp->sessionSaving()) + { // queryExit() refused closing, hide instead + hide(); + } + kdDebug(1202) << "KonqMainWindow::closeEvent end" << endl; +} + +bool KonqMainWindow::queryExit() +{ + if( kapp->sessionSaving()) // *sigh* + return true; + return !stayPreloaded(); +} + +void KonqMainWindow::setIcon( const TQPixmap& pix ) +{ + KParts::MainWindow::setIcon( pix ); + + TQPixmap big = pix; + + TQString url = m_combo->currentText(); + + if ( !url.isEmpty() ) + big = KonqPixmapProvider::self()->pixmapFor( url, TDEIcon::SizeMedium ); + + KWin::setIcons( winId(), big, pix ); +} + +void KonqMainWindow::slotIntro() +{ + openURL( 0L, KURL("about:konqueror") ); +} + +void KonqMainWindow::goURL() +{ + TQLineEdit *lineEdit = m_combo->lineEdit(); + if ( !lineEdit ) + return; + + TQKeyEvent event( TQEvent::KeyPress, Key_Return, '\n', 0 ); + TQApplication::sendEvent( lineEdit, &event ); +} + +void KonqMainWindow::slotLocationLabelActivated() +{ + focusLocationBar(); + m_combo->lineEdit()->selectAll(); +} + +void KonqMainWindow::slotOpenURL( const KURL& url ) +{ + openURL( 0L, url ); +} + +bool KonqMainWindow::sidebarVisible() const +{ +TDEAction *a = m_toggleViewGUIClient->action("konq_sidebartng"); +return (a && static_cast(a)->isChecked()); +} + +void KonqMainWindow::slotAddWebSideBar(const KURL& url, const TQString& name) +{ + if (url.url().isEmpty() && name.isEmpty()) + return; + + kdDebug(1202) << "Requested to add URL " << url << " [" << name << "] to the sidebar!" << endl; + + TDEAction *a = m_toggleViewGUIClient->action("konq_sidebartng"); + if (!a) { + KMessageBox::sorry(0L, i18n("Your sidebar is not functional or unavailable. A new entry cannot be added."), i18n("Web Sidebar")); + return; + } + + int rc = KMessageBox::questionYesNo(0L, + i18n("Add new web extension \"%1\" to your sidebar?") + .arg(name.isEmpty() ? name : url.prettyURL()), + i18n("Web Sidebar"),i18n("Add"),i18n("Do Not Add")); + + if (rc == KMessageBox::Yes) { + // Show the sidebar + if (!static_cast(a)->isChecked()) { + a->activate(); + } + + // Tell it to add a new panel + MapViews::ConstIterator it; + for (it = viewMap().begin(); it != viewMap().end(); ++it) { + KonqView *view = it.data(); + if (view) { + KService::Ptr svc = view->service(); + if (svc->desktopEntryName() == "konq_sidebartng") { + emit view->browserExtension()->addWebSideBar(url, name); + break; + } + } + } + } +} + +void KonqMainWindow::bookmarksIntoCompletion( const KBookmarkGroup& group ) +{ + static const TQString& http = TDEGlobal::staticQString( "http" ); + static const TQString& ftp = TDEGlobal::staticQString( "ftp" ); + + if ( group.isNull() ) + return; + + for ( KBookmark bm = group.first(); + !bm.isNull(); bm = group.next(bm) ) { + if ( bm.isGroup() ) { + bookmarksIntoCompletion( bm.toGroup() ); + continue; + } + + KURL url = bm.url(); + if ( !url.isValid() ) + continue; + + TQString u = url.prettyURL(); + s_pCompletion->addItem( u ); + + if ( url.isLocalFile() ) + s_pCompletion->addItem( url.path() ); + else if ( url.protocol() == http ) + s_pCompletion->addItem( u.mid( 7 )); + else if ( url.protocol() == ftp && + url.host().startsWith( ftp ) ) + s_pCompletion->addItem( u.mid( 6 ) ); + } +} + +void KonqMainWindow::connectActionCollection( TDEActionCollection *coll ) +{ + connect( coll, TQT_SIGNAL( actionStatusText( const TQString & ) ), + this, TQT_SLOT( slotActionStatusText( const TQString & ) ) ); + connect( coll, TQT_SIGNAL( clearStatusText() ), + this, TQT_SLOT( slotClearStatusText() ) ); +} + +void KonqMainWindow::disconnectActionCollection( TDEActionCollection *coll ) +{ + disconnect( coll, TQT_SIGNAL( actionStatusText( const TQString & ) ), + this, TQT_SLOT( slotActionStatusText( const TQString & ) ) ); + disconnect( coll, TQT_SIGNAL( clearStatusText() ), + this, TQT_SLOT( slotClearStatusText() ) ); +} + +// +// the smart popup completion code , +// + +// prepend http://www. or http:// if there's no protocol in 's' +// used only when there are no completion matches +static TQString hp_tryPrepend( const TQString& s ) +{ + if( s.isEmpty() || s[ 0 ] == '/' ) + return TQString::null; + for( unsigned int pos = 0; + pos < s.length() - 2; // 4 = ://x + ++pos ) + { + if( s[ pos ] == ':' && s[ pos + 1 ] == '/' && s[ pos + 2 ] == '/' ) + return TQString::null; + if( !s[ pos ].isLetter() ) + break; + } + return ( s.startsWith( "www." ) ? "http://" : "http://www." ) + s; +} + + +static void hp_removeDupe( TDECompletionMatches& l, const TQString& dupe, + TDECompletionMatches::Iterator it_orig ) +{ + for( TDECompletionMatches::Iterator it = l.begin(); + it != l.end(); + ) { + if( it == it_orig ) { + ++it; + continue; + } + if( (*it).value() == dupe ) { + (*it_orig).first = kMax( (*it_orig).first, (*it).index()); + it = l.remove( it ); + continue; + } + ++it; + } +} + +// remove duplicates like 'http://www.kde.org' and 'http://www.kde.org/' +// (i.e. the trailing slash) +// some duplicates are also created by prepending protocols +static void hp_removeDuplicates( TDECompletionMatches& l ) +{ + TQString http = "http://"; + TQString ftp = "ftp://ftp."; + TQString file = "file:"; + TQString file2 = "file://"; + l.removeDuplicates(); + for( TDECompletionMatches::Iterator it = l.begin(); + it != l.end(); + ++it ) { + TQString str = (*it).value(); + if( str.startsWith( http )) { + if( str.find( '/', 7 ) < 0 ) { // http://something + hp_removeDupe( l, str + '/', it ); + hp_removeDupe( l, str.mid( 7 ) + '/', it ); + } else if( str[ str.length() - 1 ] == '/' ) { + hp_removeDupe( l, str.left( str.length() - 1 ), it ); + hp_removeDupe( l, str.left( str.length() - 1 ).mid( 7 ), it ); + } + hp_removeDupe( l, str.mid( 7 ), it ); + } + else if( str.startsWith( ftp )) // ftp://ftp. + hp_removeDupe( l, str.mid( 6 ), it ); // remove dupes without ftp:// + else if( str.startsWith( file2 )) + hp_removeDupe( l, str.mid( 7 ), it ); // remove dupes without file:// + else if( str.startsWith( file )) + hp_removeDupe( l, str.mid( 5 ), it ); // remove dupes without file: + } +} + +static void hp_removeCommonPrefix( TDECompletionMatches& l, const TQString& prefix ) +{ + for( TDECompletionMatches::Iterator it = l.begin(); + it != l.end(); + ) { + if( (*it).value().startsWith( prefix )) { + it = l.remove( it ); + continue; + } + ++it; + } +} + +// don't include common prefixes like 'http://', i.e. when s == 'h', include +// http://hotmail.com but don't include everything just starting with 'http://' +static void hp_checkCommonPrefixes( TDECompletionMatches& matches, const TQString& s ) +{ + static const char* const prefixes[] = { + "http://", + "https://", + "www.", + "ftp://", + "http://www.", + "https://www.", + "ftp://ftp.", + "file:", + "file://", + NULL }; + for( const char* const *pos = prefixes; + *pos != NULL; + ++pos ) { + TQString prefix = *pos; + if( prefix.startsWith( s )) { + hp_removeCommonPrefix( matches, prefix ); + } + } +} + +TQStringList KonqMainWindow::historyPopupCompletionItems( const TQString& s) +{ + const TQString http = "http://"; + const TQString https = "https://"; + const TQString www = "http://www."; + const TQString wwws = "https://www."; + const TQString ftp = "ftp://"; + const TQString ftpftp = "ftp://ftp."; + const TQString file = "file:"; // without /, because people enter /usr etc. + const TQString file2 = "file://"; + if( s.isEmpty()) + return TQStringList(); + TDECompletionMatches matches= s_pCompletion->allWeightedMatches( s ); + hp_checkCommonPrefixes( matches, s ); + bool checkDuplicates = false; + if ( !s.startsWith( ftp ) ) { + matches += s_pCompletion->allWeightedMatches( ftp + s ); + if( TQString( "ftp." ).startsWith( s )) + hp_removeCommonPrefix( matches, ftpftp ); + checkDuplicates = true; + } + if ( !s.startsWith( https ) ) { + matches += s_pCompletion->allWeightedMatches( https + s ); + if( TQString( "www." ).startsWith( s )) + hp_removeCommonPrefix( matches, wwws ); + checkDuplicates = true; + } + if ( !s.startsWith( http )) { + matches += s_pCompletion->allWeightedMatches( http + s ); + if( TQString( "www." ).startsWith( s )) + hp_removeCommonPrefix( matches, www ); + checkDuplicates = true; + } + if ( !s.startsWith( www ) ) { + matches += s_pCompletion->allWeightedMatches( www + s ); + checkDuplicates = true; + } + if ( !s.startsWith( wwws ) ) { + matches += s_pCompletion->allWeightedMatches( wwws + s ); + checkDuplicates = true; + } + if ( !s.startsWith( ftpftp ) ) { + matches += s_pCompletion->allWeightedMatches( ftpftp + s ); + checkDuplicates = true; + } + if ( !s.startsWith( file ) ) { + matches += s_pCompletion->allWeightedMatches( file + s ); + checkDuplicates = true; + } + if ( !s.startsWith( file2 ) ) { + matches += s_pCompletion->allWeightedMatches( file2 + s ); + checkDuplicates = true; + } + if( checkDuplicates ) + hp_removeDuplicates( matches ); + TQStringList items = matches.list(); + if( items.count() == 0 + && !s.contains( ':' ) && s[ 0 ] != '/' ) + { + TQString pre = hp_tryPrepend( s ); + if( !pre.isNull()) + items += pre; + } + return items; +} + +#ifndef NDEBUG +void KonqMainWindow::dumpViewList() +{ + MapViews::Iterator end = m_mapViews.end(); + + kdDebug(1202) << m_mapViews.count() << "Views" << endl; + + for (MapViews::Iterator it = m_mapViews.begin(); it != end; it++) + { + kdDebug(1202) << it.data() << endl; + } +} +#endif + +// KonqFrameContainerBase implementation BEGIN + +/** + * Call this after inserting a new frame into the splitter. + */ +void KonqMainWindow::insertChildFrame( KonqFrameBase * frame, int /*index*/ ) +{ + m_pChildFrame = frame; + m_pActiveChild = frame; + frame->setParentContainer(this); + setCentralWidget( frame->widget() ); +} + +/** + * Call this before deleting one of our children. + */ +void KonqMainWindow::removeChildFrame( KonqFrameBase * /*frame*/ ) +{ + m_pChildFrame = 0L; + m_pActiveChild = 0L; +} + +void KonqMainWindow::saveConfig( TDEConfig* config, const TQString &prefix, bool saveURLs, KonqFrameBase* docContainer, int id, int depth ) { if( m_pChildFrame ) m_pChildFrame->saveConfig( config, prefix, saveURLs, docContainer, id, depth); } + +void KonqMainWindow::copyHistory( KonqFrameBase *other ) { if( m_pChildFrame ) m_pChildFrame->copyHistory( other ); } + +void KonqMainWindow::printFrameInfo( const TQString &spaces ) { if( m_pChildFrame ) m_pChildFrame->printFrameInfo( spaces ); } + +void KonqMainWindow::reparentFrame( TQWidget* /*parent*/, + const TQPoint & /*p*/, bool /*showIt*/ ) { return; } + +KonqFrameContainerBase* KonqMainWindow::parentContainer()const { return 0L; } +void KonqMainWindow::setParentContainer(KonqFrameContainerBase* /*parent*/) { return; } + +void KonqMainWindow::setTitle( const TQString &/*title*/ , TQWidget* /*sender*/) { return; } +void KonqMainWindow::setTabIcon( const KURL &/*url*/, TQWidget* /*sender*/ ) { return; } + +TQWidget* KonqMainWindow::widget() { return this; } + +void KonqMainWindow::listViews( ChildViewList *viewList ) { if( m_pChildFrame ) m_pChildFrame->listViews( viewList ); } + +TQCString KonqMainWindow::frameType() { return TQCString("MainWindow"); } + +KonqFrameBase* KonqMainWindow::childFrame()const { return m_pChildFrame; } + +void KonqMainWindow::setActiveChild( KonqFrameBase* /*activeChild*/ ) { return; } + +bool KonqMainWindow::isMimeTypeAssociatedWithSelf( const TQString &mimeType ) +{ + return isMimeTypeAssociatedWithSelf( mimeType, KServiceTypeProfile::preferredService( mimeType, "Application" ) ); +} + +bool KonqMainWindow::isMimeTypeAssociatedWithSelf( const TQString &/*mimeType*/, const KService::Ptr &offer ) +{ + // Prevention against user stupidity : if the associated app for this mimetype + // is konqueror/kfmclient, then we'll loop forever. So we have to + // 1) force embedding first, if that works we're ok + // 2) check what KRun is going to do before calling it. + return ( offer && ( offer->desktopEntryName() == "konqueror" || + offer->exec().stripWhiteSpace().startsWith( "kfmclient" ) ) ); +} + +// KonqFrameContainerBase implementation END + +void KonqMainWindow::setPreloadedFlag( bool preloaded ) +{ + if( s_preloaded == preloaded ) + return; + s_preloaded = preloaded; + if( s_preloaded ) + { + kapp->disableSessionManagement(); // dont restore preloaded konqy's + return; // was registered before calling this + } + delete s_preloadedWindow; // preloaded state was abandoned without reusing the window + s_preloadedWindow = NULL; + kapp->enableSessionManagement(); // enable SM again + DCOPRef ref( "kded", "konqy_preloader" ); + ref.send( "unregisterPreloadedKonqy", kapp->dcopClient()->appId()); +} + +void KonqMainWindow::setPreloadedWindow( KonqMainWindow* window ) +{ + s_preloadedWindow = window; + if( window == NULL ) + return; + window->viewManager()->clear(); + TDEIO::Scheduler::unregisterWindow( TQT_TQOBJECT(window) ); +} + +// used by preloading - this KonqMainWindow will be reused, reset everything +// that won't be reset by loading a profile +void KonqMainWindow::resetWindow() +{ + char data[ 1 ]; + // empty append to get current X timestamp + TQWidget tmp_widget; + XChangeProperty( tqt_xdisplay(), tmp_widget.winId(), XA_WM_CLASS, XA_STRING, 8, + PropModeAppend, (unsigned char*) &data, 0 ); + XEvent ev; + XWindowEvent( tqt_xdisplay(), tmp_widget.winId(), PropertyChangeMask, &ev ); + long x_time = ev.xproperty.time; + // bad hack - without updating the _TDE_NET_WM_USER_CREATION_TIME property, + // KWin will apply don't_steal_focus to this window, and will not make it active + // (shows mainly with 'konqueror --preload') + static Atom atom = XInternAtom( tqt_xdisplay(), "_TDE_NET_WM_USER_CREATION_TIME", False ); + XChangeProperty( tqt_xdisplay(), winId(), atom, XA_CARDINAL, 32, + PropModeReplace, (unsigned char *) &x_time, 1); + SET_QT_X_USER_TIME(CurrentTime); // won't have _NET_WM_USER_TIME set +#if !KDE_IS_VERSION( 3, 2, 90 ) // _KDE_NET_USER_TIME is obsolete + static Atom atom2 = XInternAtom( tqt_xdisplay(), "_KDE_NET_USER_TIME", False ); + timeval tv; + gettimeofday( &tv, NULL ); + unsigned long now = tv.tv_sec * 10 + tv.tv_usec / 100000; + XChangeProperty(tqt_xdisplay(), winId(), atom2, XA_CARDINAL, + 32, PropModeReplace, (unsigned char *)&now, 1); +#endif + static Atom atom3 = XInternAtom( tqt_xdisplay(), "_NET_WM_USER_TIME", False ); + XDeleteProperty( tqt_xdisplay(), winId(), atom3 ); +// Qt remembers the iconic state if the window was withdrawn while on another virtual desktop + clearWState( WState_Minimized ); + ignoreInitialGeometry(); + kapp->setTopWidget( this ); // set again the default window icon +} + +bool KonqMainWindow::event( TQEvent* e ) +{ + if( e->type() == TQEvent::DeferredDelete ) + { + // since the preloading code tries to reuse KonqMainWindow, + // the last window shouldn't be really deleted, but only hidden + // deleting WDestructiveClose windows is done using deleteLater(), + // so catch TQEvent::DefferedDelete and check if this window should stay + if( stayPreloaded()) + { + setWFlags(WDestructiveClose); // was reset before deleteLater() + return true; // no deleting + } + } + return KParts::MainWindow::event( e ); +} + +bool KonqMainWindow::stayPreloaded() +{ + // last window? + if( mainWindowList()->count() > 1 ) + return false; + // not running in full KDE environment? + if( getenv( "TDE_FULL_SESSION" ) == NULL || getenv( "TDE_FULL_SESSION" )[ 0 ] == '\0' ) + return false; + // not the same user like the one running the session (most likely we're run via sudo or something) + if( getenv( "TDE_SESSION_UID" ) != NULL && uid_t( atoi( getenv( "TDE_SESSION_UID" ))) != getuid()) + return false; + if( KonqSettings::maxPreloadCount() == 0 ) + return false; + viewManager()->clear(); // reduce resource usage before checking it + if( !checkPreloadResourceUsage()) + return false; + DCOPRef ref( "kded", "konqy_preloader" ); + if( !ref.callExt( "registerPreloadedKonqy", DCOPRef::NoEventLoop, 5000, + kapp->dcopClient()->appId(), tqt_xscreen())) + { + return false; + } + KonqMainWindow::setPreloadedFlag( true ); + kdDebug(1202) << "Konqy kept for preloading :" << kapp->dcopClient()->appId() << endl; + KonqMainWindow::setPreloadedWindow( this ); + return true; +} + +// try to avoid staying running when leaking too much memory +// this is checked by using mallinfo() and comparing +// memory usage during konqy startup and now, if the difference +// is too large -> leaks -> quit +// also, if this process is running for too long, or has been +// already reused too many times -> quit, just in case +bool KonqMainWindow::checkPreloadResourceUsage() +{ + if( +#ifndef NDEBUG + isatty( STDIN_FILENO ) || +#endif + isatty( STDOUT_FILENO ) || isatty( STDERR_FILENO )) + { + kdDebug(1202) << "Running from tty, not keeping for preloading" << endl; + return false; + } + int limit; + int usage = current_memory_usage( &limit ); + kdDebug(1202) << "Memory usage increase: " << ( usage - s_initialMemoryUsage ) + << " (" << usage << "/" << s_initialMemoryUsage << "), increase limit: " << limit << endl; + int max_allowed_usage = s_initialMemoryUsage + limit; + if( usage > max_allowed_usage ) // too much memory used? + { + kdDebug(1202) << "Not keeping for preloading due to high memory usage" << endl; + return false; + } + // working memory usage test ( usage != 0 ) makes others less strict + if( ++s_preloadUsageCount > ( usage != 0 ? 100 : 10 )) // reused too many times? + { + kdDebug(1202) << "Not keeping for preloading due to high usage count" << endl; + return false; + } + if( time( NULL ) > s_startupTime + 60 * 60 * ( usage != 0 ? 4 : 1 )) // running for too long? + { + kdDebug(1202) << "Not keeping for preloading due to long usage time" << endl; + return false; + } + return true; +} + +static int current_memory_usage( int* limit ) +{ +#ifdef __linux__ +// Check whole memory usage - VmSize + TQFile f( TQCString().sprintf( "/proc/%i/statm", getpid())); + if( f.open( IO_ReadOnly )) + { + TQString line; + if( f.readLine( line, 1024 ) > 0 ) + { + line = line.stripWhiteSpace(); + int usage = line.section( ' ', 0, 0 ).toInt(); + if( usage > 0 ) + { + int pagesize = sysconf (_SC_PAGE_SIZE); + if( pagesize < 0 ) + pagesize = 4096; + if( limit != NULL ) + *limit = 16 * 1024 * 1024; + return usage * pagesize; + } + } + } + kdWarning() << "Couldn't read VmSize from /proc/*/statm." << endl; +#endif +// Check malloc() usage - very imprecise, but better than nothing. + int usage_sum = 0; +#if defined(KDE_MALLINFO_STDLIB) || defined(KDE_MALLINFO_MALLOC) + // ugly hack for tdecore/malloc + extern int kde_malloc_is_used; + free( calloc( 4, 4 )); // trigger setting kde_malloc_is_used + if( kde_malloc_is_used ) + { + struct mallinfo m = mallinfo(); + usage_sum = m.hblkhd + m.uordblks; + } + else + { + struct mallinfo m = mallinfo(); +#ifdef KDE_MALLINFO_FIELD_hblkhd + usage_sum += m.hblkhd; +#endif +#ifdef KDE_MALLINFO_FIELD_uordblks + usage_sum += m.uordblks; +#endif +#ifdef KDE_MALLINFO_FIELD_usmblks + usage_sum += m.usmblks; +#endif + } + // unlike /proc , this doesn't include things like size of dlopened modules, + // and also doesn't include malloc overhead + if( limit != NULL ) + *limit = 6 * 1024 * 1024; +#endif + return usage_sum; +} + +void KonqMainWindow::saveWindowSize() const +{ + TQString savedGroup = TDEGlobal::config()->group(); + TDEGlobal::config()->setGroup( "KonqMainWindow_Size" ); + + KParts::MainWindow::saveWindowSize( TDEGlobal::config() ); + + TDEGlobal::config()->setGroup( savedGroup ); + TDEGlobal::config()->sync(); +} + +void KonqMainWindow::restoreWindowSize() +{ + TQString savedGroup = TDEGlobal::config()->group(); + TDEGlobal::config()->setGroup( "KonqMainWindow_Size" ); + + KParts::MainWindow::restoreWindowSize( TDEGlobal::config() ); + + TDEGlobal::config()->setGroup( savedGroup ); +} + + +#include "konq_mainwindow.moc" +#include "konq_mainwindow_p.moc" diff --git a/konqueror/konq_misc.cc b/konqueror/konq_misc.cc deleted file mode 100644 index b2f0ad47f..000000000 --- a/konqueror/konq_misc.cc +++ /dev/null @@ -1,281 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 1998, 1999 David Faure - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "konq_misc.h" -#include "konq_mainwindow.h" -#include "konq_viewmgr.h" -#include "konq_view.h" - -/********************************************** - * - * KonqMisc - * - **********************************************/ - -// Terminates fullscreen-mode for any full-screen window on the current desktop -void KonqMisc::abortFullScreenMode() -{ - TQPtrList *mainWindows = KonqMainWindow::mainWindowList(); - if ( mainWindows ) - { - TQPtrListIterator it( *mainWindows ); - for (; it.current(); ++it ) - { - if ( it.current()->fullScreenMode() ) - { - KWin::WindowInfo info = KWin::windowInfo( it.current()->winId(), NET::WMDesktop ); - if ( info.valid() && info.isOnCurrentDesktop() ) - it.current()->showNormal(); - } - } - } -} - -// #### this can probably be removed -KonqMainWindow * KonqMisc::createSimpleWindow( const KURL & _url, const TQString &frameName ) -{ - abortFullScreenMode(); - - // If _url is 0L, open $HOME [this doesn't happen anymore] - KURL url; - if (_url.isEmpty()) - url.setPath(TQDir::homeDirPath()); - else - url = _url; - - KonqMainWindow *win = new KonqMainWindow( KURL(), false ); - win->setInitialFrameName( frameName ); - win->openURL( 0L, url ); - win->show(); - - return win; -} - -KonqMainWindow * KonqMisc::createSimpleWindow( const KURL & url, const KParts::URLArgs &args, bool tempFile ) -{ - abortFullScreenMode(); - - KonqOpenURLRequest req; - req.args = args; - req.tempFile = tempFile; - KonqMainWindow *win = new KonqMainWindow( KURL(), false ); - win->openURL( 0L, url, TQString::null, req ); - win->show(); - - return win; -} - -KonqMainWindow * KonqMisc::createNewWindow( const KURL &url, const KParts::URLArgs &args, bool forbidUseHTML, TQStringList filesToSelect, bool tempFile, bool openURL ) -{ - kdDebug() << "KonqMisc::createNewWindow url=" << url << endl; - - // For HTTP or html files, use the web browsing profile, otherwise use filemanager profile - TQString profileName = (!(KProtocolInfo::supportsListing(url)) || - KMimeType::findByURL(url)->name() == "text/html") - ? "webbrowsing" : "filemanagement"; - - TQString profile = locate( "data", TQString::fromLatin1("konqueror/profiles/") + profileName ); - return createBrowserWindowFromProfile(profile, profileName, - url, args, - forbidUseHTML, filesToSelect, tempFile, openURL ); -} - -KonqMainWindow * KonqMisc::createBrowserWindowFromProfile( const TQString &path, const TQString &filename, const KURL &url, const KParts::URLArgs &args, bool forbidUseHTML, const TQStringList& filesToSelect, bool tempFile, bool openURL ) -{ - kdDebug(1202) << "void KonqMisc::createBrowserWindowFromProfile() " << endl; - kdDebug(1202) << "path=" << path << ",filename=" << filename << ",url=" << url.prettyURL() << endl; - abortFullScreenMode(); - - KonqMainWindow * mainWindow; - if ( path.isEmpty() ) - { - // The profile doesn't exit -> creating a simple window - mainWindow = createSimpleWindow( url, args, tempFile ); - if ( forbidUseHTML ) - mainWindow->setShowHTML( false ); - } - else if( KonqMainWindow::isPreloaded() && KonqMainWindow::preloadedWindow() != NULL ) - { - mainWindow = KonqMainWindow::preloadedWindow(); - TDEStartupInfo::setWindowStartupId( mainWindow->winId(), kapp->startupId()); - KonqMainWindow::setPreloadedWindow( NULL ); - KonqMainWindow::setPreloadedFlag( false ); - mainWindow->resetWindow(); - mainWindow->reparseConfiguration(); - if( forbidUseHTML ) - mainWindow->setShowHTML( false ); - KonqOpenURLRequest req; - req.args = args; - req.filesToSelect = filesToSelect; - req.tempFile = tempFile; - mainWindow->viewManager()->loadViewProfile( path, filename, url, req, true ); - } - else - { - TDEConfig cfg( path, true ); - cfg.setDollarExpansion( true ); - cfg.setGroup( "Profile" ); - TQString xmluiFile=cfg.readEntry("XMLUIFile","konqueror.rc"); - - mainWindow = new KonqMainWindow( KURL(), false, 0, xmluiFile ); - if ( forbidUseHTML ) - mainWindow->setShowHTML( false ); - KonqOpenURLRequest req; - req.args = args; - req.filesToSelect = filesToSelect; - req.tempFile = tempFile; - mainWindow->viewManager()->loadViewProfile( cfg, filename, url, req, false, openURL ); - } - mainWindow->setInitialFrameName( args.frameName ); - mainWindow->show(); - return mainWindow; -} - -KonqMainWindow * KonqMisc::newWindowFromHistory( KonqView* view, int steps ) -{ - int oldPos = view->historyPos(); - int newPos = oldPos + steps; - - const HistoryEntry * he = view->historyAt(newPos); - if(!he) - return 0L; - - KonqMainWindow* mainwindow = createNewWindow(he->url, KParts::URLArgs(), - false, TQStringList(), false, /*openURL*/false); - if(!mainwindow) - return 0L; - KonqView* newView = mainwindow->currentView(); - - if(!newView) - return 0L; - - newView->copyHistory(view); - newView->setHistoryPos(newPos); - newView->restoreHistory(); - return mainwindow; -} - -TQString KonqMisc::konqFilteredURL( TQWidget* parent, const TQString& _url, const TQString& _path ) -{ - if ( !_url.startsWith( "about:" ) ) // Don't filter "about:" URLs - { - KURIFilterData data = _url; - - if( !_path.isEmpty() ) - data.setAbsolutePath(_path); - - // We do not want to the filter to check for executables - // from the location bar. - data.setCheckForExecutables (false); - - if( KURIFilter::self()->filterURI( data ) ) - { - if( data.uriType() == KURIFilterData::ERROR && !data.errorMsg().isEmpty() ) - { - KMessageBox::sorry( parent, i18n( data.errorMsg().utf8() ) ); - return TQString::null; - } - else - return data.uri().url(); - } - } - else if ( _url.startsWith( "about:" ) && _url != "about:blank" ) { - // We can't use "about:" as it is, KURL doesn't parse it. - if (_url == "about:plugins") - return "about:plugins"; - return "about:konqueror"; - } - return _url; // return the original url if it cannot be filtered. -} - -KonqDraggableLabel::KonqDraggableLabel( KonqMainWindow* mw, const TQString& text ) - : TQLabel( text, 0L, "tde toolbar widget" ) // Use this name for it to be styled! - , m_mw(mw) -{ - setBackgroundMode( TQt::PaletteButton ); - setAlignment( (TQApplication::reverseLayout() ? Qt::AlignRight : Qt::AlignLeft) | - Qt::AlignVCenter | TQt::ShowPrefix ); - setAcceptDrops(true); - adjustSize(); - validDrag = false; -} - -void KonqDraggableLabel::mousePressEvent( TQMouseEvent * ev ) -{ - validDrag = true; - startDragPos = ev->pos(); -} - -void KonqDraggableLabel::mouseMoveEvent( TQMouseEvent * ev ) -{ - if ((startDragPos - ev->pos()).manhattanLength() > TQApplication::startDragDistance()) - { - validDrag = false; - if ( m_mw->currentView() ) - { - KURL::List lst; - lst.append( m_mw->currentView()->url() ); - TQDragObject * drag = new KURLDrag( lst, m_mw ); - drag->setPixmap( KMimeType::pixmapForURL( lst.first(), 0, TDEIcon::Small ) ); - drag->dragCopy(); - } - } -} - -void KonqDraggableLabel::mouseReleaseEvent( TQMouseEvent * ) -{ - validDrag = false; -} - -void KonqDraggableLabel::dragEnterEvent( TQDragEnterEvent *ev ) -{ - if ( KURLDrag::canDecode( ev ) ) - ev->acceptAction(); -} - -void KonqDraggableLabel::dropEvent( TQDropEvent* ev ) -{ - _savedLst.clear(); - if ( KURLDrag::decode( ev, _savedLst ) ) { - TQTimer::singleShot(0, this, TQT_SLOT(delayedOpenURL())); - } -} - -void KonqDraggableLabel::delayedOpenURL() -{ - m_mw->openURL( 0L, _savedLst.first() ); -} - -#include "konq_misc.moc" diff --git a/konqueror/konq_misc.cpp b/konqueror/konq_misc.cpp new file mode 100644 index 000000000..b2f0ad47f --- /dev/null +++ b/konqueror/konq_misc.cpp @@ -0,0 +1,281 @@ +/* This file is part of the KDE project + Copyright (C) 1998, 1999 David Faure + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "konq_misc.h" +#include "konq_mainwindow.h" +#include "konq_viewmgr.h" +#include "konq_view.h" + +/********************************************** + * + * KonqMisc + * + **********************************************/ + +// Terminates fullscreen-mode for any full-screen window on the current desktop +void KonqMisc::abortFullScreenMode() +{ + TQPtrList *mainWindows = KonqMainWindow::mainWindowList(); + if ( mainWindows ) + { + TQPtrListIterator it( *mainWindows ); + for (; it.current(); ++it ) + { + if ( it.current()->fullScreenMode() ) + { + KWin::WindowInfo info = KWin::windowInfo( it.current()->winId(), NET::WMDesktop ); + if ( info.valid() && info.isOnCurrentDesktop() ) + it.current()->showNormal(); + } + } + } +} + +// #### this can probably be removed +KonqMainWindow * KonqMisc::createSimpleWindow( const KURL & _url, const TQString &frameName ) +{ + abortFullScreenMode(); + + // If _url is 0L, open $HOME [this doesn't happen anymore] + KURL url; + if (_url.isEmpty()) + url.setPath(TQDir::homeDirPath()); + else + url = _url; + + KonqMainWindow *win = new KonqMainWindow( KURL(), false ); + win->setInitialFrameName( frameName ); + win->openURL( 0L, url ); + win->show(); + + return win; +} + +KonqMainWindow * KonqMisc::createSimpleWindow( const KURL & url, const KParts::URLArgs &args, bool tempFile ) +{ + abortFullScreenMode(); + + KonqOpenURLRequest req; + req.args = args; + req.tempFile = tempFile; + KonqMainWindow *win = new KonqMainWindow( KURL(), false ); + win->openURL( 0L, url, TQString::null, req ); + win->show(); + + return win; +} + +KonqMainWindow * KonqMisc::createNewWindow( const KURL &url, const KParts::URLArgs &args, bool forbidUseHTML, TQStringList filesToSelect, bool tempFile, bool openURL ) +{ + kdDebug() << "KonqMisc::createNewWindow url=" << url << endl; + + // For HTTP or html files, use the web browsing profile, otherwise use filemanager profile + TQString profileName = (!(KProtocolInfo::supportsListing(url)) || + KMimeType::findByURL(url)->name() == "text/html") + ? "webbrowsing" : "filemanagement"; + + TQString profile = locate( "data", TQString::fromLatin1("konqueror/profiles/") + profileName ); + return createBrowserWindowFromProfile(profile, profileName, + url, args, + forbidUseHTML, filesToSelect, tempFile, openURL ); +} + +KonqMainWindow * KonqMisc::createBrowserWindowFromProfile( const TQString &path, const TQString &filename, const KURL &url, const KParts::URLArgs &args, bool forbidUseHTML, const TQStringList& filesToSelect, bool tempFile, bool openURL ) +{ + kdDebug(1202) << "void KonqMisc::createBrowserWindowFromProfile() " << endl; + kdDebug(1202) << "path=" << path << ",filename=" << filename << ",url=" << url.prettyURL() << endl; + abortFullScreenMode(); + + KonqMainWindow * mainWindow; + if ( path.isEmpty() ) + { + // The profile doesn't exit -> creating a simple window + mainWindow = createSimpleWindow( url, args, tempFile ); + if ( forbidUseHTML ) + mainWindow->setShowHTML( false ); + } + else if( KonqMainWindow::isPreloaded() && KonqMainWindow::preloadedWindow() != NULL ) + { + mainWindow = KonqMainWindow::preloadedWindow(); + TDEStartupInfo::setWindowStartupId( mainWindow->winId(), kapp->startupId()); + KonqMainWindow::setPreloadedWindow( NULL ); + KonqMainWindow::setPreloadedFlag( false ); + mainWindow->resetWindow(); + mainWindow->reparseConfiguration(); + if( forbidUseHTML ) + mainWindow->setShowHTML( false ); + KonqOpenURLRequest req; + req.args = args; + req.filesToSelect = filesToSelect; + req.tempFile = tempFile; + mainWindow->viewManager()->loadViewProfile( path, filename, url, req, true ); + } + else + { + TDEConfig cfg( path, true ); + cfg.setDollarExpansion( true ); + cfg.setGroup( "Profile" ); + TQString xmluiFile=cfg.readEntry("XMLUIFile","konqueror.rc"); + + mainWindow = new KonqMainWindow( KURL(), false, 0, xmluiFile ); + if ( forbidUseHTML ) + mainWindow->setShowHTML( false ); + KonqOpenURLRequest req; + req.args = args; + req.filesToSelect = filesToSelect; + req.tempFile = tempFile; + mainWindow->viewManager()->loadViewProfile( cfg, filename, url, req, false, openURL ); + } + mainWindow->setInitialFrameName( args.frameName ); + mainWindow->show(); + return mainWindow; +} + +KonqMainWindow * KonqMisc::newWindowFromHistory( KonqView* view, int steps ) +{ + int oldPos = view->historyPos(); + int newPos = oldPos + steps; + + const HistoryEntry * he = view->historyAt(newPos); + if(!he) + return 0L; + + KonqMainWindow* mainwindow = createNewWindow(he->url, KParts::URLArgs(), + false, TQStringList(), false, /*openURL*/false); + if(!mainwindow) + return 0L; + KonqView* newView = mainwindow->currentView(); + + if(!newView) + return 0L; + + newView->copyHistory(view); + newView->setHistoryPos(newPos); + newView->restoreHistory(); + return mainwindow; +} + +TQString KonqMisc::konqFilteredURL( TQWidget* parent, const TQString& _url, const TQString& _path ) +{ + if ( !_url.startsWith( "about:" ) ) // Don't filter "about:" URLs + { + KURIFilterData data = _url; + + if( !_path.isEmpty() ) + data.setAbsolutePath(_path); + + // We do not want to the filter to check for executables + // from the location bar. + data.setCheckForExecutables (false); + + if( KURIFilter::self()->filterURI( data ) ) + { + if( data.uriType() == KURIFilterData::ERROR && !data.errorMsg().isEmpty() ) + { + KMessageBox::sorry( parent, i18n( data.errorMsg().utf8() ) ); + return TQString::null; + } + else + return data.uri().url(); + } + } + else if ( _url.startsWith( "about:" ) && _url != "about:blank" ) { + // We can't use "about:" as it is, KURL doesn't parse it. + if (_url == "about:plugins") + return "about:plugins"; + return "about:konqueror"; + } + return _url; // return the original url if it cannot be filtered. +} + +KonqDraggableLabel::KonqDraggableLabel( KonqMainWindow* mw, const TQString& text ) + : TQLabel( text, 0L, "tde toolbar widget" ) // Use this name for it to be styled! + , m_mw(mw) +{ + setBackgroundMode( TQt::PaletteButton ); + setAlignment( (TQApplication::reverseLayout() ? Qt::AlignRight : Qt::AlignLeft) | + Qt::AlignVCenter | TQt::ShowPrefix ); + setAcceptDrops(true); + adjustSize(); + validDrag = false; +} + +void KonqDraggableLabel::mousePressEvent( TQMouseEvent * ev ) +{ + validDrag = true; + startDragPos = ev->pos(); +} + +void KonqDraggableLabel::mouseMoveEvent( TQMouseEvent * ev ) +{ + if ((startDragPos - ev->pos()).manhattanLength() > TQApplication::startDragDistance()) + { + validDrag = false; + if ( m_mw->currentView() ) + { + KURL::List lst; + lst.append( m_mw->currentView()->url() ); + TQDragObject * drag = new KURLDrag( lst, m_mw ); + drag->setPixmap( KMimeType::pixmapForURL( lst.first(), 0, TDEIcon::Small ) ); + drag->dragCopy(); + } + } +} + +void KonqDraggableLabel::mouseReleaseEvent( TQMouseEvent * ) +{ + validDrag = false; +} + +void KonqDraggableLabel::dragEnterEvent( TQDragEnterEvent *ev ) +{ + if ( KURLDrag::canDecode( ev ) ) + ev->acceptAction(); +} + +void KonqDraggableLabel::dropEvent( TQDropEvent* ev ) +{ + _savedLst.clear(); + if ( KURLDrag::decode( ev, _savedLst ) ) { + TQTimer::singleShot(0, this, TQT_SLOT(delayedOpenURL())); + } +} + +void KonqDraggableLabel::delayedOpenURL() +{ + m_mw->openURL( 0L, _savedLst.first() ); +} + +#include "konq_misc.moc" diff --git a/konqueror/konq_misc.h b/konqueror/konq_misc.h index ada1712c5..762d72d19 100644 --- a/konqueror/konq_misc.h +++ b/konqueror/konq_misc.h @@ -21,7 +21,7 @@ #define _konq_misc_h // This file can hold every global class for konqueror that used to pollute -// konq_main.cc +// konq_main.cpp #include #include diff --git a/konqueror/konq_profiledlg.cc b/konqueror/konq_profiledlg.cc deleted file mode 100644 index f7241713b..000000000 --- a/konqueror/konq_profiledlg.cc +++ /dev/null @@ -1,266 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 1999 Simon Hausmann - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - -*/ - -#include "konq_profiledlg.h" -#include "konq_viewmgr.h" -#include "konq_settingsxt.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -KonqProfileMap KonqProfileDlg::readAllProfiles() -{ - KonqProfileMap mapProfiles; - - TQStringList profiles = TDEGlobal::dirs()->findAllResources( "data", "konqueror/profiles/*", false, true ); - TQStringList::ConstIterator pIt = profiles.begin(); - TQStringList::ConstIterator pEnd = profiles.end(); - for (; pIt != pEnd; ++pIt ) - { - TQFileInfo info( *pIt ); - TQString profileName = TDEIO::decodeFileName( info.baseName() ); - KSimpleConfig cfg( *pIt, true ); - if ( cfg.hasGroup( "Profile" ) ) - { - cfg.setGroup( "Profile" ); - if ( cfg.hasKey( "Name" ) ) - profileName = cfg.readEntry( "Name" ); - - mapProfiles.insert( profileName, *pIt ); - } - } - - return mapProfiles; -} - -KonqProfileItem::KonqProfileItem( TDEListView *parent, const TQString & text ) - : TQListViewItem( parent, text ), m_profileName( text ) -{ -} - -#define BTN_RENAME KDialogBase::User1 -#define BTN_DELETE KDialogBase::User2 -#define BTN_SAVE KDialogBase::User3 - -KonqProfileDlg::KonqProfileDlg( KonqViewManager *manager, const TQString & preselectProfile, TQWidget *parent ) -: KDialogBase( parent, "konq_profile_dialog", true, i18n( "Profile Management" ), - KDialogBase::Close | BTN_RENAME | BTN_DELETE | BTN_SAVE, BTN_SAVE, true, - KGuiItem( i18n( "&Rename Profile" ) ), - KGuiItem( i18n( "&Delete Profile" ), "edit-delete"), - KStdGuiItem::save() ) -{ - m_pViewManager = manager; - - TQVBox* box = new TQVBox( this ); - box->setSpacing( KDialog::spacingHint() ); - setMainWidget( box ); - - TQLabel *lblName = new TQLabel( i18n( "&Profile name:" ), box ); - - m_pProfileNameLineEdit = new TQLineEdit( box ); - m_pProfileNameLineEdit->setFocus(); - - lblName->setBuddy( m_pProfileNameLineEdit ); - - m_pListView = new TDEListView( box ); - m_pListView->setAllColumnsShowFocus(true); - m_pListView->header()->hide(); - m_pListView->addColumn(""); - m_pListView->setRenameable( 0 ); - - box->setStretchFactor( m_pListView, 1 ); - - connect( m_pListView, TQT_SIGNAL( itemRenamed( TQListViewItem * ) ), - TQT_SLOT( slotItemRenamed( TQListViewItem * ) ) ); - - loadAllProfiles( preselectProfile ); - m_pListView->setMinimumSize( m_pListView->sizeHint() ); - - m_cbSaveURLs = new TQCheckBox( i18n("Save &URLs in profile"), box ); - m_cbSaveURLs->setChecked( KonqSettings::saveURLInProfile() ); - - m_cbSaveSize = new TQCheckBox( i18n("Save &window size in profile"), box ); - m_cbSaveSize->setChecked( KonqSettings::saveWindowSizeInProfile() ); - - connect( m_pListView, TQT_SIGNAL( selectionChanged( TQListViewItem * ) ), - this, TQT_SLOT( slotSelectionChanged( TQListViewItem * ) ) ); - - connect( m_pProfileNameLineEdit, TQT_SIGNAL( textChanged( const TQString & ) ), - this, TQT_SLOT( slotTextChanged( const TQString & ) ) ); - - enableButton( BTN_RENAME, m_pListView->selectedItem ()!=0 ); - enableButton( BTN_DELETE, m_pListView->selectedItem ()!=0 ); - - resize( sizeHint() ); -} - -KonqProfileDlg::~KonqProfileDlg() -{ - KonqSettings::setSaveURLInProfile( m_cbSaveURLs->isChecked() ); - KonqSettings::setSaveWindowSizeInProfile( m_cbSaveSize->isChecked() ); -} - -void KonqProfileDlg::loadAllProfiles(const TQString & preselectProfile) -{ - bool profileFound = false; - m_mapEntries.clear(); - m_pListView->clear(); - m_mapEntries = readAllProfiles(); - KonqProfileMap::ConstIterator eIt = m_mapEntries.begin(); - KonqProfileMap::ConstIterator eEnd = m_mapEntries.end(); - for (; eIt != eEnd; ++eIt ) - { - TQListViewItem *item = new KonqProfileItem( m_pListView, eIt.key() ); - TQString filename = eIt.data().mid( eIt.data().findRev( '/' ) + 1 ); - kdDebug(1202) << filename << endl; - if ( filename == preselectProfile ) - { - profileFound = true; - m_pProfileNameLineEdit->setText( eIt.key() ); - m_pListView->setSelected( item, true ); - } - } - if (!profileFound) - m_pProfileNameLineEdit->setText( preselectProfile); -} - -void KonqProfileDlg::slotUser3() // Save button -{ - TQString name = TDEIO::encodeFileName( m_pProfileNameLineEdit->text() ); // in case of '/' - - // Reuse filename of existing item, if any - if ( m_pListView->selectedItem() ) - { - KonqProfileMap::Iterator it = m_mapEntries.find( m_pListView->selectedItem()->text(0) ); - if ( it != m_mapEntries.end() ) - { - TQFileInfo info( it.data() ); - name = info.baseName(); - } - } - - kdDebug(1202) << "Saving as " << name << endl; - m_pViewManager->saveViewProfile( name, m_pProfileNameLineEdit->text(), - m_cbSaveURLs->isChecked(), m_cbSaveSize->isChecked() ); - - accept(); -} - -void KonqProfileDlg::slotUser2() // Delete button -{ - if(!m_pListView->selectedItem()) - return; - KonqProfileMap::Iterator it = m_mapEntries.find( m_pListView->selectedItem()->text(0) ); - - if ( it != m_mapEntries.end() && TQFile::remove( it.data() ) ) - loadAllProfiles(); - - enableButton( BTN_RENAME, m_pListView->selectedItem() != 0 ); - enableButton( BTN_DELETE, m_pListView->selectedItem() != 0 ); -} - -void KonqProfileDlg::slotUser1() // Rename button -{ - TQListViewItem *item = m_pListView->selectedItem(); - - if ( item ) - m_pListView->rename( item, 0 ); -} - -void KonqProfileDlg::slotItemRenamed( TQListViewItem * item ) -{ - KonqProfileItem * profileItem = static_cast( item ); - - TQString newName = profileItem->text(0); - TQString oldName = profileItem->m_profileName; - - if (!newName.isEmpty()) - { - KonqProfileMap::ConstIterator it = m_mapEntries.find( oldName ); - - if ( it != m_mapEntries.end() ) - { - TQString fileName = it.data(); - KSimpleConfig cfg( fileName ); - cfg.setGroup( "Profile" ); - cfg.writeEntry( "Name", newName ); - cfg.sync(); - // Didn't find how to change a key... - m_mapEntries.remove( oldName ); - m_mapEntries.insert( newName, fileName ); - m_pProfileNameLineEdit->setText( newName ); - profileItem->m_profileName = newName; - } - } -} - -void KonqProfileDlg::slotSelectionChanged( TQListViewItem * item ) -{ - m_pProfileNameLineEdit->setText( item ? item->text(0) : TQString::null ); -} - -void KonqProfileDlg::slotTextChanged( const TQString & text ) -{ - enableButton( KDialogBase::User3, !text.isEmpty() ); - - // If we type the name of a profile, select it in the list - - bool itemSelected = false; - TQListViewItem * item; - - for ( item = m_pListView->firstChild() ; item ; item = item->nextSibling() ) - if ( item->text(0) == text /*only full text, not partial*/ ) - { - itemSelected = true; - m_pListView->setSelected( item, true ); - break; - } - - if ( !itemSelected ) // otherwise, clear selection - m_pListView->clearSelection(); - - if ( itemSelected ) - { - TQFileInfo fi( m_mapEntries[ item->text( 0 ) ] ); - itemSelected = itemSelected && fi.isWritable(); - } - - enableButton( BTN_RENAME, itemSelected ); - enableButton( BTN_DELETE, itemSelected ); -} - -#undef BTN_RENAME -#undef BTN_DELETE -#undef BTN_SAVE - -#include "konq_profiledlg.moc" diff --git a/konqueror/konq_profiledlg.cpp b/konqueror/konq_profiledlg.cpp new file mode 100644 index 000000000..f7241713b --- /dev/null +++ b/konqueror/konq_profiledlg.cpp @@ -0,0 +1,266 @@ +/* This file is part of the KDE project + Copyright (C) 1999 Simon Hausmann + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +*/ + +#include "konq_profiledlg.h" +#include "konq_viewmgr.h" +#include "konq_settingsxt.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +KonqProfileMap KonqProfileDlg::readAllProfiles() +{ + KonqProfileMap mapProfiles; + + TQStringList profiles = TDEGlobal::dirs()->findAllResources( "data", "konqueror/profiles/*", false, true ); + TQStringList::ConstIterator pIt = profiles.begin(); + TQStringList::ConstIterator pEnd = profiles.end(); + for (; pIt != pEnd; ++pIt ) + { + TQFileInfo info( *pIt ); + TQString profileName = TDEIO::decodeFileName( info.baseName() ); + KSimpleConfig cfg( *pIt, true ); + if ( cfg.hasGroup( "Profile" ) ) + { + cfg.setGroup( "Profile" ); + if ( cfg.hasKey( "Name" ) ) + profileName = cfg.readEntry( "Name" ); + + mapProfiles.insert( profileName, *pIt ); + } + } + + return mapProfiles; +} + +KonqProfileItem::KonqProfileItem( TDEListView *parent, const TQString & text ) + : TQListViewItem( parent, text ), m_profileName( text ) +{ +} + +#define BTN_RENAME KDialogBase::User1 +#define BTN_DELETE KDialogBase::User2 +#define BTN_SAVE KDialogBase::User3 + +KonqProfileDlg::KonqProfileDlg( KonqViewManager *manager, const TQString & preselectProfile, TQWidget *parent ) +: KDialogBase( parent, "konq_profile_dialog", true, i18n( "Profile Management" ), + KDialogBase::Close | BTN_RENAME | BTN_DELETE | BTN_SAVE, BTN_SAVE, true, + KGuiItem( i18n( "&Rename Profile" ) ), + KGuiItem( i18n( "&Delete Profile" ), "edit-delete"), + KStdGuiItem::save() ) +{ + m_pViewManager = manager; + + TQVBox* box = new TQVBox( this ); + box->setSpacing( KDialog::spacingHint() ); + setMainWidget( box ); + + TQLabel *lblName = new TQLabel( i18n( "&Profile name:" ), box ); + + m_pProfileNameLineEdit = new TQLineEdit( box ); + m_pProfileNameLineEdit->setFocus(); + + lblName->setBuddy( m_pProfileNameLineEdit ); + + m_pListView = new TDEListView( box ); + m_pListView->setAllColumnsShowFocus(true); + m_pListView->header()->hide(); + m_pListView->addColumn(""); + m_pListView->setRenameable( 0 ); + + box->setStretchFactor( m_pListView, 1 ); + + connect( m_pListView, TQT_SIGNAL( itemRenamed( TQListViewItem * ) ), + TQT_SLOT( slotItemRenamed( TQListViewItem * ) ) ); + + loadAllProfiles( preselectProfile ); + m_pListView->setMinimumSize( m_pListView->sizeHint() ); + + m_cbSaveURLs = new TQCheckBox( i18n("Save &URLs in profile"), box ); + m_cbSaveURLs->setChecked( KonqSettings::saveURLInProfile() ); + + m_cbSaveSize = new TQCheckBox( i18n("Save &window size in profile"), box ); + m_cbSaveSize->setChecked( KonqSettings::saveWindowSizeInProfile() ); + + connect( m_pListView, TQT_SIGNAL( selectionChanged( TQListViewItem * ) ), + this, TQT_SLOT( slotSelectionChanged( TQListViewItem * ) ) ); + + connect( m_pProfileNameLineEdit, TQT_SIGNAL( textChanged( const TQString & ) ), + this, TQT_SLOT( slotTextChanged( const TQString & ) ) ); + + enableButton( BTN_RENAME, m_pListView->selectedItem ()!=0 ); + enableButton( BTN_DELETE, m_pListView->selectedItem ()!=0 ); + + resize( sizeHint() ); +} + +KonqProfileDlg::~KonqProfileDlg() +{ + KonqSettings::setSaveURLInProfile( m_cbSaveURLs->isChecked() ); + KonqSettings::setSaveWindowSizeInProfile( m_cbSaveSize->isChecked() ); +} + +void KonqProfileDlg::loadAllProfiles(const TQString & preselectProfile) +{ + bool profileFound = false; + m_mapEntries.clear(); + m_pListView->clear(); + m_mapEntries = readAllProfiles(); + KonqProfileMap::ConstIterator eIt = m_mapEntries.begin(); + KonqProfileMap::ConstIterator eEnd = m_mapEntries.end(); + for (; eIt != eEnd; ++eIt ) + { + TQListViewItem *item = new KonqProfileItem( m_pListView, eIt.key() ); + TQString filename = eIt.data().mid( eIt.data().findRev( '/' ) + 1 ); + kdDebug(1202) << filename << endl; + if ( filename == preselectProfile ) + { + profileFound = true; + m_pProfileNameLineEdit->setText( eIt.key() ); + m_pListView->setSelected( item, true ); + } + } + if (!profileFound) + m_pProfileNameLineEdit->setText( preselectProfile); +} + +void KonqProfileDlg::slotUser3() // Save button +{ + TQString name = TDEIO::encodeFileName( m_pProfileNameLineEdit->text() ); // in case of '/' + + // Reuse filename of existing item, if any + if ( m_pListView->selectedItem() ) + { + KonqProfileMap::Iterator it = m_mapEntries.find( m_pListView->selectedItem()->text(0) ); + if ( it != m_mapEntries.end() ) + { + TQFileInfo info( it.data() ); + name = info.baseName(); + } + } + + kdDebug(1202) << "Saving as " << name << endl; + m_pViewManager->saveViewProfile( name, m_pProfileNameLineEdit->text(), + m_cbSaveURLs->isChecked(), m_cbSaveSize->isChecked() ); + + accept(); +} + +void KonqProfileDlg::slotUser2() // Delete button +{ + if(!m_pListView->selectedItem()) + return; + KonqProfileMap::Iterator it = m_mapEntries.find( m_pListView->selectedItem()->text(0) ); + + if ( it != m_mapEntries.end() && TQFile::remove( it.data() ) ) + loadAllProfiles(); + + enableButton( BTN_RENAME, m_pListView->selectedItem() != 0 ); + enableButton( BTN_DELETE, m_pListView->selectedItem() != 0 ); +} + +void KonqProfileDlg::slotUser1() // Rename button +{ + TQListViewItem *item = m_pListView->selectedItem(); + + if ( item ) + m_pListView->rename( item, 0 ); +} + +void KonqProfileDlg::slotItemRenamed( TQListViewItem * item ) +{ + KonqProfileItem * profileItem = static_cast( item ); + + TQString newName = profileItem->text(0); + TQString oldName = profileItem->m_profileName; + + if (!newName.isEmpty()) + { + KonqProfileMap::ConstIterator it = m_mapEntries.find( oldName ); + + if ( it != m_mapEntries.end() ) + { + TQString fileName = it.data(); + KSimpleConfig cfg( fileName ); + cfg.setGroup( "Profile" ); + cfg.writeEntry( "Name", newName ); + cfg.sync(); + // Didn't find how to change a key... + m_mapEntries.remove( oldName ); + m_mapEntries.insert( newName, fileName ); + m_pProfileNameLineEdit->setText( newName ); + profileItem->m_profileName = newName; + } + } +} + +void KonqProfileDlg::slotSelectionChanged( TQListViewItem * item ) +{ + m_pProfileNameLineEdit->setText( item ? item->text(0) : TQString::null ); +} + +void KonqProfileDlg::slotTextChanged( const TQString & text ) +{ + enableButton( KDialogBase::User3, !text.isEmpty() ); + + // If we type the name of a profile, select it in the list + + bool itemSelected = false; + TQListViewItem * item; + + for ( item = m_pListView->firstChild() ; item ; item = item->nextSibling() ) + if ( item->text(0) == text /*only full text, not partial*/ ) + { + itemSelected = true; + m_pListView->setSelected( item, true ); + break; + } + + if ( !itemSelected ) // otherwise, clear selection + m_pListView->clearSelection(); + + if ( itemSelected ) + { + TQFileInfo fi( m_mapEntries[ item->text( 0 ) ] ); + itemSelected = itemSelected && fi.isWritable(); + } + + enableButton( BTN_RENAME, itemSelected ); + enableButton( BTN_DELETE, itemSelected ); +} + +#undef BTN_RENAME +#undef BTN_DELETE +#undef BTN_SAVE + +#include "konq_profiledlg.moc" diff --git a/konqueror/konq_run.cc b/konqueror/konq_run.cc deleted file mode 100644 index 8c2a91329..000000000 --- a/konqueror/konq_run.cc +++ /dev/null @@ -1,195 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 1998, 1999 Torben Weis - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include - -#include "konq_run.h" -#include "konq_view.h" -#include -#include -#include - -#include - -#include - -#define HINT_UTF8 106 - -KonqRun::KonqRun( KonqMainWindow* mainWindow, KonqView *_childView, - const KURL & _url, const KonqOpenURLRequest & req, bool trustedSource ) - : KParts::BrowserRun( _url, req.args, _childView ? _childView->part() : 0L, mainWindow, - //remove referrer if request was typed in manually. - // ### TODO: turn this off optionally. - !req.typedURL.isEmpty(), trustedSource, - // Don't use inline errors on reloading due to auto-refresh sites, but use them in all other cases - // (no reload or user-requested reload) - !req.args.reload || req.userRequestedReload ), - m_pMainWindow( mainWindow ), m_pView( _childView ), m_bFoundMimeType( false ), m_req( req ) -{ - //kdDebug(1202) << "KonqRun::KonqRun() " << this << endl; - assert( !m_pMainWindow.isNull() ); - if (m_pView) - m_pView->setLoading(true); -} - -KonqRun::~KonqRun() -{ - //kdDebug(1202) << "KonqRun::~KonqRun() " << this << endl; - if (m_pView && m_pView->run() == this) - m_pView->setRun(0L); -} - -void KonqRun::foundMimeType( const TQString & _type ) -{ - //kdDebug(1202) << "KonqRun::foundMimeType " << _type << " m_req=" << m_req.debug() << endl; - - TQString mimeType = _type; // this ref comes from the job, we lose it when using TDEIO again - - m_bFoundMimeType = true; - - if (m_pView) - m_pView->setLoading(false); // first phase finished, don't confuse KonqView - - // Check if the main window wasn't deleted meanwhile - if( !m_pMainWindow ) - { - m_bFinished = true; - m_bFault = true; - m_timer.start( 0, true ); - return; - } - - // Grab the args back from BrowserRun - m_req.args = m_args; - - bool tryEmbed = true; - - // One case where we shouldn't try to embed, is when the server asks us to save - if ( serverSuggestsSave() ) - tryEmbed = false; - - if ( KonqMainWindow::isMimeTypeAssociatedWithSelf( mimeType ) ) - m_req.forceAutoEmbed = true; - - if ( tryEmbed ) - m_bFinished = m_pMainWindow->openView( mimeType, m_strURL, m_pView, m_req ); - - if ( m_bFinished ) { - m_pMainWindow = 0L; - m_timer.start( 0, true ); - return; - } - - // If we were following another view, do nothing if opening didn't work. - if ( m_req.followMode ) - m_bFinished = true; - - if ( !m_bFinished ) { - // If we couldn't embed the mimetype, call BrowserRun::handleNonEmbeddable() - KParts::BrowserRun::NonEmbeddableResult res = handleNonEmbeddable( mimeType ); - if ( res == KParts::BrowserRun::Delayed ) - return; - m_bFinished = ( res == KParts::BrowserRun::Handled ); - if (!m_bFinished && !tryEmbed) // Open selected for a serverSuggestsSave() file - m_bFinished = m_pMainWindow->openView( mimeType, m_strURL, m_pView, m_req ); - } - - // make Konqueror think there was an error, in order to stop the spinning wheel - // (we saved, canceled, or we're starting another app... in any case the current view should stop loading). - m_bFault = true; - - if ( !m_bFinished && // only if we're going to open - KonqMainWindow::isMimeTypeAssociatedWithSelf( mimeType ) ) { - KMessageBox::error( m_pMainWindow, i18n( "There appears to be a configuration error. You have associated Konqueror with %1, but it cannot handle this file type." ).arg( mimeType ) ); - m_bFinished = true; - } - - if ( m_bFinished ) { - m_pMainWindow = 0L; - m_timer.start( 0, true ); - return; - } - - kdDebug(1202) << "Nothing special to do in KonqRun, falling back to KRun" << endl; - KRun::foundMimeType( mimeType ); -} - -void KonqRun::handleError( TDEIO::Job *job ) -{ - kdDebug(1202) << "KonqRun::handleError error:" << job->errorString() << endl; - if (!m_mailto.isEmpty()) - { - m_job = 0; - m_bFinished = true; - m_timer.start( 0, true ); - return; - } - KParts::BrowserRun::handleError( job ); -} - -void KonqRun::init() -{ - KParts::BrowserRun::init(); - // Maybe init went to the "let's try stat'ing" part. Then connect to info messages. - // (in case it goes to scanFile, this will be done below) - TDEIO::StatJob *job = tqt_dynamic_cast( m_job ); - if ( job && !job->error() && m_pView ) { - connect( job, TQT_SIGNAL( infoMessage( TDEIO::Job*, const TQString& ) ), - m_pView, TQT_SLOT( slotInfoMessage(TDEIO::Job*, const TQString& ) ) ); - } -} - -void KonqRun::scanFile() -{ - KParts::BrowserRun::scanFile(); - // could be a static cast as of now, but who would notify when - // BrowserRun changes - TDEIO::TransferJob *job = tqt_dynamic_cast( m_job ); - if ( job && !job->error() ) { - connect( job, TQT_SIGNAL( redirection( TDEIO::Job *, const KURL& )), - TQT_SLOT( slotRedirection( TDEIO::Job *, const KURL& ) )); - if ( m_pView && m_pView->service()->desktopEntryName() != "konq_sidebartng") { - connect( job, TQT_SIGNAL( infoMessage( TDEIO::Job*, const TQString& ) ), - m_pView, TQT_SLOT( slotInfoMessage(TDEIO::Job*, const TQString& ) ) ); - } - } -} - -void KonqRun::slotRedirection( TDEIO::Job *job, const KURL& redirectedToURL ) -{ - KURL redirectFromURL = static_cast(job)->url(); - kdDebug(1202) << "KonqRun::slotRedirection from " << - redirectFromURL.prettyURL() << " to " << redirectedToURL.prettyURL() << endl; - KonqHistoryManager::kself()->confirmPending( redirectFromURL ); - - if (redirectedToURL.protocol() == "mailto") - { - m_mailto = redirectedToURL; - return; // Error will follow - } - KonqHistoryManager::kself()->addPending( redirectedToURL ); - - // Do not post data on reload if we were redirected to a new URL when - // doing a POST request. - if (redirectFromURL != redirectedToURL) - m_args.setDoPost (false); - m_args.setRedirectedRequest(true); -} - -#include "konq_run.moc" diff --git a/konqueror/konq_run.cpp b/konqueror/konq_run.cpp new file mode 100644 index 000000000..8c2a91329 --- /dev/null +++ b/konqueror/konq_run.cpp @@ -0,0 +1,195 @@ +/* This file is part of the KDE project + Copyright (C) 1998, 1999 Torben Weis + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include + +#include "konq_run.h" +#include "konq_view.h" +#include +#include +#include + +#include + +#include + +#define HINT_UTF8 106 + +KonqRun::KonqRun( KonqMainWindow* mainWindow, KonqView *_childView, + const KURL & _url, const KonqOpenURLRequest & req, bool trustedSource ) + : KParts::BrowserRun( _url, req.args, _childView ? _childView->part() : 0L, mainWindow, + //remove referrer if request was typed in manually. + // ### TODO: turn this off optionally. + !req.typedURL.isEmpty(), trustedSource, + // Don't use inline errors on reloading due to auto-refresh sites, but use them in all other cases + // (no reload or user-requested reload) + !req.args.reload || req.userRequestedReload ), + m_pMainWindow( mainWindow ), m_pView( _childView ), m_bFoundMimeType( false ), m_req( req ) +{ + //kdDebug(1202) << "KonqRun::KonqRun() " << this << endl; + assert( !m_pMainWindow.isNull() ); + if (m_pView) + m_pView->setLoading(true); +} + +KonqRun::~KonqRun() +{ + //kdDebug(1202) << "KonqRun::~KonqRun() " << this << endl; + if (m_pView && m_pView->run() == this) + m_pView->setRun(0L); +} + +void KonqRun::foundMimeType( const TQString & _type ) +{ + //kdDebug(1202) << "KonqRun::foundMimeType " << _type << " m_req=" << m_req.debug() << endl; + + TQString mimeType = _type; // this ref comes from the job, we lose it when using TDEIO again + + m_bFoundMimeType = true; + + if (m_pView) + m_pView->setLoading(false); // first phase finished, don't confuse KonqView + + // Check if the main window wasn't deleted meanwhile + if( !m_pMainWindow ) + { + m_bFinished = true; + m_bFault = true; + m_timer.start( 0, true ); + return; + } + + // Grab the args back from BrowserRun + m_req.args = m_args; + + bool tryEmbed = true; + + // One case where we shouldn't try to embed, is when the server asks us to save + if ( serverSuggestsSave() ) + tryEmbed = false; + + if ( KonqMainWindow::isMimeTypeAssociatedWithSelf( mimeType ) ) + m_req.forceAutoEmbed = true; + + if ( tryEmbed ) + m_bFinished = m_pMainWindow->openView( mimeType, m_strURL, m_pView, m_req ); + + if ( m_bFinished ) { + m_pMainWindow = 0L; + m_timer.start( 0, true ); + return; + } + + // If we were following another view, do nothing if opening didn't work. + if ( m_req.followMode ) + m_bFinished = true; + + if ( !m_bFinished ) { + // If we couldn't embed the mimetype, call BrowserRun::handleNonEmbeddable() + KParts::BrowserRun::NonEmbeddableResult res = handleNonEmbeddable( mimeType ); + if ( res == KParts::BrowserRun::Delayed ) + return; + m_bFinished = ( res == KParts::BrowserRun::Handled ); + if (!m_bFinished && !tryEmbed) // Open selected for a serverSuggestsSave() file + m_bFinished = m_pMainWindow->openView( mimeType, m_strURL, m_pView, m_req ); + } + + // make Konqueror think there was an error, in order to stop the spinning wheel + // (we saved, canceled, or we're starting another app... in any case the current view should stop loading). + m_bFault = true; + + if ( !m_bFinished && // only if we're going to open + KonqMainWindow::isMimeTypeAssociatedWithSelf( mimeType ) ) { + KMessageBox::error( m_pMainWindow, i18n( "There appears to be a configuration error. You have associated Konqueror with %1, but it cannot handle this file type." ).arg( mimeType ) ); + m_bFinished = true; + } + + if ( m_bFinished ) { + m_pMainWindow = 0L; + m_timer.start( 0, true ); + return; + } + + kdDebug(1202) << "Nothing special to do in KonqRun, falling back to KRun" << endl; + KRun::foundMimeType( mimeType ); +} + +void KonqRun::handleError( TDEIO::Job *job ) +{ + kdDebug(1202) << "KonqRun::handleError error:" << job->errorString() << endl; + if (!m_mailto.isEmpty()) + { + m_job = 0; + m_bFinished = true; + m_timer.start( 0, true ); + return; + } + KParts::BrowserRun::handleError( job ); +} + +void KonqRun::init() +{ + KParts::BrowserRun::init(); + // Maybe init went to the "let's try stat'ing" part. Then connect to info messages. + // (in case it goes to scanFile, this will be done below) + TDEIO::StatJob *job = tqt_dynamic_cast( m_job ); + if ( job && !job->error() && m_pView ) { + connect( job, TQT_SIGNAL( infoMessage( TDEIO::Job*, const TQString& ) ), + m_pView, TQT_SLOT( slotInfoMessage(TDEIO::Job*, const TQString& ) ) ); + } +} + +void KonqRun::scanFile() +{ + KParts::BrowserRun::scanFile(); + // could be a static cast as of now, but who would notify when + // BrowserRun changes + TDEIO::TransferJob *job = tqt_dynamic_cast( m_job ); + if ( job && !job->error() ) { + connect( job, TQT_SIGNAL( redirection( TDEIO::Job *, const KURL& )), + TQT_SLOT( slotRedirection( TDEIO::Job *, const KURL& ) )); + if ( m_pView && m_pView->service()->desktopEntryName() != "konq_sidebartng") { + connect( job, TQT_SIGNAL( infoMessage( TDEIO::Job*, const TQString& ) ), + m_pView, TQT_SLOT( slotInfoMessage(TDEIO::Job*, const TQString& ) ) ); + } + } +} + +void KonqRun::slotRedirection( TDEIO::Job *job, const KURL& redirectedToURL ) +{ + KURL redirectFromURL = static_cast(job)->url(); + kdDebug(1202) << "KonqRun::slotRedirection from " << + redirectFromURL.prettyURL() << " to " << redirectedToURL.prettyURL() << endl; + KonqHistoryManager::kself()->confirmPending( redirectFromURL ); + + if (redirectedToURL.protocol() == "mailto") + { + m_mailto = redirectedToURL; + return; // Error will follow + } + KonqHistoryManager::kself()->addPending( redirectedToURL ); + + // Do not post data on reload if we were redirected to a new URL when + // doing a POST request. + if (redirectFromURL != redirectedToURL) + m_args.setDoPost (false); + m_args.setRedirectedRequest(true); +} + +#include "konq_run.moc" diff --git a/konqueror/konq_tabs.cc b/konqueror/konq_tabs.cc deleted file mode 100644 index 868b8edc9..000000000 --- a/konqueror/konq_tabs.cc +++ /dev/null @@ -1,609 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2002-2003 Konqueror Developers - 2002-2003 Douglas Hanley - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. -*/ - -#include "konq_tabs.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include "konq_frame.h" -#include "konq_view.h" -#include "konq_viewmgr.h" -#include "konq_misc.h" -#include "konq_settingsxt.h" - -#include -#include -#include -#include -#include -#include - -#define DUPLICATE_ID 3 -#define RELOAD_ID 4 -#define BREAKOFF_ID 5 -#define CLOSETAB_ID 6 -#define OTHERTABS_ID 7 -#define MOVE_LEFT_ID 8 -#define MOVE_RIGHT_ID 9 - -//################################################################### - -KonqFrameTabs::KonqFrameTabs(TQWidget* parent, KonqFrameContainerBase* parentContainer, - KonqViewManager* viewManager, const char * name) - : KTabWidget(parent, name), m_rightWidget(0), m_leftWidget(0), m_alwaysTabBar(false), - m_closeOtherTabsId(0) -{ - TDEAcceleratorManager::setNoAccel(this); - - TQWhatsThis::add( tabBar(), i18n( "This bar contains the list of currently open tabs. Click on a tab to make it " - "active. The option to show a close button instead of the website icon in the left " - "corner of the tab is configurable. You can also use keyboard shortcuts to " - "navigate through tabs. The text on the tab is the title of the website " - "currently open in it, put your mouse over the tab too see the full title in " - "case it was truncated to fit the tab size." ) ); - //kdDebug(1202) << "KonqFrameTabs::KonqFrameTabs()" << endl; - - m_pParentContainer = parentContainer; - m_pChildFrameList = new TQPtrList; - m_pChildFrameList->setAutoDelete(false); - m_pActiveChild = 0L; - m_pViewManager = viewManager; - - connect( this, TQT_SIGNAL( currentChanged ( TQWidget * ) ), - this, TQT_SLOT( slotCurrentChanged( TQWidget* ) ) ); - - m_pPopupMenu = new TQPopupMenu( this ); - m_pPopupMenu->insertItem( SmallIcon( "tab_new" ), - i18n("&New Tab"), - m_pViewManager->mainWindow(), - TQT_SLOT( slotAddTab() ), - m_pViewManager->mainWindow()->action("newtab")->shortcut() ); - m_pPopupMenu->insertItem( SmallIconSet( "reload" ), - i18n( "&Reload Tab" ), - m_pViewManager->mainWindow(), - TQT_SLOT( slotReloadPopup() ), - m_pViewManager->mainWindow()->action("reload")->shortcut(), RELOAD_ID ); - m_pPopupMenu->insertItem( SmallIconSet( "tab_duplicate" ), - i18n("&Duplicate Tab"), - m_pViewManager->mainWindow(), - TQT_SLOT( slotDuplicateTabPopup() ), - m_pViewManager->mainWindow()->action("duplicatecurrenttab")->shortcut(), - DUPLICATE_ID ); - m_pPopupMenu->insertItem( SmallIconSet( "tab_breakoff" ), - i18n("D&etach Tab"), - m_pViewManager->mainWindow(), - TQT_SLOT( slotBreakOffTabPopup() ), - m_pViewManager->mainWindow()->action("breakoffcurrenttab")->shortcut(), - BREAKOFF_ID ); - m_pPopupMenu->insertSeparator(); - m_pPopupMenu->insertItem( SmallIconSet( "tab_move_left" ), - i18n("Move Tab &Left"), - m_pViewManager->mainWindow(), - TQT_SLOT( slotMoveTabLeft() ), - m_pViewManager->mainWindow()->action("tab_move_left")->shortcut(), - MOVE_LEFT_ID ); - m_pPopupMenu->insertItem( SmallIconSet( "tab_move_right" ), - i18n("Move Tab &Right"), - m_pViewManager->mainWindow(), - TQT_SLOT( slotMoveTabRight() ), - m_pViewManager->mainWindow()->action("tab_move_right")->shortcut(), - MOVE_RIGHT_ID ); - m_pPopupMenu->insertSeparator(); - m_pSubPopupMenuTab = new TQPopupMenu( this ); - m_pPopupMenu->insertItem( i18n("Other Tabs" ), m_pSubPopupMenuTab, OTHERTABS_ID ); - connect( m_pSubPopupMenuTab, TQT_SIGNAL( activated ( int ) ), - this, TQT_SLOT( slotSubPopupMenuTabActivated( int ) ) ); - m_pPopupMenu->insertSeparator(); - m_pPopupMenu->insertItem( SmallIconSet( "tab_remove" ), - i18n("&Close Tab"), - m_pViewManager->mainWindow(), - TQT_SLOT( slotRemoveTabPopup() ), - m_pViewManager->mainWindow()->action("removecurrenttab")->shortcut(), - CLOSETAB_ID ); - connect( this, TQT_SIGNAL( contextMenu( TQWidget *, const TQPoint & ) ), - TQT_SLOT(slotContextMenu( TQWidget *, const TQPoint & ) ) ); - connect( this, TQT_SIGNAL( contextMenu( const TQPoint & ) ), - TQT_SLOT(slotContextMenu( const TQPoint & ) ) ); - - m_MouseMiddleClickClosesTab = KonqSettings::mouseMiddleClickClosesTab(); - - m_permanentCloseButtons = KonqSettings::permanentCloseButton(); - if (m_permanentCloseButtons) { - setHoverCloseButton( true ); - setHoverCloseButtonDelayed( false ); - } - else - setHoverCloseButton( KonqSettings::hoverCloseButton() ); - setTabCloseActivatePrevious( KonqSettings::tabCloseActivatePrevious() ); - if (KonqSettings::tabPosition()=="Bottom") - setTabPosition(TQTabWidget::Bottom); - connect( this, TQT_SIGNAL( closeRequest( TQWidget * )), TQT_SLOT(slotCloseRequest( TQWidget * ))); - connect( this, TQT_SIGNAL( removeTabPopup() ), - m_pViewManager->mainWindow(), TQT_SLOT( slotRemoveTabPopup() ) ); - - if ( KonqSettings::addTabButton() ) { - m_leftWidget = new TQToolButton( this ); - connect( m_leftWidget, TQT_SIGNAL( clicked() ), - m_pViewManager->mainWindow(), TQT_SLOT( slotAddTab() ) ); - m_leftWidget->setIconSet( SmallIcon( "tab_new" ) ); - m_leftWidget->adjustSize(); - TQToolTip::add(m_leftWidget, i18n("Open a new tab")); - setCornerWidget( m_leftWidget, TopLeft ); - } - if ( KonqSettings::closeTabButton() ) { - m_rightWidget = new TQToolButton( this ); - connect( m_rightWidget, TQT_SIGNAL( clicked() ), - m_pViewManager->mainWindow(), TQT_SLOT( slotRemoveTab() ) ); - m_rightWidget->setIconSet( SmallIconSet( "tab_remove" ) ); - m_rightWidget->adjustSize(); - TQToolTip::add(m_rightWidget, i18n("Close the current tab")); - setCornerWidget( m_rightWidget, TopRight ); - } - - setAutomaticResizeTabs( true ); - setTabReorderingEnabled( true ); - connect( this, TQT_SIGNAL( movedTab( int, int ) ), - TQT_SLOT( slotMovedTab( int, int ) ) ); - connect( this, TQT_SIGNAL( mouseMiddleClick() ), - TQT_SLOT( slotMouseMiddleClick() ) ); - connect( this, TQT_SIGNAL( mouseMiddleClick( TQWidget * ) ), - TQT_SLOT( slotMouseMiddleClick( TQWidget * ) ) ); - connect( this, TQT_SIGNAL( mouseDoubleClick() ), - m_pViewManager->mainWindow(), TQT_SLOT( slotAddTab() ) ); - - connect( this, TQT_SIGNAL( testCanDecode(const TQDragMoveEvent *, bool & )), - TQT_SLOT( slotTestCanDecode(const TQDragMoveEvent *, bool & ) ) ); - connect( this, TQT_SIGNAL( receivedDropEvent( TQDropEvent * )), - TQT_SLOT( slotReceivedDropEvent( TQDropEvent * ) ) ); - connect( this, TQT_SIGNAL( receivedDropEvent( TQWidget *, TQDropEvent * )), - TQT_SLOT( slotReceivedDropEvent( TQWidget *, TQDropEvent * ) ) ); - connect( this, TQT_SIGNAL( initiateDrag( TQWidget * )), - TQT_SLOT( slotInitiateDrag( TQWidget * ) ) ); - - setMouseWheelScroll(KonqSettings::tabsCycleWheel()); -} - -KonqFrameTabs::~KonqFrameTabs() -{ - //kdDebug(1202) << "KonqFrameTabs::~KonqFrameTabs() " << this << " - " << className() << endl; - m_pChildFrameList->setAutoDelete(true); - delete m_pChildFrameList; -} - -void KonqFrameTabs::listViews( ChildViewList *viewList ) { - for( TQPtrListIterator it( *m_pChildFrameList ); *it; ++it ) - it.current()->listViews(viewList); -} - -void KonqFrameTabs::saveConfig( TDEConfig* config, const TQString &prefix, bool saveURLs, - KonqFrameBase* docContainer, int id, int depth ) -{ - //write children - TQStringList strlst; - int i = 0; - TQString newPrefix; - for (KonqFrameBase* it = m_pChildFrameList->first(); it; it = m_pChildFrameList->next()) - { - newPrefix = TQString::fromLatin1( it->frameType() ) + "T" + TQString::number(i); - strlst.append( newPrefix ); - newPrefix.append( '_' ); - it->saveConfig( config, newPrefix, saveURLs, docContainer, id, depth + i ); - i++; - } - - config->writeEntry( TQString::fromLatin1( "Children" ).prepend( prefix ), strlst ); - - config->writeEntry( TQString::fromLatin1( "activeChildIndex" ).prepend( prefix ), - currentPageIndex() ); -} - -void KonqFrameTabs::copyHistory( KonqFrameBase *other ) -{ - if( other->frameType() != "Tabs" ) { - kdDebug(1202) << "Frame types are not the same" << endl; - return; - } - - for (uint i = 0; i < m_pChildFrameList->count(); i++ ) - { - m_pChildFrameList->at(i)->copyHistory( static_cast( other )->m_pChildFrameList->at(i) ); - } -} - -void KonqFrameTabs::printFrameInfo( const TQString& spaces ) -{ - kdDebug(1202) << spaces << "KonqFrameTabs " << this << " visible=" - << TQString("%1").arg(isVisible()) << " activeChild=" - << m_pActiveChild << endl; - - if (!m_pActiveChild) - kdDebug(1202) << "WARNING: " << this << " has a null active child!" << endl; - - KonqFrameBase* child; - int childFrameCount = m_pChildFrameList->count(); - for (int i = 0 ; i < childFrameCount ; i++) { - child = m_pChildFrameList->at(i); - if (child != 0L) - child->printFrameInfo(spaces + " "); - else - kdDebug(1202) << spaces << " Null child" << endl; - } -} - -void KonqFrameTabs::reparentFrame( TQWidget* parent, const TQPoint & p, bool showIt ) -{ - TQWidget::reparent( parent, p, showIt ); -} - -void KonqFrameTabs::setTitle( const TQString &title , TQWidget* sender) -{ - // kdDebug(1202) << "KonqFrameTabs::setTitle( " << title << " , " << sender << " )" << endl; - setTabLabel( sender,title ); -} - -void KonqFrameTabs::setTabIcon( const KURL &url, TQWidget* sender ) -{ - //kdDebug(1202) << "KonqFrameTabs::setTabIcon( " << url << " , " << sender << " )" << endl; - TQIconSet iconSet; - if (m_permanentCloseButtons) - iconSet = SmallIcon( "window-close" ); - else - iconSet = SmallIconSet( KonqPixmapProvider::self()->iconNameFor( url.url() ) ); - if (tabIconSet( sender ).pixmap().serialNumber() != iconSet.pixmap().serialNumber()) - setTabIconSet( sender, iconSet ); -} - -void KonqFrameTabs::activateChild() -{ - if (m_pActiveChild) - { - showPage( m_pActiveChild->widget() ); - m_pActiveChild->activateChild(); - } -} - -void KonqFrameTabs::insertChildFrame( KonqFrameBase* frame, int index ) -{ - //kdDebug(1202) << "KonqFrameTabs " << this << ": insertChildFrame " << frame << endl; - - if (frame) - { - //kdDebug(1202) << "Adding frame" << endl; - bool showTabBar = (count() == 1); - insertTab(frame->widget(),"", index); - frame->setParentContainer(this); - if (index == -1) m_pChildFrameList->append(frame); - else m_pChildFrameList->insert(index, frame); - if (m_rightWidget) - m_rightWidget->setEnabled( m_pChildFrameList->count()>1 ); - KonqView* activeChildView = frame->activeChildView(); - if (activeChildView != 0L) { - activeChildView->setCaption( activeChildView->caption() ); - activeChildView->setTabIcon( activeChildView->url() ); - } - if (showTabBar) - setTabBarHidden(false); - else if ( count() == 1 ) - this->hideTabBar();//the first frame inserted (initialization) - } - else - kdWarning(1202) << "KonqFrameTabs " << this << ": insertChildFrame(0L) !" << endl; -} - -void KonqFrameTabs::removeChildFrame( KonqFrameBase * frame ) -{ - //kdDebug(1202) << "KonqFrameTabs::RemoveChildFrame " << this << ". Child " << frame << " removed" << endl; - if (frame) { - removePage(frame->widget()); - m_pChildFrameList->remove(frame); - if (m_rightWidget) - m_rightWidget->setEnabled( m_pChildFrameList->count()>1 ); - if (count() == 1) - hideTabBar(); - } - else - kdWarning(1202) << "KonqFrameTabs " << this << ": removeChildFrame(0L) !" << endl; - - //kdDebug(1202) << "KonqFrameTabs::RemoveChildFrame finished" << endl; -} - -void KonqFrameTabs::slotCurrentChanged( TQWidget* newPage ) -{ - setTabColor( newPage, TDEGlobalSettings::textColor() ); - KonqFrameBase* currentFrame = tqt_dynamic_cast(newPage); - - if (currentFrame && !m_pViewManager->isLoadingProfile()) { - m_pActiveChild = currentFrame; - currentFrame->activateChild(); - } -} - -void KonqFrameTabs::moveTabBackward( int index ) -{ - if ( index == 0 ) - return; - moveTab( index, index-1 ); -} - -void KonqFrameTabs::moveTabForward( int index ) -{ - if ( index == count()-1 ) - return; - moveTab( index, index+1 ); -} - -void KonqFrameTabs::slotMovedTab( int from, int to ) -{ - KonqFrameBase* fromFrame = m_pChildFrameList->at( from ); - m_pChildFrameList->remove( fromFrame ); - m_pChildFrameList->insert( to, fromFrame ); - - KonqFrameBase* currentFrame = tqt_dynamic_cast( currentPage() ); - if ( currentFrame && !m_pViewManager->isLoadingProfile() ) { - m_pActiveChild = currentFrame; - currentFrame->activateChild(); - } -} - -void KonqFrameTabs::slotContextMenu( const TQPoint &p ) -{ - refreshSubPopupMenuTab(); - - m_pPopupMenu->setItemEnabled( RELOAD_ID, false ); - m_pPopupMenu->setItemEnabled( DUPLICATE_ID, false ); - m_pPopupMenu->setItemEnabled( BREAKOFF_ID, false ); - - uint tabCount = m_pChildFrameList->count(); - KonqView *kview = m_pViewManager->mainWindow()->currentView(); - if (tabCount>1 && kview) - { - // Move tab left - bool left_enable = false, right_enable = false; - if (TQApplication::reverseLayout()) - { - left_enable = (kview->frame() != m_pChildFrameList->last()); - right_enable= (kview->frame() != m_pChildFrameList->first()); - } - else - { - left_enable = (kview->frame() != m_pChildFrameList->first()); - right_enable= (kview->frame() != m_pChildFrameList->last()); - } - m_pPopupMenu->setItemEnabled( MOVE_LEFT_ID, left_enable); - m_pPopupMenu->setItemEnabled( MOVE_RIGHT_ID, right_enable); - } - else - { - m_pPopupMenu->setItemEnabled(MOVE_LEFT_ID, false); - m_pPopupMenu->setItemEnabled(MOVE_RIGHT_ID, false); - } - - m_pPopupMenu->setItemEnabled( CLOSETAB_ID, false ); - m_pPopupMenu->setItemEnabled( OTHERTABS_ID, true ); - m_pSubPopupMenuTab->setItemEnabled( m_closeOtherTabsId, false ); - - m_pPopupMenu->exec( p ); -} - -void KonqFrameTabs::slotContextMenu( TQWidget *w, const TQPoint &p ) -{ - refreshSubPopupMenuTab(); - - uint tabCount = m_pChildFrameList->count(); - m_pPopupMenu->setItemEnabled( RELOAD_ID, true ); - m_pPopupMenu->setItemEnabled( DUPLICATE_ID, true ); - m_pPopupMenu->setItemEnabled( BREAKOFF_ID, tabCount>1 ); - - KonqView *kview = m_pViewManager->mainWindow()->currentView(); - if (tabCount>1 && kview) - { - // Move tab left - bool left_enable = false, right_enable = false; - if (TQApplication::reverseLayout()) - { - left_enable = (kview->frame() != m_pChildFrameList->last()); - right_enable= (kview->frame() != m_pChildFrameList->first()); - } - else - { - left_enable = (kview->frame() != m_pChildFrameList->first()); - right_enable= (kview->frame() != m_pChildFrameList->last()); - } - m_pPopupMenu->setItemEnabled( MOVE_LEFT_ID, left_enable); - m_pPopupMenu->setItemEnabled( MOVE_RIGHT_ID, right_enable); - } - else - { - m_pPopupMenu->setItemEnabled(MOVE_LEFT_ID, false); - m_pPopupMenu->setItemEnabled(MOVE_RIGHT_ID, false); - } - - m_pPopupMenu->setItemEnabled( CLOSETAB_ID, tabCount>1 ); - m_pPopupMenu->setItemEnabled( OTHERTABS_ID, tabCount>1 ); - m_pSubPopupMenuTab->setItemEnabled( m_closeOtherTabsId, true ); - - // Yes, I know this is an unchecked tqt_dynamic_cast - I'm casting sideways in a - // class hierarchy and it could crash one day, but I haven't checked - // setWorkingTab so I don't know if it can handle nulls. - - m_pViewManager->mainWindow()->setWorkingTab( tqt_dynamic_cast(w) ); - m_pPopupMenu->exec( p ); -} - -void KonqFrameTabs::refreshSubPopupMenuTab() -{ - m_pSubPopupMenuTab->clear(); - int i=0; - m_pSubPopupMenuTab->insertItem( SmallIcon( "reload_all_tabs" ), - i18n( "&Reload All Tabs" ), - m_pViewManager->mainWindow(), - TQT_SLOT( slotReloadAllTabs() ), - m_pViewManager->mainWindow()->action("reload_all_tabs")->shortcut() ); - m_pSubPopupMenuTab->insertSeparator(); - for (KonqFrameBase* it = m_pChildFrameList->first(); it; it = m_pChildFrameList->next()) - { - KonqFrame* frame = dynamic_cast(it); - if ( frame && frame->activeChildView() ) - { - TQString title = frame->title().stripWhiteSpace(); - if ( title.isEmpty() ) - title = frame->activeChildView()->url().url(); - title = KStringHandler::csqueeze( title, 50 ); - m_pSubPopupMenuTab->insertItem( TQIconSet( KonqPixmapProvider::self()->pixmapFor( frame->activeChildView()->url().url() ) ), title, i ); - - } - i++; - } - m_pSubPopupMenuTab->insertSeparator(); - m_closeOtherTabsId = - m_pSubPopupMenuTab->insertItem( SmallIconSet( "tab_remove_other" ), - i18n( "Close &Other Tabs" ), - m_pViewManager->mainWindow(), - TQT_SLOT( slotRemoveOtherTabsPopup() ), - m_pViewManager->mainWindow()->action("removeothertabs")->shortcut() ); -} - -void KonqFrameTabs::slotCloseRequest( TQWidget *w ) -{ - if ( m_pChildFrameList->count() > 1 ) { - // Yes, I know this is an unchecked tqt_dynamic_cast - I'm casting sideways in a class hierarchy and it could crash one day, but I haven't checked setWorkingTab so I don't know if it can handle nulls. - m_pViewManager->mainWindow()->setWorkingTab( tqt_dynamic_cast(w) ); - emit ( removeTabPopup() ); - } -} - -void KonqFrameTabs::slotSubPopupMenuTabActivated( int _id) -{ - setCurrentPage( _id ); -} - -void KonqFrameTabs::slotMouseMiddleClick() -{ - TQApplication::clipboard()->setSelectionMode( TQClipboard::Selection ); - KURL filteredURL ( KonqMisc::konqFilteredURL( this, TQApplication::clipboard()->text() ) ); - if ( !filteredURL.isEmpty() ) { - KonqView* newView = m_pViewManager->addTab(TQString::null, TQString::null, false, false); - if (newView == 0L) return; - m_pViewManager->mainWindow()->openURL( newView, filteredURL, TQString::null ); - m_pViewManager->showTab( newView ); - m_pViewManager->mainWindow()->focusLocationBar(); - } -} - -void KonqFrameTabs::slotMouseMiddleClick( TQWidget *w ) -{ - if ( m_MouseMiddleClickClosesTab ) { - if ( m_pChildFrameList->count() > 1 ) { - // Yes, I know this is an unchecked tqt_dynamic_cast - I'm casting sideways in a class hierarchy and it could crash one day, but I haven't checked setWorkingTab so I don't know if it can handle nulls. - m_pViewManager->mainWindow()->setWorkingTab( tqt_dynamic_cast(w) ); - emit ( removeTabPopup() ); - } - } - else { - TQApplication::clipboard()->setSelectionMode( TQClipboard::Selection ); - KURL filteredURL ( KonqMisc::konqFilteredURL( this, TQApplication::clipboard()->text() ) ); - if ( !filteredURL.isEmpty() ) { - KonqFrameBase* frame = tqt_dynamic_cast(w); - if (frame) { - m_pViewManager->mainWindow()->openURL( frame->activeChildView(), filteredURL ); - } - } - } -} - -void KonqFrameTabs::slotTestCanDecode(const TQDragMoveEvent *e, bool &accept /* result */) -{ - accept = KURLDrag::canDecode( e ); -} - -void KonqFrameTabs::slotReceivedDropEvent( TQDropEvent *e ) -{ - KURL::List lstDragURLs; - bool ok = KURLDrag::decode( e, lstDragURLs ); - if ( ok && lstDragURLs.first().isValid() ) { - KonqView* newView = m_pViewManager->addTab(TQString::null, TQString::null, false, false); - if (newView == 0L) return; - m_pViewManager->mainWindow()->openURL( newView, lstDragURLs.first(), TQString::null ); - m_pViewManager->showTab( newView ); - m_pViewManager->mainWindow()->focusLocationBar(); - } -} - -void KonqFrameTabs::slotReceivedDropEvent( TQWidget *w, TQDropEvent *e ) -{ - KURL::List lstDragURLs; - bool ok = KURLDrag::decode( e, lstDragURLs ); - KonqFrameBase* frame = tqt_dynamic_cast(w); - if ( ok && lstDragURLs.first().isValid() && frame ) { - KURL lstDragURL = lstDragURLs.first(); - if ( lstDragURL != frame->activeChildView()->url() ) - m_pViewManager->mainWindow()->openURL( frame->activeChildView(), lstDragURL ); - } -} - -void KonqFrameTabs::slotInitiateDrag( TQWidget *w ) -{ - KonqFrameBase* frame = tqt_dynamic_cast( w ); - if (frame) { - KURL::List lst; - lst.append( frame->activeChildView()->url() ); - KURLDrag *d = new KURLDrag( lst, this ); - d->setPixmap( KMimeType::pixmapForURL( lst.first(), 0, TDEIcon::Small ) ); - d->dragCopy(); - } -} - -void KonqFrameTabs::hideTabBar() -{ - if ( !m_alwaysTabBar ) { - setTabBarHidden(true); - } - m_pPopupMenu->setItemEnabled( BREAKOFF_ID, false ); - m_pPopupMenu->setItemEnabled( MOVE_LEFT_ID, false ); - m_pPopupMenu->setItemEnabled( MOVE_RIGHT_ID, false ); - m_pPopupMenu->setItemEnabled( CLOSETAB_ID, false ); -} - -void KonqFrameTabs::setAlwaysTabbedMode( bool enable ) -{ - bool update = ( enable != m_alwaysTabBar ); - - m_alwaysTabBar = enable; - if ( update ) { - if ( m_alwaysTabBar ) - setTabBarHidden(false); - else - hideTabBar(); - } -} - -#include "konq_tabs.moc" diff --git a/konqueror/konq_tabs.cpp b/konqueror/konq_tabs.cpp new file mode 100644 index 000000000..868b8edc9 --- /dev/null +++ b/konqueror/konq_tabs.cpp @@ -0,0 +1,609 @@ +/* This file is part of the KDE project + + Copyright (C) 2002-2003 Konqueror Developers + 2002-2003 Douglas Hanley + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. +*/ + +#include "konq_tabs.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "konq_frame.h" +#include "konq_view.h" +#include "konq_viewmgr.h" +#include "konq_misc.h" +#include "konq_settingsxt.h" + +#include +#include +#include +#include +#include +#include + +#define DUPLICATE_ID 3 +#define RELOAD_ID 4 +#define BREAKOFF_ID 5 +#define CLOSETAB_ID 6 +#define OTHERTABS_ID 7 +#define MOVE_LEFT_ID 8 +#define MOVE_RIGHT_ID 9 + +//################################################################### + +KonqFrameTabs::KonqFrameTabs(TQWidget* parent, KonqFrameContainerBase* parentContainer, + KonqViewManager* viewManager, const char * name) + : KTabWidget(parent, name), m_rightWidget(0), m_leftWidget(0), m_alwaysTabBar(false), + m_closeOtherTabsId(0) +{ + TDEAcceleratorManager::setNoAccel(this); + + TQWhatsThis::add( tabBar(), i18n( "This bar contains the list of currently open tabs. Click on a tab to make it " + "active. The option to show a close button instead of the website icon in the left " + "corner of the tab is configurable. You can also use keyboard shortcuts to " + "navigate through tabs. The text on the tab is the title of the website " + "currently open in it, put your mouse over the tab too see the full title in " + "case it was truncated to fit the tab size." ) ); + //kdDebug(1202) << "KonqFrameTabs::KonqFrameTabs()" << endl; + + m_pParentContainer = parentContainer; + m_pChildFrameList = new TQPtrList; + m_pChildFrameList->setAutoDelete(false); + m_pActiveChild = 0L; + m_pViewManager = viewManager; + + connect( this, TQT_SIGNAL( currentChanged ( TQWidget * ) ), + this, TQT_SLOT( slotCurrentChanged( TQWidget* ) ) ); + + m_pPopupMenu = new TQPopupMenu( this ); + m_pPopupMenu->insertItem( SmallIcon( "tab_new" ), + i18n("&New Tab"), + m_pViewManager->mainWindow(), + TQT_SLOT( slotAddTab() ), + m_pViewManager->mainWindow()->action("newtab")->shortcut() ); + m_pPopupMenu->insertItem( SmallIconSet( "reload" ), + i18n( "&Reload Tab" ), + m_pViewManager->mainWindow(), + TQT_SLOT( slotReloadPopup() ), + m_pViewManager->mainWindow()->action("reload")->shortcut(), RELOAD_ID ); + m_pPopupMenu->insertItem( SmallIconSet( "tab_duplicate" ), + i18n("&Duplicate Tab"), + m_pViewManager->mainWindow(), + TQT_SLOT( slotDuplicateTabPopup() ), + m_pViewManager->mainWindow()->action("duplicatecurrenttab")->shortcut(), + DUPLICATE_ID ); + m_pPopupMenu->insertItem( SmallIconSet( "tab_breakoff" ), + i18n("D&etach Tab"), + m_pViewManager->mainWindow(), + TQT_SLOT( slotBreakOffTabPopup() ), + m_pViewManager->mainWindow()->action("breakoffcurrenttab")->shortcut(), + BREAKOFF_ID ); + m_pPopupMenu->insertSeparator(); + m_pPopupMenu->insertItem( SmallIconSet( "tab_move_left" ), + i18n("Move Tab &Left"), + m_pViewManager->mainWindow(), + TQT_SLOT( slotMoveTabLeft() ), + m_pViewManager->mainWindow()->action("tab_move_left")->shortcut(), + MOVE_LEFT_ID ); + m_pPopupMenu->insertItem( SmallIconSet( "tab_move_right" ), + i18n("Move Tab &Right"), + m_pViewManager->mainWindow(), + TQT_SLOT( slotMoveTabRight() ), + m_pViewManager->mainWindow()->action("tab_move_right")->shortcut(), + MOVE_RIGHT_ID ); + m_pPopupMenu->insertSeparator(); + m_pSubPopupMenuTab = new TQPopupMenu( this ); + m_pPopupMenu->insertItem( i18n("Other Tabs" ), m_pSubPopupMenuTab, OTHERTABS_ID ); + connect( m_pSubPopupMenuTab, TQT_SIGNAL( activated ( int ) ), + this, TQT_SLOT( slotSubPopupMenuTabActivated( int ) ) ); + m_pPopupMenu->insertSeparator(); + m_pPopupMenu->insertItem( SmallIconSet( "tab_remove" ), + i18n("&Close Tab"), + m_pViewManager->mainWindow(), + TQT_SLOT( slotRemoveTabPopup() ), + m_pViewManager->mainWindow()->action("removecurrenttab")->shortcut(), + CLOSETAB_ID ); + connect( this, TQT_SIGNAL( contextMenu( TQWidget *, const TQPoint & ) ), + TQT_SLOT(slotContextMenu( TQWidget *, const TQPoint & ) ) ); + connect( this, TQT_SIGNAL( contextMenu( const TQPoint & ) ), + TQT_SLOT(slotContextMenu( const TQPoint & ) ) ); + + m_MouseMiddleClickClosesTab = KonqSettings::mouseMiddleClickClosesTab(); + + m_permanentCloseButtons = KonqSettings::permanentCloseButton(); + if (m_permanentCloseButtons) { + setHoverCloseButton( true ); + setHoverCloseButtonDelayed( false ); + } + else + setHoverCloseButton( KonqSettings::hoverCloseButton() ); + setTabCloseActivatePrevious( KonqSettings::tabCloseActivatePrevious() ); + if (KonqSettings::tabPosition()=="Bottom") + setTabPosition(TQTabWidget::Bottom); + connect( this, TQT_SIGNAL( closeRequest( TQWidget * )), TQT_SLOT(slotCloseRequest( TQWidget * ))); + connect( this, TQT_SIGNAL( removeTabPopup() ), + m_pViewManager->mainWindow(), TQT_SLOT( slotRemoveTabPopup() ) ); + + if ( KonqSettings::addTabButton() ) { + m_leftWidget = new TQToolButton( this ); + connect( m_leftWidget, TQT_SIGNAL( clicked() ), + m_pViewManager->mainWindow(), TQT_SLOT( slotAddTab() ) ); + m_leftWidget->setIconSet( SmallIcon( "tab_new" ) ); + m_leftWidget->adjustSize(); + TQToolTip::add(m_leftWidget, i18n("Open a new tab")); + setCornerWidget( m_leftWidget, TopLeft ); + } + if ( KonqSettings::closeTabButton() ) { + m_rightWidget = new TQToolButton( this ); + connect( m_rightWidget, TQT_SIGNAL( clicked() ), + m_pViewManager->mainWindow(), TQT_SLOT( slotRemoveTab() ) ); + m_rightWidget->setIconSet( SmallIconSet( "tab_remove" ) ); + m_rightWidget->adjustSize(); + TQToolTip::add(m_rightWidget, i18n("Close the current tab")); + setCornerWidget( m_rightWidget, TopRight ); + } + + setAutomaticResizeTabs( true ); + setTabReorderingEnabled( true ); + connect( this, TQT_SIGNAL( movedTab( int, int ) ), + TQT_SLOT( slotMovedTab( int, int ) ) ); + connect( this, TQT_SIGNAL( mouseMiddleClick() ), + TQT_SLOT( slotMouseMiddleClick() ) ); + connect( this, TQT_SIGNAL( mouseMiddleClick( TQWidget * ) ), + TQT_SLOT( slotMouseMiddleClick( TQWidget * ) ) ); + connect( this, TQT_SIGNAL( mouseDoubleClick() ), + m_pViewManager->mainWindow(), TQT_SLOT( slotAddTab() ) ); + + connect( this, TQT_SIGNAL( testCanDecode(const TQDragMoveEvent *, bool & )), + TQT_SLOT( slotTestCanDecode(const TQDragMoveEvent *, bool & ) ) ); + connect( this, TQT_SIGNAL( receivedDropEvent( TQDropEvent * )), + TQT_SLOT( slotReceivedDropEvent( TQDropEvent * ) ) ); + connect( this, TQT_SIGNAL( receivedDropEvent( TQWidget *, TQDropEvent * )), + TQT_SLOT( slotReceivedDropEvent( TQWidget *, TQDropEvent * ) ) ); + connect( this, TQT_SIGNAL( initiateDrag( TQWidget * )), + TQT_SLOT( slotInitiateDrag( TQWidget * ) ) ); + + setMouseWheelScroll(KonqSettings::tabsCycleWheel()); +} + +KonqFrameTabs::~KonqFrameTabs() +{ + //kdDebug(1202) << "KonqFrameTabs::~KonqFrameTabs() " << this << " - " << className() << endl; + m_pChildFrameList->setAutoDelete(true); + delete m_pChildFrameList; +} + +void KonqFrameTabs::listViews( ChildViewList *viewList ) { + for( TQPtrListIterator it( *m_pChildFrameList ); *it; ++it ) + it.current()->listViews(viewList); +} + +void KonqFrameTabs::saveConfig( TDEConfig* config, const TQString &prefix, bool saveURLs, + KonqFrameBase* docContainer, int id, int depth ) +{ + //write children + TQStringList strlst; + int i = 0; + TQString newPrefix; + for (KonqFrameBase* it = m_pChildFrameList->first(); it; it = m_pChildFrameList->next()) + { + newPrefix = TQString::fromLatin1( it->frameType() ) + "T" + TQString::number(i); + strlst.append( newPrefix ); + newPrefix.append( '_' ); + it->saveConfig( config, newPrefix, saveURLs, docContainer, id, depth + i ); + i++; + } + + config->writeEntry( TQString::fromLatin1( "Children" ).prepend( prefix ), strlst ); + + config->writeEntry( TQString::fromLatin1( "activeChildIndex" ).prepend( prefix ), + currentPageIndex() ); +} + +void KonqFrameTabs::copyHistory( KonqFrameBase *other ) +{ + if( other->frameType() != "Tabs" ) { + kdDebug(1202) << "Frame types are not the same" << endl; + return; + } + + for (uint i = 0; i < m_pChildFrameList->count(); i++ ) + { + m_pChildFrameList->at(i)->copyHistory( static_cast( other )->m_pChildFrameList->at(i) ); + } +} + +void KonqFrameTabs::printFrameInfo( const TQString& spaces ) +{ + kdDebug(1202) << spaces << "KonqFrameTabs " << this << " visible=" + << TQString("%1").arg(isVisible()) << " activeChild=" + << m_pActiveChild << endl; + + if (!m_pActiveChild) + kdDebug(1202) << "WARNING: " << this << " has a null active child!" << endl; + + KonqFrameBase* child; + int childFrameCount = m_pChildFrameList->count(); + for (int i = 0 ; i < childFrameCount ; i++) { + child = m_pChildFrameList->at(i); + if (child != 0L) + child->printFrameInfo(spaces + " "); + else + kdDebug(1202) << spaces << " Null child" << endl; + } +} + +void KonqFrameTabs::reparentFrame( TQWidget* parent, const TQPoint & p, bool showIt ) +{ + TQWidget::reparent( parent, p, showIt ); +} + +void KonqFrameTabs::setTitle( const TQString &title , TQWidget* sender) +{ + // kdDebug(1202) << "KonqFrameTabs::setTitle( " << title << " , " << sender << " )" << endl; + setTabLabel( sender,title ); +} + +void KonqFrameTabs::setTabIcon( const KURL &url, TQWidget* sender ) +{ + //kdDebug(1202) << "KonqFrameTabs::setTabIcon( " << url << " , " << sender << " )" << endl; + TQIconSet iconSet; + if (m_permanentCloseButtons) + iconSet = SmallIcon( "window-close" ); + else + iconSet = SmallIconSet( KonqPixmapProvider::self()->iconNameFor( url.url() ) ); + if (tabIconSet( sender ).pixmap().serialNumber() != iconSet.pixmap().serialNumber()) + setTabIconSet( sender, iconSet ); +} + +void KonqFrameTabs::activateChild() +{ + if (m_pActiveChild) + { + showPage( m_pActiveChild->widget() ); + m_pActiveChild->activateChild(); + } +} + +void KonqFrameTabs::insertChildFrame( KonqFrameBase* frame, int index ) +{ + //kdDebug(1202) << "KonqFrameTabs " << this << ": insertChildFrame " << frame << endl; + + if (frame) + { + //kdDebug(1202) << "Adding frame" << endl; + bool showTabBar = (count() == 1); + insertTab(frame->widget(),"", index); + frame->setParentContainer(this); + if (index == -1) m_pChildFrameList->append(frame); + else m_pChildFrameList->insert(index, frame); + if (m_rightWidget) + m_rightWidget->setEnabled( m_pChildFrameList->count()>1 ); + KonqView* activeChildView = frame->activeChildView(); + if (activeChildView != 0L) { + activeChildView->setCaption( activeChildView->caption() ); + activeChildView->setTabIcon( activeChildView->url() ); + } + if (showTabBar) + setTabBarHidden(false); + else if ( count() == 1 ) + this->hideTabBar();//the first frame inserted (initialization) + } + else + kdWarning(1202) << "KonqFrameTabs " << this << ": insertChildFrame(0L) !" << endl; +} + +void KonqFrameTabs::removeChildFrame( KonqFrameBase * frame ) +{ + //kdDebug(1202) << "KonqFrameTabs::RemoveChildFrame " << this << ". Child " << frame << " removed" << endl; + if (frame) { + removePage(frame->widget()); + m_pChildFrameList->remove(frame); + if (m_rightWidget) + m_rightWidget->setEnabled( m_pChildFrameList->count()>1 ); + if (count() == 1) + hideTabBar(); + } + else + kdWarning(1202) << "KonqFrameTabs " << this << ": removeChildFrame(0L) !" << endl; + + //kdDebug(1202) << "KonqFrameTabs::RemoveChildFrame finished" << endl; +} + +void KonqFrameTabs::slotCurrentChanged( TQWidget* newPage ) +{ + setTabColor( newPage, TDEGlobalSettings::textColor() ); + KonqFrameBase* currentFrame = tqt_dynamic_cast(newPage); + + if (currentFrame && !m_pViewManager->isLoadingProfile()) { + m_pActiveChild = currentFrame; + currentFrame->activateChild(); + } +} + +void KonqFrameTabs::moveTabBackward( int index ) +{ + if ( index == 0 ) + return; + moveTab( index, index-1 ); +} + +void KonqFrameTabs::moveTabForward( int index ) +{ + if ( index == count()-1 ) + return; + moveTab( index, index+1 ); +} + +void KonqFrameTabs::slotMovedTab( int from, int to ) +{ + KonqFrameBase* fromFrame = m_pChildFrameList->at( from ); + m_pChildFrameList->remove( fromFrame ); + m_pChildFrameList->insert( to, fromFrame ); + + KonqFrameBase* currentFrame = tqt_dynamic_cast( currentPage() ); + if ( currentFrame && !m_pViewManager->isLoadingProfile() ) { + m_pActiveChild = currentFrame; + currentFrame->activateChild(); + } +} + +void KonqFrameTabs::slotContextMenu( const TQPoint &p ) +{ + refreshSubPopupMenuTab(); + + m_pPopupMenu->setItemEnabled( RELOAD_ID, false ); + m_pPopupMenu->setItemEnabled( DUPLICATE_ID, false ); + m_pPopupMenu->setItemEnabled( BREAKOFF_ID, false ); + + uint tabCount = m_pChildFrameList->count(); + KonqView *kview = m_pViewManager->mainWindow()->currentView(); + if (tabCount>1 && kview) + { + // Move tab left + bool left_enable = false, right_enable = false; + if (TQApplication::reverseLayout()) + { + left_enable = (kview->frame() != m_pChildFrameList->last()); + right_enable= (kview->frame() != m_pChildFrameList->first()); + } + else + { + left_enable = (kview->frame() != m_pChildFrameList->first()); + right_enable= (kview->frame() != m_pChildFrameList->last()); + } + m_pPopupMenu->setItemEnabled( MOVE_LEFT_ID, left_enable); + m_pPopupMenu->setItemEnabled( MOVE_RIGHT_ID, right_enable); + } + else + { + m_pPopupMenu->setItemEnabled(MOVE_LEFT_ID, false); + m_pPopupMenu->setItemEnabled(MOVE_RIGHT_ID, false); + } + + m_pPopupMenu->setItemEnabled( CLOSETAB_ID, false ); + m_pPopupMenu->setItemEnabled( OTHERTABS_ID, true ); + m_pSubPopupMenuTab->setItemEnabled( m_closeOtherTabsId, false ); + + m_pPopupMenu->exec( p ); +} + +void KonqFrameTabs::slotContextMenu( TQWidget *w, const TQPoint &p ) +{ + refreshSubPopupMenuTab(); + + uint tabCount = m_pChildFrameList->count(); + m_pPopupMenu->setItemEnabled( RELOAD_ID, true ); + m_pPopupMenu->setItemEnabled( DUPLICATE_ID, true ); + m_pPopupMenu->setItemEnabled( BREAKOFF_ID, tabCount>1 ); + + KonqView *kview = m_pViewManager->mainWindow()->currentView(); + if (tabCount>1 && kview) + { + // Move tab left + bool left_enable = false, right_enable = false; + if (TQApplication::reverseLayout()) + { + left_enable = (kview->frame() != m_pChildFrameList->last()); + right_enable= (kview->frame() != m_pChildFrameList->first()); + } + else + { + left_enable = (kview->frame() != m_pChildFrameList->first()); + right_enable= (kview->frame() != m_pChildFrameList->last()); + } + m_pPopupMenu->setItemEnabled( MOVE_LEFT_ID, left_enable); + m_pPopupMenu->setItemEnabled( MOVE_RIGHT_ID, right_enable); + } + else + { + m_pPopupMenu->setItemEnabled(MOVE_LEFT_ID, false); + m_pPopupMenu->setItemEnabled(MOVE_RIGHT_ID, false); + } + + m_pPopupMenu->setItemEnabled( CLOSETAB_ID, tabCount>1 ); + m_pPopupMenu->setItemEnabled( OTHERTABS_ID, tabCount>1 ); + m_pSubPopupMenuTab->setItemEnabled( m_closeOtherTabsId, true ); + + // Yes, I know this is an unchecked tqt_dynamic_cast - I'm casting sideways in a + // class hierarchy and it could crash one day, but I haven't checked + // setWorkingTab so I don't know if it can handle nulls. + + m_pViewManager->mainWindow()->setWorkingTab( tqt_dynamic_cast(w) ); + m_pPopupMenu->exec( p ); +} + +void KonqFrameTabs::refreshSubPopupMenuTab() +{ + m_pSubPopupMenuTab->clear(); + int i=0; + m_pSubPopupMenuTab->insertItem( SmallIcon( "reload_all_tabs" ), + i18n( "&Reload All Tabs" ), + m_pViewManager->mainWindow(), + TQT_SLOT( slotReloadAllTabs() ), + m_pViewManager->mainWindow()->action("reload_all_tabs")->shortcut() ); + m_pSubPopupMenuTab->insertSeparator(); + for (KonqFrameBase* it = m_pChildFrameList->first(); it; it = m_pChildFrameList->next()) + { + KonqFrame* frame = dynamic_cast(it); + if ( frame && frame->activeChildView() ) + { + TQString title = frame->title().stripWhiteSpace(); + if ( title.isEmpty() ) + title = frame->activeChildView()->url().url(); + title = KStringHandler::csqueeze( title, 50 ); + m_pSubPopupMenuTab->insertItem( TQIconSet( KonqPixmapProvider::self()->pixmapFor( frame->activeChildView()->url().url() ) ), title, i ); + + } + i++; + } + m_pSubPopupMenuTab->insertSeparator(); + m_closeOtherTabsId = + m_pSubPopupMenuTab->insertItem( SmallIconSet( "tab_remove_other" ), + i18n( "Close &Other Tabs" ), + m_pViewManager->mainWindow(), + TQT_SLOT( slotRemoveOtherTabsPopup() ), + m_pViewManager->mainWindow()->action("removeothertabs")->shortcut() ); +} + +void KonqFrameTabs::slotCloseRequest( TQWidget *w ) +{ + if ( m_pChildFrameList->count() > 1 ) { + // Yes, I know this is an unchecked tqt_dynamic_cast - I'm casting sideways in a class hierarchy and it could crash one day, but I haven't checked setWorkingTab so I don't know if it can handle nulls. + m_pViewManager->mainWindow()->setWorkingTab( tqt_dynamic_cast(w) ); + emit ( removeTabPopup() ); + } +} + +void KonqFrameTabs::slotSubPopupMenuTabActivated( int _id) +{ + setCurrentPage( _id ); +} + +void KonqFrameTabs::slotMouseMiddleClick() +{ + TQApplication::clipboard()->setSelectionMode( TQClipboard::Selection ); + KURL filteredURL ( KonqMisc::konqFilteredURL( this, TQApplication::clipboard()->text() ) ); + if ( !filteredURL.isEmpty() ) { + KonqView* newView = m_pViewManager->addTab(TQString::null, TQString::null, false, false); + if (newView == 0L) return; + m_pViewManager->mainWindow()->openURL( newView, filteredURL, TQString::null ); + m_pViewManager->showTab( newView ); + m_pViewManager->mainWindow()->focusLocationBar(); + } +} + +void KonqFrameTabs::slotMouseMiddleClick( TQWidget *w ) +{ + if ( m_MouseMiddleClickClosesTab ) { + if ( m_pChildFrameList->count() > 1 ) { + // Yes, I know this is an unchecked tqt_dynamic_cast - I'm casting sideways in a class hierarchy and it could crash one day, but I haven't checked setWorkingTab so I don't know if it can handle nulls. + m_pViewManager->mainWindow()->setWorkingTab( tqt_dynamic_cast(w) ); + emit ( removeTabPopup() ); + } + } + else { + TQApplication::clipboard()->setSelectionMode( TQClipboard::Selection ); + KURL filteredURL ( KonqMisc::konqFilteredURL( this, TQApplication::clipboard()->text() ) ); + if ( !filteredURL.isEmpty() ) { + KonqFrameBase* frame = tqt_dynamic_cast(w); + if (frame) { + m_pViewManager->mainWindow()->openURL( frame->activeChildView(), filteredURL ); + } + } + } +} + +void KonqFrameTabs::slotTestCanDecode(const TQDragMoveEvent *e, bool &accept /* result */) +{ + accept = KURLDrag::canDecode( e ); +} + +void KonqFrameTabs::slotReceivedDropEvent( TQDropEvent *e ) +{ + KURL::List lstDragURLs; + bool ok = KURLDrag::decode( e, lstDragURLs ); + if ( ok && lstDragURLs.first().isValid() ) { + KonqView* newView = m_pViewManager->addTab(TQString::null, TQString::null, false, false); + if (newView == 0L) return; + m_pViewManager->mainWindow()->openURL( newView, lstDragURLs.first(), TQString::null ); + m_pViewManager->showTab( newView ); + m_pViewManager->mainWindow()->focusLocationBar(); + } +} + +void KonqFrameTabs::slotReceivedDropEvent( TQWidget *w, TQDropEvent *e ) +{ + KURL::List lstDragURLs; + bool ok = KURLDrag::decode( e, lstDragURLs ); + KonqFrameBase* frame = tqt_dynamic_cast(w); + if ( ok && lstDragURLs.first().isValid() && frame ) { + KURL lstDragURL = lstDragURLs.first(); + if ( lstDragURL != frame->activeChildView()->url() ) + m_pViewManager->mainWindow()->openURL( frame->activeChildView(), lstDragURL ); + } +} + +void KonqFrameTabs::slotInitiateDrag( TQWidget *w ) +{ + KonqFrameBase* frame = tqt_dynamic_cast( w ); + if (frame) { + KURL::List lst; + lst.append( frame->activeChildView()->url() ); + KURLDrag *d = new KURLDrag( lst, this ); + d->setPixmap( KMimeType::pixmapForURL( lst.first(), 0, TDEIcon::Small ) ); + d->dragCopy(); + } +} + +void KonqFrameTabs::hideTabBar() +{ + if ( !m_alwaysTabBar ) { + setTabBarHidden(true); + } + m_pPopupMenu->setItemEnabled( BREAKOFF_ID, false ); + m_pPopupMenu->setItemEnabled( MOVE_LEFT_ID, false ); + m_pPopupMenu->setItemEnabled( MOVE_RIGHT_ID, false ); + m_pPopupMenu->setItemEnabled( CLOSETAB_ID, false ); +} + +void KonqFrameTabs::setAlwaysTabbedMode( bool enable ) +{ + bool update = ( enable != m_alwaysTabBar ); + + m_alwaysTabBar = enable; + if ( update ) { + if ( m_alwaysTabBar ) + setTabBarHidden(false); + else + hideTabBar(); + } +} + +#include "konq_tabs.moc" diff --git a/konqueror/konq_view.cc b/konqueror/konq_view.cc deleted file mode 100644 index 3a970018b..000000000 --- a/konqueror/konq_view.cc +++ /dev/null @@ -1,1398 +0,0 @@ -/* - This file is part of the KDE project - Copyright (C) 1998-2005 David Faure - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - - -#include "konq_view.h" -#include "tdeapplication.h" -#include "KonqViewIface.h" -#include "konq_settingsxt.h" -#include "konq_frame.h" -#include "konq_run.h" -#include "konq_events.h" -#include "konq_viewmgr.h" -#include "konq_tabs.h" -#include "konq_browseriface.h" -#include -#include - -#include -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include - -//#define DEBUG_HISTORY - -template class TQPtrList; - -KonqView::KonqView( KonqViewFactory &viewFactory, - KonqFrame* viewFrame, - KonqMainWindow *mainWindow, - const KService::Ptr &service, - const TDETrader::OfferList &partServiceOffers, - const TDETrader::OfferList &appServiceOffers, - const TQString &serviceType, - bool passiveMode - ) -{ - m_pKonqFrame = viewFrame; - m_pKonqFrame->setView( this ); - - m_sLocationBarURL = ""; - m_pageSecurity = KonqMainWindow::NotCrypted; - m_bLockHistory = false; - m_doPost = false; - m_pMainWindow = mainWindow; - m_pRun = 0L; - m_pPart = 0L; - m_dcopObject = 0L; - - m_randID = TDEApplication::random(); - - m_service = service; - m_partServiceOffers = partServiceOffers; - m_appServiceOffers = appServiceOffers; - m_serviceType = serviceType; - - m_bAllowHTML = m_pMainWindow->isHTMLAllowed(); - m_lstHistory.setAutoDelete( true ); - m_bLoading = false; - m_bPendingRedirection = false; - m_bPassiveMode = passiveMode; - m_bLockedLocation = false; - m_bLinkedView = false; - m_bAborted = false; - m_bToggleView = false; - m_bHierarchicalView = false; - m_bDisableScrolling = false; - m_bGotIconURL = false; - m_bPopupMenuEnabled = true; - m_browserIface = new KonqBrowserInterface( this, "browseriface" ); - m_bBackRightClick = KonqSettings::backRightClick(); - m_bFollowActive = false; - m_bBuiltinView = false; - m_bURLDropHandling = false; - - switchView( viewFactory ); -} - -KonqView::~KonqView() -{ - //kdDebug(1202) << "KonqView::~KonqView : part = " << m_pPart << endl; - - if (KonqMainWindow::s_crashlog_file) { - TQString part_url; - if (m_pPart) - part_url = m_pPart->url().url(); - if (part_url.isNull()) - part_url = ""; - TQCString line; - line = ( TQString("close(%1):%2\n").arg(m_randID,0,16).arg(part_url) ).utf8(); - KonqMainWindow::s_crashlog_file->writeBlock(line, line.length()); - KonqMainWindow::s_crashlog_file->flush(); - } - - // We did so ourselves for passive views - if (m_pPart != 0L) - { - finishedWithCurrentURL(); - if ( isPassiveMode() ) - disconnect( m_pPart, TQT_SIGNAL( destroyed() ), m_pMainWindow->viewManager(), TQT_SLOT( slotObjectDestroyed() ) ); - - delete m_pPart; - } - - setRun( 0L ); - //kdDebug(1202) << "KonqView::~KonqView " << this << " done" << endl; -} - -void KonqView::openURL( const KURL &url, const TQString & locationBarURL, - const TQString & nameFilter, bool tempFile ) -{ - kdDebug(1202) << "KonqView::openURL url=" << url << " locationBarURL=" << locationBarURL << endl; - setServiceTypeInExtension(); - - if (KonqMainWindow::s_crashlog_file) { - TQString part_url; - if (m_pPart) - part_url = m_pPart->url().url(); - if (part_url.isNull()) - part_url = ""; - - TQString url_url = url.url(); - if (url_url.isNull()) - url_url = TQString(""); - - TQCString line; - - line = ( TQString("closed(%1):%2\n").arg(m_randID,0,16).arg(part_url) ).utf8(); - KonqMainWindow::s_crashlog_file->writeBlock(line,line.length()); - line = ( TQString("opened(%3):%4\n").arg(m_randID,0,16).arg(url_url) ).utf8(); - KonqMainWindow::s_crashlog_file->writeBlock(line,line.length()); - KonqMainWindow::s_crashlog_file->flush(); - } - - KParts::BrowserExtension *ext = browserExtension(); - KParts::URLArgs args; - if ( ext ) - args = ext->urlArgs(); - - // Typing "Enter" again after the URL of an aborted view, triggers a reload. - if ( m_bAborted && m_pPart && m_pPart->url() == url && !args.doPost()) - { - if ( !prepareReload( args ) ) - return; - if ( ext ) - ext->setURLArgs( args ); - } - -#ifdef DEBUG_HISTORY - kdDebug(1202) << "m_bLockedLocation=" << m_bLockedLocation << " args.lockHistory()=" << args.lockHistory() << endl; -#endif - if ( args.lockHistory() ) - lockHistory(); - - if ( !m_bLockHistory ) - { - // Store this new URL in the history, removing any existing forward history. - // We do this first so that everything is ready if a part calls completed(). - createHistoryEntry(); - } else - m_bLockHistory = false; - - callExtensionStringMethod( "setNameFilter(const TQString&)", nameFilter ); - if ( m_bDisableScrolling ) - callExtensionMethod( "disableScrolling()" ); - - setLocationBarURL( locationBarURL ); - setPageSecurity(KonqMainWindow::NotCrypted); - - if ( !args.reload ) - { - // Save the POST data that is necessary to open this URL - // (so that reload can re-post it) - m_doPost = args.doPost(); - m_postContentType = args.contentType(); - m_postData = args.postData; - // Save the referrer - m_pageReferrer = args.metaData()["referrer"]; - } - - if ( tempFile ) { - // Store the path to the tempfile. Yes, we could store a bool only, - // but this would be more dangerous. If anything goes wrong in the code, - // we might end up deleting a real file. - if ( url.isLocalFile() ) - m_tempFile = url.path(); - else - kdWarning(1202) << "Tempfile option is set, but URL is remote: " << url << endl; - } - - aboutToOpenURL( url, args ); - - m_pPart->openURL( url ); - - updateHistoryEntry(false /* don't save location bar URL yet */); - // add pending history entry - KonqHistoryManager::kself()->addPending( url, locationBarURL, TQString::null); - -#ifdef DEBUG_HISTORY - kdDebug(1202) << "Current position : " << m_lstHistory.at() << endl; -#endif -} - -void KonqView::switchView( KonqViewFactory &viewFactory ) -{ - kdDebug(1202) << "KonqView::switchView" << endl; - if ( m_pPart ) - m_pPart->widget()->hide(); - - KParts::ReadOnlyPart *oldPart = m_pPart; - m_pPart = m_pKonqFrame->attach( viewFactory ); // creates the part - - // Set the statusbar in the BE asap to avoid a TDEMainWindow statusbar being created. - KParts::StatusBarExtension* sbext = statusBarExtension(); - if ( sbext ) - sbext->setStatusBar( frame()->statusbar() ); - - // Activate the new part - if ( oldPart ) - { - m_pPart->setName( oldPart->name() ); - emit sigPartChanged( this, oldPart, m_pPart ); - delete oldPart; - } - - connectPart(); - - TQVariant prop; - - prop = m_service->property( "X-TDE-BrowserView-FollowActive"); - if (prop.isValid() && prop.toBool()) - { - //kdDebug(1202) << "KonqView::switchView X-TDE-BrowserView-FollowActive -> setFollowActive" <property( "X-TDE-BrowserView-Built-Into" ); - m_bBuiltinView = (prop.isValid() && prop.toString() == "konqueror"); - - if ( !m_pMainWindow->viewManager()->isLoadingProfile() ) - { - // Honour "non-removeable passive mode" (like the dirtree) - prop = m_service->property( "X-TDE-BrowserView-PassiveMode"); - if ( prop.isValid() && prop.toBool() ) - { - kdDebug(1202) << "KonqView::switchView X-TDE-BrowserView-PassiveMode -> setPassiveMode" << endl; - setPassiveMode( true ); // set as passive - } - - // Honour "linked view" - prop = m_service->property( "X-TDE-BrowserView-LinkedView"); - if ( prop.isValid() && prop.toBool() ) - { - setLinkedView( true ); // set as linked - // Two views : link both - if (m_pMainWindow->viewCount() <= 2) // '1' can happen if this view is not yet in the map - { - KonqView * otherView = m_pMainWindow->otherView( this ); - if (otherView) - otherView->setLinkedView( true ); - } - } - } - - prop = m_service->property( "X-TDE-BrowserView-HierarchicalView"); - if ( prop.isValid() && prop.toBool() ) - { - kdDebug() << "KonqView::switchView X-TDE-BrowserView-HierarchicalView -> setHierarchicalView" << endl; - setHierarchicalView( true ); // set as hierarchial - } - else - { - setHierarchicalView( false ); - } -} - -bool KonqView::changeViewMode( const TQString &serviceType, - const TQString &serviceName, - bool forceAutoEmbed ) -{ - // Caller should call stop first. - assert ( !m_bLoading ); - - kdDebug(1202) << "changeViewMode: serviceType is " << serviceType - << " serviceName is " << serviceName - << " current service name is " << m_service->desktopEntryName() << endl; - - if ( KMimeType::mimeType(serviceType)->is(m_serviceType) && (serviceName.isEmpty() || serviceName == m_service->desktopEntryName()) ) - return true; - - if ( isLockedViewMode() ) - { - //kdDebug(1202) << "This view's mode is locked - can't change" << endl; - return false; // we can't do that if our view mode is locked - } - - kdDebug(1202) << "Switching view modes..." << endl; - TDETrader::OfferList partServiceOffers, appServiceOffers; - KService::Ptr service = 0L; - KonqViewFactory viewFactory = KonqFactory::createView( serviceType, serviceName, &service, &partServiceOffers, &appServiceOffers, forceAutoEmbed ); - - if ( viewFactory.isNull() ) - { - // Revert location bar's URL to the working one - if(history().current()) - setLocationBarURL( history().current()->locationBarURL ); - return false; - } - - m_serviceType = serviceType; - m_partServiceOffers = partServiceOffers; - m_appServiceOffers = appServiceOffers; - - // Check if that's already the kind of part we have -> no need to recreate it - // Note: we should have an operator= for KService... - if ( m_service && m_service->desktopEntryPath() == service->desktopEntryPath() ) - { - kdDebug( 1202 ) << "KonqView::changeViewMode. Reusing service. Service type set to " << m_serviceType << endl; - if ( m_pMainWindow->currentView() == this ) - m_pMainWindow->updateViewModeActions(); - } - else - { - m_service = service; - - switchView( viewFactory ); - } - - if ( m_pMainWindow->viewManager()->activePart() != m_pPart ) - { - // Make the new part active. Note that we don't do it each time we - // open a URL (becomes awful in view-follows-view mode), but we do - // each time we change the view mode. - // We don't do it in switchView either because it's called from the constructor too, - // where the location bar url isn't set yet. - //kdDebug(1202) << "Giving focus to new part " << m_pPart << endl; - m_pMainWindow->viewManager()->setActivePart( m_pPart ); - } - return true; -} - -void KonqView::connectPart( ) -{ - //kdDebug(1202) << "KonqView::connectPart" << endl; - connect( m_pPart, TQT_SIGNAL( started( TDEIO::Job * ) ), - this, TQT_SLOT( slotStarted( TDEIO::Job * ) ) ); - connect( m_pPart, TQT_SIGNAL( completed() ), - this, TQT_SLOT( slotCompleted() ) ); - connect( m_pPart, TQT_SIGNAL( completed(bool) ), - this, TQT_SLOT( slotCompleted(bool) ) ); - connect( m_pPart, TQT_SIGNAL( canceled( const TQString & ) ), - this, TQT_SLOT( slotCanceled( const TQString & ) ) ); - connect( m_pPart, TQT_SIGNAL( setWindowCaption( const TQString & ) ), - this, TQT_SLOT( setCaption( const TQString & ) ) ); - - KParts::BrowserExtension *ext = browserExtension(); - - if ( ext ) - { - ext->setBrowserInterface( m_browserIface ); - - connect( ext, TQT_SIGNAL( openURLRequestDelayed( const KURL &, const KParts::URLArgs &) ), - m_pMainWindow, TQT_SLOT( slotOpenURLRequest( const KURL &, const KParts::URLArgs & ) ) ); - - if ( m_bPopupMenuEnabled ) - { - m_bPopupMenuEnabled = false; // force - enablePopupMenu( true ); - } - - connect( ext, TQT_SIGNAL( setLocationBarURL( const TQString & ) ), - this, TQT_SLOT( setLocationBarURL( const TQString & ) ) ); - - connect( ext, TQT_SIGNAL( setIconURL( const KURL & ) ), - this, TQT_SLOT( setIconURL( const KURL & ) ) ); - - connect( ext, TQT_SIGNAL( setPageSecurity( int ) ), - this, TQT_SLOT( setPageSecurity( int ) ) ); - - connect( ext, TQT_SIGNAL( createNewWindow( const KURL &, const KParts::URLArgs & ) ), - m_pMainWindow, TQT_SLOT( slotCreateNewWindow( const KURL &, const KParts::URLArgs & ) ) ); - - connect( ext, TQT_SIGNAL( createNewWindow( const KURL &, const KParts::URLArgs &, const KParts::WindowArgs &, KParts::ReadOnlyPart *& ) ), - m_pMainWindow, TQT_SLOT( slotCreateNewWindow( const KURL &, const KParts::URLArgs &, const KParts::WindowArgs &, KParts::ReadOnlyPart *& ) ) ); - - connect( ext, TQT_SIGNAL( loadingProgress( int ) ), - m_pKonqFrame->statusbar(), TQT_SLOT( slotLoadingProgress( int ) ) ); - - connect( ext, TQT_SIGNAL( speedProgress( int ) ), - m_pKonqFrame->statusbar(), TQT_SLOT( slotSpeedProgress( int ) ) ); - - connect( ext, TQT_SIGNAL( selectionInfo( const KFileItemList & ) ), - this, TQT_SLOT( slotSelectionInfo( const KFileItemList & ) ) ); - - connect( ext, TQT_SIGNAL( mouseOverInfo( const KFileItem * ) ), - this, TQT_SLOT( slotMouseOverInfo( const KFileItem * ) ) ); - - connect( ext, TQT_SIGNAL( openURLNotify() ), - this, TQT_SLOT( slotOpenURLNotify() ) ); - - connect( ext, TQT_SIGNAL( enableAction( const char *, bool ) ), - this, TQT_SLOT( slotEnableAction( const char *, bool ) ) ); - - connect( ext, TQT_SIGNAL( setActionText( const char *, const TQString& ) ), - this, TQT_SLOT( slotSetActionText( const char *, const TQString& ) ) ); - - connect( ext, TQT_SIGNAL( moveTopLevelWidget( int, int ) ), - this, TQT_SLOT( slotMoveTopLevelWidget( int, int ) ) ); - - connect( ext, TQT_SIGNAL( resizeTopLevelWidget( int, int ) ), - this, TQT_SLOT( slotResizeTopLevelWidget( int, int ) ) ); - - connect( ext, TQT_SIGNAL( requestFocus(KParts::ReadOnlyPart *) ), - this, TQT_SLOT( slotRequestFocus(KParts::ReadOnlyPart *) ) ); - - if (service()->desktopEntryName() != "konq_sidebartng") { - connect( ext, TQT_SIGNAL( infoMessage( const TQString & ) ), - m_pKonqFrame->statusbar(), TQT_SLOT( message( const TQString & ) ) ); - - connect( ext, - TQT_SIGNAL( addWebSideBar(const KURL&, const TQString&) ), - m_pMainWindow, - TQT_SLOT( slotAddWebSideBar(const KURL&, const TQString&) ) ); - } - - callExtensionBoolMethod( "setSaveViewPropertiesLocally(bool)", m_pMainWindow->saveViewPropertiesLocally() ); - } - - TQVariant urlDropHandling; - - if ( ext ) - urlDropHandling = ext->property( "urlDropHandling" ); - else - urlDropHandling = TQVariant( true ); - - // Handle url drops if - // a) either the property says "ok" - // or - // b) the part is a plain krop (no BE) - m_bURLDropHandling = ( urlDropHandling.type() == TQVariant::Bool && - urlDropHandling.toBool() ); - - m_pPart->widget()->installEventFilter( this ); - - if (m_bBackRightClick && m_pPart->widget()->inherits(TQSCROLLVIEW_OBJECT_NAME_STRING) ) - { - (static_cast(m_pPart->widget()))->viewport()->installEventFilter( this ); - } - - // KonqDirPart signal - if ( m_pPart->inherits("KonqDirPart") ) - { - connect( m_pPart, TQT_SIGNAL( findOpen( KonqDirPart * ) ), - m_pMainWindow, TQT_SLOT( slotFindOpen( KonqDirPart * ) ) ); - } -} - -void KonqView::slotEnableAction( const char * name, bool enabled ) -{ - if ( m_pMainWindow->currentView() == this ) - m_pMainWindow->enableAction( name, enabled ); - // Otherwise, we don't have to do anything, the state of the action is - // stored inside the browser-extension. -} - -void KonqView::slotSetActionText( const char* name, const TQString& text ) -{ - if ( m_pMainWindow->currentView() == this ) - m_pMainWindow->setActionText( name, text ); - // Otherwise, we don't have to do anything, the state of the action is - // stored inside the browser-extension. -} - -void KonqView::slotMoveTopLevelWidget( int x, int y ) -{ - KonqFrameContainerBase* container = frame()->parentContainer(); - // If tabs are shown, only accept to move the whole window if there's only one tab. - if ( container->frameType() != "Tabs" || static_cast(container)->count() == 1 ) - m_pMainWindow->move( x, y ); -} - -void KonqView::slotResizeTopLevelWidget( int w, int h ) -{ - KonqFrameContainerBase* container = frame()->parentContainer(); - // If tabs are shown, only accept to resize the whole window if there's only one tab. - // ### Maybe we could store the size requested by each tab and resize the window to the biggest one. - if ( container->frameType() != "Tabs" || static_cast(container)->count() == 1 ) - m_pMainWindow->resize( w, h ); -} - -void KonqView::slotStarted( TDEIO::Job * job ) -{ - //kdDebug(1202) << "KonqView::slotStarted" << job << endl; - setLoading( true ); - - if (job) - { - // Manage passwords properly... - if (m_pMainWindow) - { - kdDebug(7035) << "slotStarted: Window ID = " << m_pMainWindow->topLevelWidget()->winId() << endl; - job->setWindow (m_pMainWindow->topLevelWidget ()); - } - - connect( job, TQT_SIGNAL( percent( TDEIO::Job *, unsigned long ) ), this, TQT_SLOT( slotPercent( TDEIO::Job *, unsigned long ) ) ); - connect( job, TQT_SIGNAL( speed( TDEIO::Job *, unsigned long ) ), this, TQT_SLOT( slotSpeed( TDEIO::Job *, unsigned long ) ) ); - connect( job, TQT_SIGNAL( infoMessage( TDEIO::Job *, const TQString & ) ), this, TQT_SLOT( slotInfoMessage( TDEIO::Job *, const TQString & ) ) ); - } -} - -void KonqView::slotRequestFocus( KParts::ReadOnlyPart * ) -{ - m_pMainWindow->viewManager()->showTab(this); -} - -void KonqView::setLoading( bool loading, bool hasPending /*= false*/) -{ - //kdDebug(1202) << "KonqView::setLoading loading=" << loading << " hasPending=" << hasPending << endl; - m_bLoading = loading; - m_bPendingRedirection = hasPending; - if ( m_pMainWindow->currentView() == this ) - m_pMainWindow->updateToolBarActions( hasPending ); - - m_pMainWindow->viewManager()->setLoading( this, loading || hasPending ); -} - -void KonqView::slotPercent( TDEIO::Job *, unsigned long percent ) -{ - m_pKonqFrame->statusbar()->slotLoadingProgress( percent ); -} - -void KonqView::slotSpeed( TDEIO::Job *, unsigned long bytesPerSecond ) -{ - m_pKonqFrame->statusbar()->slotSpeedProgress( bytesPerSecond ); -} - -void KonqView::slotInfoMessage( TDEIO::Job *, const TQString &msg ) -{ - m_pKonqFrame->statusbar()->message( msg ); -} - -void KonqView::slotCompleted() -{ - slotCompleted( false ); -} - -void KonqView::slotCompleted( bool hasPending ) -{ - //kdDebug(1202) << "KonqView::slotCompleted hasPending=" << hasPending << endl; - m_pKonqFrame->statusbar()->slotLoadingProgress( -1 ); - - if ( ! m_bLockHistory ) - { - // Success... update history entry, including location bar URL - updateHistoryEntry( true ); - - if ( m_bAborted ) // remove the pending entry on error - KonqHistoryManager::kself()->removePending( url() ); - else if ( m_lstHistory.current() ) // register as proper history entry - KonqHistoryManager::kself()->confirmPending(url(), typedURL(), - m_lstHistory.current()->title); - - emit viewCompleted( this ); - } - setLoading( false, hasPending ); - - if (!m_bGotIconURL && !m_bAborted) - { - if ( KonqSettings::enableFavicon() == true ) - { - // Try to get /favicon.ico - if ( supportsServiceType( "text/html" ) && url().protocol().startsWith( "http" ) ) - KonqPixmapProvider::downloadHostIcon( url() ); - } - } -} - -void KonqView::slotCanceled( const TQString & errorMsg ) -{ - kdDebug(1202) << "KonqView::slotCanceled" << endl; - // The errorMsg comes from the ReadOnlyPart's job. - // It should probably be used in a KMessageBox - // Let's use the statusbar for now - m_pKonqFrame->statusbar()->message( errorMsg ); - m_bAborted = true; - slotCompleted(); -} - -void KonqView::slotSelectionInfo( const KFileItemList &items ) -{ - KonqFileSelectionEvent ev( items, m_pPart ); - TQApplication::sendEvent( m_pMainWindow, &ev ); -} - -void KonqView::slotMouseOverInfo( const KFileItem *item ) -{ - KonqFileMouseOverEvent ev( item, m_pPart ); - TQApplication::sendEvent( m_pMainWindow, &ev ); -} - -void KonqView::setLocationBarURL( const KURL& locationBarURL ) -{ - setLocationBarURL( locationBarURL.pathOrURL() ); -} - -void KonqView::setLocationBarURL( const TQString & locationBarURL ) -{ - //kdDebug(1202) << "KonqView::setLocationBarURL " << locationBarURL << " this=" << this << endl; - - m_sLocationBarURL = locationBarURL; - if ( m_pMainWindow->currentView() == this ) - { - //kdDebug(1202) << "is current view " << this << endl; - m_pMainWindow->setLocationBarURL( m_sLocationBarURL ); - m_pMainWindow->setPageSecurity( m_pageSecurity ); - } - if (!m_bPassiveMode) setTabIcon( KURL::fromPathOrURL( m_sLocationBarURL ) ); -} - -void KonqView::setIconURL( const KURL & iconURL ) -// This function sets the favIcon in konqui's window if enabled, -// thus it is responsible for the icon in the taskbar. -// It does not set the tab's favIcon. -{ - kdDebug(1202) << "entering KonqView::setIconURL" << endl; - if ( KonqSettings::enableFavicon() ) - { - KonqPixmapProvider::setIconForURL( KURL( m_sLocationBarURL ), iconURL ); - m_bGotIconURL = true; - } -} - -void KonqView::setPageSecurity( int pageSecurity ) -{ - m_pageSecurity = (KonqMainWindow::PageSecurity)pageSecurity; - - if ( m_pMainWindow->currentView() == this ) - m_pMainWindow->setPageSecurity( m_pageSecurity ); -} - -void KonqView::setTabIcon( const KURL &url ) -{ - if (!m_bPassiveMode) frame()->setTabIcon( url, 0L ); -} - -void KonqView::setCaption( const TQString & caption ) -{ - if (caption.isEmpty()) return; - - TQString adjustedCaption = caption; - // For local URLs we prefer to use only the directory name - if (url().isLocalFile()) - { - // Is the caption a URL? If so, is it local? If so, only display the filename! - KURL url = KURL::fromPathOrURL(caption); - if (url.isValid() && url.isLocalFile() && url.fileName() == this->url().fileName()) - adjustedCaption = url.fileName(); - } - - m_caption = adjustedCaption; - if (!m_bPassiveMode) frame()->setTitle( adjustedCaption , 0L ); -} - -void KonqView::slotOpenURLNotify() -{ -#ifdef DEBUG_HISTORY - kdDebug(1202) << "KonqView::slotOpenURLNotify" << endl; -#endif - updateHistoryEntry(true); - createHistoryEntry(); - if ( m_pMainWindow->currentView() == this ) - m_pMainWindow->updateToolBarActions(); -} - -void KonqView::createHistoryEntry() -{ - // First, remove any forward history - HistoryEntry * current = m_lstHistory.current(); - if (current) - { -#ifdef DEBUG_HISTORY - kdDebug(1202) << "Truncating history" << endl; -#endif - m_lstHistory.at( m_lstHistory.count() - 1 ); // go to last one - for ( ; m_lstHistory.current() != current ; ) - { - if ( !m_lstHistory.removeLast() ) // and remove from the end (faster and easier) - assert(0); - // go to last one. The documentation says that removeLast() - // makes current() null if it's the last item. however in qt2 - // the behaviour was different than the documentation. this is - // changed in qt3 to behave as documented ;-) (Simon) - m_lstHistory.at( m_lstHistory.count() - 1 ); - } - // Now current is the current again. - } - // Append a new entry -#ifdef DEBUG_HISTORY - kdDebug(1202) << "Append a new entry" << endl; -#endif - m_lstHistory.append( new HistoryEntry ); // made current -#ifdef DEBUG_HISTORY - kdDebug(1202) << "at=" << m_lstHistory.at() << " count=" << m_lstHistory.count() << endl; -#endif - assert( m_lstHistory.at() == (int) m_lstHistory.count() - 1 ); -} - -void KonqView::updateHistoryEntry( bool saveLocationBarURL ) -{ - Q_ASSERT( !m_bLockHistory ); // should never happen - - HistoryEntry * current = m_lstHistory.current(); - if ( !current ) - return; - - if ( browserExtension() ) - { - current->buffer = TQByteArray(); // Start with empty buffer. - TQDataStream stream( current->buffer, IO_WriteOnly ); - - browserExtension()->saveState( stream ); - } - -#ifdef DEBUG_HISTORY - kdDebug(1202) << "Saving part URL : " << m_pPart->url() << " in history position " << m_lstHistory.at() << endl; -#endif - current->url = m_pPart->url(); - - if (saveLocationBarURL) - { -#ifdef DEBUG_HISTORY - kdDebug(1202) << "Saving location bar URL : " << m_sLocationBarURL << " in history position " << m_lstHistory.at() << endl; -#endif - current->locationBarURL = m_sLocationBarURL; - current->pageSecurity = m_pageSecurity; - } -#ifdef DEBUG_HISTORY - kdDebug(1202) << "Saving title : " << m_caption << " in history position " << m_lstHistory.at() << endl; -#endif - current->title = m_caption; - current->strServiceType = m_serviceType; - current->strServiceName = m_service->desktopEntryName(); - - current->doPost = m_doPost; - current->postData = m_doPost ? m_postData : TQByteArray(); - current->postContentType = m_doPost ? m_postContentType : TQString::null; - current->pageReferrer = m_pageReferrer; -} - -void KonqView::goHistory( int steps ) -{ - // This is called by KonqBrowserInterface - if ( m_pMainWindow->currentView() == this ) - m_pMainWindow->viewManager()->setActivePart( part() ); - - // Delay the go() call (we need to return to the caller first) - m_pMainWindow->slotGoHistoryActivated( steps ); -} - -void KonqView::go( int steps ) -{ - if ( !steps ) // [WildFox] i bet there are sites on the net with stupid devs who do that :) - { -#ifdef DEBUG_HISTORY - kdDebug(1202) << "KonqView::go(0)" << endl; -#endif - // [David] and you're right. And they expect that it reloads, apparently. - // [George] I'm going to make nspluginviewer rely on this too. :-) - m_pMainWindow->slotReload(); - return; - } - - int newPos = m_lstHistory.at() + steps; -#ifdef DEBUG_HISTORY - kdDebug(1202) << "go : steps=" << steps - << " newPos=" << newPos - << " m_lstHistory.count()=" << m_lstHistory.count() - << endl; -#endif - if( newPos < 0 || (uint)newPos >= m_lstHistory.count() ) - return; - - stop(); - - // Yay, we can move there without a loop ! - HistoryEntry *currentHistoryEntry = m_lstHistory.at( newPos ); // sets current item - - assert( currentHistoryEntry ); - assert( newPos == m_lstHistory.at() ); // check we moved (i.e. if I understood the docu) - assert( currentHistoryEntry == m_lstHistory.current() ); -#ifdef DEBUG_HISTORY - kdDebug(1202) << "New position " << m_lstHistory.at() << endl; -#endif - - restoreHistory(); -} - -void KonqView::restoreHistory() -{ - HistoryEntry h( *(m_lstHistory.current()) ); // make a copy of the current history entry, as the data - // the pointer points to will change with the following calls - -#ifdef DEBUG_HISTORY - kdDebug(1202) << "Restoring servicetype/name, and location bar URL from history : " << h.locationBarURL << endl; -#endif - setLocationBarURL( h.locationBarURL ); - setPageSecurity( h.pageSecurity ); - m_sTypedURL = TQString::null; - if ( ! changeViewMode( h.strServiceType, h.strServiceName ) ) - { - kdWarning(1202) << "Couldn't change view mode to " << h.strServiceType - << " " << h.strServiceName << endl; - return /*false*/; - } - - setServiceTypeInExtension(); - - aboutToOpenURL( h.url ); - - if ( browserExtension() ) - { - //kdDebug(1202) << "Restoring view from stream" << endl; - TQDataStream stream( h.buffer, IO_ReadOnly ); - - browserExtension()->restoreState( stream ); - - m_doPost = h.doPost; - m_postContentType = h.postContentType; - m_postData = h.postData; - m_pageReferrer = h.pageReferrer; - } - else - m_pPart->openURL( h.url ); - - if ( m_pMainWindow->currentView() == this ) - m_pMainWindow->updateToolBarActions(); - -#ifdef DEBUG_HISTORY - kdDebug(1202) << "New position (2) " << m_lstHistory.at() << endl; -#endif -} - -const HistoryEntry * KonqView::historyAt(const int pos) -{ - if(pos<0 || pos>=(int)m_lstHistory.count()) - return 0L; - int oldpos = m_lstHistory.at(); - const HistoryEntry* h = m_lstHistory.at(pos); - m_lstHistory.at( oldpos ); - return h; -} - -void KonqView::copyHistory( KonqView *other ) -{ - m_lstHistory.clear(); - - TQPtrListIterator it( other->m_lstHistory ); - for (; it.current(); ++it ) - m_lstHistory.append( new HistoryEntry( *it.current() ) ); - m_lstHistory.at(other->m_lstHistory.at()); -} - -KURL KonqView::url() const -{ - assert( m_pPart ); - return m_pPart->url(); -} - -KURL KonqView::upURL() const -{ - KURL currentURL; - if ( m_pRun ) - currentURL = m_pRun->url(); - else - currentURL = KURL::fromPathOrURL( m_sLocationBarURL ); - return currentURL.upURL(); -} - -void KonqView::setRun( KonqRun * run ) -{ - if ( m_pRun ) - { - // Tell the KonqRun to abort, but don't delete it ourselves. - // It could be showing a message box right now. It will delete itself anyway. - m_pRun->abort(); - // finish() will be emitted later (when back to event loop) - // and we don't want it to call slotRunFinished (which stops the animation and stop button). - m_pRun->disconnect( m_pMainWindow ); - if ( !run ) - frame()->unsetCursor(); - } - else if ( run ) - frame()->setCursor( KCursor::workingCursor() ); - m_pRun = run; -} - -void KonqView::stop() -{ - //kdDebug(1202) << "KonqView::stop()" << endl; - m_bAborted = false; - finishedWithCurrentURL(); - if ( m_bLoading || m_bPendingRedirection ) - { - // aborted -> confirm the pending url. We might as well remove it, but - // we decided to keep it :) - KonqHistoryManager::kself()->confirmPending( url(), m_sTypedURL ); - - //kdDebug(1202) << "m_pPart->closeURL()" << endl; - m_pPart->closeURL(); - m_bAborted = true; - m_pKonqFrame->statusbar()->slotLoadingProgress( -1 ); - setLoading( false, false ); - } - if ( m_pRun ) - { - // Revert to working URL - unless the URL was typed manually - // This is duplicated with KonqMainWindow::slotRunFinished, but we can't call it - // since it relies on sender()... - if ( history().current() && m_pRun->typedURL().isEmpty() ) { // not typed - setLocationBarURL( history().current()->locationBarURL ); - setPageSecurity( history().current()->pageSecurity ); - } - - setRun( 0L ); - m_pKonqFrame->statusbar()->slotLoadingProgress( -1 ); - } - if ( !m_bLockHistory && m_lstHistory.count() > 0 ) - updateHistoryEntry(true); -} - -void KonqView::finishedWithCurrentURL() -{ - if ( !m_tempFile.isEmpty() ) - { - kdDebug(1202) << "######### Deleting tempfile after use:" << m_tempFile << endl; - TQFile::remove( m_tempFile ); - m_tempFile = TQString::null; - } -} - -void KonqView::setPassiveMode( bool mode ) -{ - // In theory, if m_bPassiveMode is true and mode is false, - // the part should be removed from the part manager, - // and if the other way round, it should be readded to the part manager... - m_bPassiveMode = mode; - - if ( mode && m_pMainWindow->viewCount() > 1 && m_pMainWindow->currentView() == this ) - { - KParts::Part * part = m_pMainWindow->viewManager()->chooseNextView( this )->part(); // switch active part - m_pMainWindow->viewManager()->setActivePart( part ); - } - - // Update statusbar stuff - m_pMainWindow->viewManager()->viewCountChanged(); -} - -void KonqView::setHierarchicalView( bool mode ) -{ - m_bHierarchicalView=mode; -} - - - -void KonqView::setLinkedView( bool mode ) -{ - m_bLinkedView = mode; - if ( m_pMainWindow->currentView() == this ) - m_pMainWindow->linkViewAction()->setChecked( mode ); - frame()->statusbar()->setLinkedView( mode ); -} - -void KonqView::setLockedLocation( bool b ) -{ - m_bLockedLocation = b; -} - -void KonqView::aboutToOpenURL( const KURL &url, const KParts::URLArgs &args ) -{ - KParts::OpenURLEvent ev( m_pPart, url, args ); - TQApplication::sendEvent( m_pMainWindow, &ev ); - - m_bGotIconURL = false; - m_bAborted = false; -} - -void KonqView::setServiceTypeInExtension() -{ - KParts::BrowserExtension *ext = browserExtension(); - if ( !ext ) - return; - - KParts::URLArgs args( ext->urlArgs() ); - args.serviceType = m_serviceType; - ext->setURLArgs( args ); -} - -TQStringList KonqView::frameNames() const -{ - return childFrameNames( m_pPart ); -} - -TQStringList KonqView::childFrameNames( KParts::ReadOnlyPart *part ) -{ - TQStringList res; - - KParts::BrowserHostExtension *hostExtension = KParts::BrowserHostExtension::childObject( part ); - - if ( !hostExtension ) - return res; - - res += hostExtension->frameNames(); - - const TQPtrList children = hostExtension->frames(); - TQPtrListIterator it( children ); - for (; it.current(); ++it ) - res += childFrameNames( it.current() ); - - return res; -} - -KParts::BrowserHostExtension* KonqView::hostExtension( KParts::ReadOnlyPart *part, const TQString &name ) -{ - KParts::BrowserHostExtension *ext = KParts::BrowserHostExtension::childObject( part ); - - if ( !ext ) - return 0; - - if ( ext->frameNames().contains( name ) ) - return ext; - - const TQPtrList children = ext->frames(); - TQPtrListIterator it( children ); - for (; it.current(); ++it ) - { - KParts::BrowserHostExtension *childHost = hostExtension( it.current(), name ); - if ( childHost ) - return childHost; - } - - return 0; -} - -bool KonqView::callExtensionMethod( const char *methodName ) -{ - TQObject *obj = KParts::BrowserExtension::childObject( m_pPart ); - if ( !obj ) // not all views have a browser extension ! - return false; - - int id = obj->metaObject()->findSlot( methodName ); - if ( id == -1 ) - return false; - TQUObject o[ 1 ]; - - obj->tqt_invoke( id, o ); - return true; -} - -bool KonqView::callExtensionBoolMethod( const char *methodName, bool value ) -{ - TQObject *obj = KParts::BrowserExtension::childObject( m_pPart ); - if ( !obj ) // not all views have a browser extension ! - return false; - - int id = obj->metaObject()->findSlot( methodName ); - if ( id == -1 ) - return false; - TQUObject o[ 2 ]; - - static_TQUType_bool.set( o + 1, value ); - - obj->tqt_invoke( id, o ); - return true; -} - -bool KonqView::callExtensionStringMethod( const char *methodName, TQString value ) -{ - TQObject *obj = KParts::BrowserExtension::childObject( m_pPart ); - if ( !obj ) // not all views have a browser extension ! - return false; - - int id = obj->metaObject()->findSlot( methodName ); - if ( id == -1 ) - return false; - TQUObject o[ 2 ]; - - static_TQUType_TQString.set( o + 1, value ); - - obj->tqt_invoke( id, o ); - return true; -} - -bool KonqView::callExtensionURLMethod( const char *methodName, const KURL& value ) -{ - TQObject *obj = KParts::BrowserExtension::childObject( m_pPart ); - if ( !obj ) // not all views have a browser extension ! - return false; - - int id = obj->metaObject()->findSlot( methodName ); - if ( id == -1 ) - return false; - TQUObject o[ 2 ]; - - static_TQUType_ptr.set( o + 1, &value ); - - obj->tqt_invoke( id, o ); - return true; -} - -void KonqView::setViewName( const TQString &name ) -{ - //kdDebug() << "KonqView::setViewName this=" << this << " name=" << name << endl; - if ( m_pPart ) - m_pPart->setName( name.local8Bit().data() ); -} - -TQString KonqView::viewName() const -{ - return m_pPart ? TQString::fromLocal8Bit( m_pPart->name() ) : TQString(); -} - -void KonqView::enablePopupMenu( bool b ) -{ - Q_ASSERT( m_pMainWindow ); - - KParts::BrowserExtension *ext = browserExtension(); - - if ( !ext ) - return; - - if ( m_bPopupMenuEnabled == b ) - return; - - // enable context popup - if ( b ) { - m_bPopupMenuEnabled = true; - - connect( ext, TQT_SIGNAL( popupMenu( const TQPoint &, const KFileItemList & ) ), - m_pMainWindow, TQT_SLOT( slotPopupMenu( const TQPoint &, const KFileItemList & ) ) ); - - connect( ext, TQT_SIGNAL( popupMenu( const TQPoint &, const KURL &, const TQString &, mode_t ) ), - m_pMainWindow, TQT_SLOT( slotPopupMenu( const TQPoint &, const KURL &, const TQString &, mode_t ) ) ); - - connect( ext, TQT_SIGNAL( popupMenu( KXMLGUIClient *, const TQPoint &, const KFileItemList & ) ), - m_pMainWindow, TQT_SLOT( slotPopupMenu( KXMLGUIClient *, const TQPoint &, const KFileItemList & ) ) ); - - connect( ext, TQT_SIGNAL( popupMenu( KXMLGUIClient *, const TQPoint &, const KFileItemList &, const KParts::URLArgs &, KParts::BrowserExtension::PopupFlags ) ), - m_pMainWindow, TQT_SLOT( slotPopupMenu( KXMLGUIClient *, const TQPoint &, const KFileItemList &, const KParts::URLArgs &, KParts::BrowserExtension::PopupFlags ) ) ); - - connect( ext, TQT_SIGNAL( popupMenu( KXMLGUIClient *, const TQPoint &, const KURL &, const TQString &, mode_t ) ), - m_pMainWindow, TQT_SLOT( slotPopupMenu( KXMLGUIClient *, const TQPoint &, const KURL &, const TQString &, mode_t ) ) ); - - connect( ext, TQT_SIGNAL( popupMenu( KXMLGUIClient *, const TQPoint &, const KURL &, const KParts::URLArgs &, KParts::BrowserExtension::PopupFlags, mode_t ) ), - m_pMainWindow, TQT_SLOT( slotPopupMenu( KXMLGUIClient *, const TQPoint &, const KURL &, const KParts::URLArgs &, KParts::BrowserExtension::PopupFlags, mode_t ) ) ); - } - else // disable context popup - { - m_bPopupMenuEnabled = false; - - disconnect( ext, TQT_SIGNAL( popupMenu( const TQPoint &, const KFileItemList & ) ), - m_pMainWindow, TQT_SLOT( slotPopupMenu( const TQPoint &, const KFileItemList & ) ) ); - - disconnect( ext, TQT_SIGNAL( popupMenu( const TQPoint &, const KURL &, const TQString &, mode_t ) ), - m_pMainWindow, TQT_SLOT( slotPopupMenu( const TQPoint &, const KURL &, const TQString &, mode_t ) ) ); - - disconnect( ext, TQT_SIGNAL( popupMenu( KXMLGUIClient *, const TQPoint &, const KFileItemList & ) ), - m_pMainWindow, TQT_SLOT( slotPopupMenu( KXMLGUIClient *, const TQPoint &, const KFileItemList & ) ) ); - - disconnect( ext, TQT_SIGNAL( popupMenu( KXMLGUIClient *, const TQPoint &, const KURL &, const TQString &, mode_t ) ), - m_pMainWindow, TQT_SLOT( slotPopupMenu( KXMLGUIClient *, const TQPoint &, const KURL &, const TQString &, mode_t ) ) ); - } - enableBackRightClick( m_bBackRightClick ); -} - -// caller should ensure that this is called only when b changed, or for new parts -void KonqView::enableBackRightClick( bool b ) -{ - m_bBackRightClick = b; - if ( b ) - connect( this, TQT_SIGNAL( backRightClick() ), - m_pMainWindow, TQT_SLOT( slotBack() ) ); - else - disconnect( this, TQT_SIGNAL( backRightClick() ), - m_pMainWindow, TQT_SLOT( slotBack() ) ); -} - -void KonqView::reparseConfiguration() -{ - callExtensionMethod( "reparseConfiguration()" ); - bool b = KonqSettings::backRightClick(); - if ( m_bBackRightClick != b ) - { - if (m_bBackRightClick && m_pPart->widget()->inherits(TQSCROLLVIEW_OBJECT_NAME_STRING) ) - { - (static_cast(m_pPart->widget()))->viewport()->installEventFilter( this ); - } - enableBackRightClick( b ); - } -} - -void KonqView::disableScrolling() -{ - m_bDisableScrolling = true; - callExtensionMethod( "disableScrolling()" ); -} - -KonqViewIface * KonqView::dcopObject() -{ - if ( !m_dcopObject ) { - TQCString dcopName = name(); - if ( dcopName.isEmpty() || dcopName == "unnamed" ) - dcopName = viewName().utf8(); - if ( dcopName.isEmpty() || dcopName == "unnamed" ) { - TQVariant dcopProperty = part()->property( "dcopObjectId" ); - if ( dcopProperty.type() == TQVariant::CString ) - dcopName = dcopProperty.toCString(); - } - dcopName += "-view"; // to avoid having the same name as the part - m_dcopObject = new KonqViewIface( this, dcopName ); - } - return m_dcopObject; -} - -bool KonqView::eventFilter( TQObject *obj, TQEvent *e ) -{ - if ( !m_pPart ) - return false; -// kdDebug() << "--" << obj->className() << "--" << e->type() << "--" << endl; - if ( e->type() == TQEvent::DragEnter && m_bURLDropHandling && TQT_BASE_OBJECT(obj) == TQT_BASE_OBJECT(m_pPart->widget()) ) - { - TQDragEnterEvent *ev = static_cast( e ); - - if ( KURLDrag::canDecode( ev ) ) - { - KURL::List lstDragURLs; - bool ok = KURLDrag::decode( ev, lstDragURLs ); - - TQObjectList *children = m_pPart->widget()->queryList( TQWIDGET_OBJECT_NAME_STRING ); - - if ( ok && - !lstDragURLs.first().url().contains( "javascript:", false ) && // ### this looks like a hack to me - ev->source() != m_pPart->widget() && - children && - children->findRef( TQT_TQOBJECT(ev->source()) ) == -1 ) - ev->acceptAction(); - - delete children; - } - } - else if ( e->type() == TQEvent::Drop && m_bURLDropHandling && TQT_BASE_OBJECT(obj) == TQT_BASE_OBJECT(m_pPart->widget()) ) - { - TQDropEvent *ev = static_cast( e ); - - KURL::List lstDragURLs; - bool ok = KURLDrag::decode( ev, lstDragURLs ); - - KParts::BrowserExtension *ext = browserExtension(); - if ( ok && ext && lstDragURLs.first().isValid() ) - emit ext->openURLRequest( lstDragURLs.first() ); // this will call m_pMainWindow::slotOpenURLRequest delayed - } - - if ( m_bBackRightClick ) - { - if ( e->type() == TQEvent::ContextMenu ) - { - TQContextMenuEvent *ev = TQT_TQCONTEXTMENUEVENT( e ); - if ( ev->reason() == TQContextMenuEvent::Mouse ) - { - return true; - } - } - else if ( e->type() == TQEvent::MouseButtonPress ) - { - TQMouseEvent *ev = TQT_TQMOUSEEVENT( e ); - if ( ev->button() == Qt::RightButton ) - { - return true; - } - } - else if ( e->type() == TQEvent::MouseButtonRelease ) - { - TQMouseEvent *ev = TQT_TQMOUSEEVENT( e ); - if ( ev->button() == Qt::RightButton ) - { - emit backRightClick(); - return true; - } - } - else if ( e->type() == TQEvent::MouseMove ) - { - TQMouseEvent *ev = TQT_TQMOUSEEVENT( e ); - if ( ev->state() == Qt::RightButton ) - { - obj->removeEventFilter( this ); - TQMouseEvent me( TQEvent::MouseButtonPress, ev->pos(), 2, 2 ); - TQApplication::sendEvent( obj, &me ); - TQContextMenuEvent ce( TQContextMenuEvent::Mouse, ev->pos(), 2 ); - TQApplication::sendEvent( obj, &ce ); - obj->installEventFilter( this ); - return true; - } - } - } - - if ( e->type() == TQEvent::FocusIn ) - { - setActiveInstance(); - } - return false; -} - -void KonqView::setActiveInstance() -{ - if ( m_bBuiltinView || !m_pPart->instance() /*never!*/) - TDEGlobal::_activeInstance = TDEGlobal::instance(); - else - TDEGlobal::_activeInstance = m_pPart->instance(); -} - -bool KonqView::prepareReload( KParts::URLArgs& args ) -{ - args.reload = true; - // Repost form data if this URL is the result of a POST HTML form. - if ( m_doPost && !args.redirectedRequest() ) - { - if ( KMessageBox::warningContinueCancel( 0, i18n( - "The page you are trying to view is the result of posted form data. " - "If you resend the data, any action the form carried out (such as search or online purchase) will be repeated. "), - i18n( "Warning" ), i18n( "Resend" ) ) == KMessageBox::Continue ) - { - args.setDoPost( true ); - args.setContentType( m_postContentType ); - args.postData = m_postData; - } - else - return false; - } - // Re-set referrer - args.metaData()["referrer"] = m_pageReferrer; - - return true; -} - -KParts::BrowserExtension * KonqView::browserExtension() const -{ - return KParts::BrowserExtension::childObject( m_pPart ); -} - -KParts::StatusBarExtension * KonqView::statusBarExtension() const -{ - return KParts::StatusBarExtension::childObject( m_pPart ); -} - -bool KonqView::supportsServiceType( const TQString &serviceType ) const -{ - const TQStringList lst = serviceTypes(); - for( TQStringList::ConstIterator it = lst.begin(); it != lst.end(); ++it ) { - if ( *it == serviceType ) - return true; - // Maybe we should keep around a list of KServiceType::Ptr? - KMimeType::Ptr mime = KMimeType::mimeType( *it ); - if ( mime && mime->is( serviceType ) ) // respect inheritance - return true; - } - return false; -} - -#include "konq_view.moc" diff --git a/konqueror/konq_view.cpp b/konqueror/konq_view.cpp new file mode 100644 index 000000000..3a970018b --- /dev/null +++ b/konqueror/konq_view.cpp @@ -0,0 +1,1398 @@ +/* + This file is part of the KDE project + Copyright (C) 1998-2005 David Faure + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + + +#include "konq_view.h" +#include "tdeapplication.h" +#include "KonqViewIface.h" +#include "konq_settingsxt.h" +#include "konq_frame.h" +#include "konq_run.h" +#include "konq_events.h" +#include "konq_viewmgr.h" +#include "konq_tabs.h" +#include "konq_browseriface.h" +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +//#define DEBUG_HISTORY + +template class TQPtrList; + +KonqView::KonqView( KonqViewFactory &viewFactory, + KonqFrame* viewFrame, + KonqMainWindow *mainWindow, + const KService::Ptr &service, + const TDETrader::OfferList &partServiceOffers, + const TDETrader::OfferList &appServiceOffers, + const TQString &serviceType, + bool passiveMode + ) +{ + m_pKonqFrame = viewFrame; + m_pKonqFrame->setView( this ); + + m_sLocationBarURL = ""; + m_pageSecurity = KonqMainWindow::NotCrypted; + m_bLockHistory = false; + m_doPost = false; + m_pMainWindow = mainWindow; + m_pRun = 0L; + m_pPart = 0L; + m_dcopObject = 0L; + + m_randID = TDEApplication::random(); + + m_service = service; + m_partServiceOffers = partServiceOffers; + m_appServiceOffers = appServiceOffers; + m_serviceType = serviceType; + + m_bAllowHTML = m_pMainWindow->isHTMLAllowed(); + m_lstHistory.setAutoDelete( true ); + m_bLoading = false; + m_bPendingRedirection = false; + m_bPassiveMode = passiveMode; + m_bLockedLocation = false; + m_bLinkedView = false; + m_bAborted = false; + m_bToggleView = false; + m_bHierarchicalView = false; + m_bDisableScrolling = false; + m_bGotIconURL = false; + m_bPopupMenuEnabled = true; + m_browserIface = new KonqBrowserInterface( this, "browseriface" ); + m_bBackRightClick = KonqSettings::backRightClick(); + m_bFollowActive = false; + m_bBuiltinView = false; + m_bURLDropHandling = false; + + switchView( viewFactory ); +} + +KonqView::~KonqView() +{ + //kdDebug(1202) << "KonqView::~KonqView : part = " << m_pPart << endl; + + if (KonqMainWindow::s_crashlog_file) { + TQString part_url; + if (m_pPart) + part_url = m_pPart->url().url(); + if (part_url.isNull()) + part_url = ""; + TQCString line; + line = ( TQString("close(%1):%2\n").arg(m_randID,0,16).arg(part_url) ).utf8(); + KonqMainWindow::s_crashlog_file->writeBlock(line, line.length()); + KonqMainWindow::s_crashlog_file->flush(); + } + + // We did so ourselves for passive views + if (m_pPart != 0L) + { + finishedWithCurrentURL(); + if ( isPassiveMode() ) + disconnect( m_pPart, TQT_SIGNAL( destroyed() ), m_pMainWindow->viewManager(), TQT_SLOT( slotObjectDestroyed() ) ); + + delete m_pPart; + } + + setRun( 0L ); + //kdDebug(1202) << "KonqView::~KonqView " << this << " done" << endl; +} + +void KonqView::openURL( const KURL &url, const TQString & locationBarURL, + const TQString & nameFilter, bool tempFile ) +{ + kdDebug(1202) << "KonqView::openURL url=" << url << " locationBarURL=" << locationBarURL << endl; + setServiceTypeInExtension(); + + if (KonqMainWindow::s_crashlog_file) { + TQString part_url; + if (m_pPart) + part_url = m_pPart->url().url(); + if (part_url.isNull()) + part_url = ""; + + TQString url_url = url.url(); + if (url_url.isNull()) + url_url = TQString(""); + + TQCString line; + + line = ( TQString("closed(%1):%2\n").arg(m_randID,0,16).arg(part_url) ).utf8(); + KonqMainWindow::s_crashlog_file->writeBlock(line,line.length()); + line = ( TQString("opened(%3):%4\n").arg(m_randID,0,16).arg(url_url) ).utf8(); + KonqMainWindow::s_crashlog_file->writeBlock(line,line.length()); + KonqMainWindow::s_crashlog_file->flush(); + } + + KParts::BrowserExtension *ext = browserExtension(); + KParts::URLArgs args; + if ( ext ) + args = ext->urlArgs(); + + // Typing "Enter" again after the URL of an aborted view, triggers a reload. + if ( m_bAborted && m_pPart && m_pPart->url() == url && !args.doPost()) + { + if ( !prepareReload( args ) ) + return; + if ( ext ) + ext->setURLArgs( args ); + } + +#ifdef DEBUG_HISTORY + kdDebug(1202) << "m_bLockedLocation=" << m_bLockedLocation << " args.lockHistory()=" << args.lockHistory() << endl; +#endif + if ( args.lockHistory() ) + lockHistory(); + + if ( !m_bLockHistory ) + { + // Store this new URL in the history, removing any existing forward history. + // We do this first so that everything is ready if a part calls completed(). + createHistoryEntry(); + } else + m_bLockHistory = false; + + callExtensionStringMethod( "setNameFilter(const TQString&)", nameFilter ); + if ( m_bDisableScrolling ) + callExtensionMethod( "disableScrolling()" ); + + setLocationBarURL( locationBarURL ); + setPageSecurity(KonqMainWindow::NotCrypted); + + if ( !args.reload ) + { + // Save the POST data that is necessary to open this URL + // (so that reload can re-post it) + m_doPost = args.doPost(); + m_postContentType = args.contentType(); + m_postData = args.postData; + // Save the referrer + m_pageReferrer = args.metaData()["referrer"]; + } + + if ( tempFile ) { + // Store the path to the tempfile. Yes, we could store a bool only, + // but this would be more dangerous. If anything goes wrong in the code, + // we might end up deleting a real file. + if ( url.isLocalFile() ) + m_tempFile = url.path(); + else + kdWarning(1202) << "Tempfile option is set, but URL is remote: " << url << endl; + } + + aboutToOpenURL( url, args ); + + m_pPart->openURL( url ); + + updateHistoryEntry(false /* don't save location bar URL yet */); + // add pending history entry + KonqHistoryManager::kself()->addPending( url, locationBarURL, TQString::null); + +#ifdef DEBUG_HISTORY + kdDebug(1202) << "Current position : " << m_lstHistory.at() << endl; +#endif +} + +void KonqView::switchView( KonqViewFactory &viewFactory ) +{ + kdDebug(1202) << "KonqView::switchView" << endl; + if ( m_pPart ) + m_pPart->widget()->hide(); + + KParts::ReadOnlyPart *oldPart = m_pPart; + m_pPart = m_pKonqFrame->attach( viewFactory ); // creates the part + + // Set the statusbar in the BE asap to avoid a TDEMainWindow statusbar being created. + KParts::StatusBarExtension* sbext = statusBarExtension(); + if ( sbext ) + sbext->setStatusBar( frame()->statusbar() ); + + // Activate the new part + if ( oldPart ) + { + m_pPart->setName( oldPart->name() ); + emit sigPartChanged( this, oldPart, m_pPart ); + delete oldPart; + } + + connectPart(); + + TQVariant prop; + + prop = m_service->property( "X-TDE-BrowserView-FollowActive"); + if (prop.isValid() && prop.toBool()) + { + //kdDebug(1202) << "KonqView::switchView X-TDE-BrowserView-FollowActive -> setFollowActive" <property( "X-TDE-BrowserView-Built-Into" ); + m_bBuiltinView = (prop.isValid() && prop.toString() == "konqueror"); + + if ( !m_pMainWindow->viewManager()->isLoadingProfile() ) + { + // Honour "non-removeable passive mode" (like the dirtree) + prop = m_service->property( "X-TDE-BrowserView-PassiveMode"); + if ( prop.isValid() && prop.toBool() ) + { + kdDebug(1202) << "KonqView::switchView X-TDE-BrowserView-PassiveMode -> setPassiveMode" << endl; + setPassiveMode( true ); // set as passive + } + + // Honour "linked view" + prop = m_service->property( "X-TDE-BrowserView-LinkedView"); + if ( prop.isValid() && prop.toBool() ) + { + setLinkedView( true ); // set as linked + // Two views : link both + if (m_pMainWindow->viewCount() <= 2) // '1' can happen if this view is not yet in the map + { + KonqView * otherView = m_pMainWindow->otherView( this ); + if (otherView) + otherView->setLinkedView( true ); + } + } + } + + prop = m_service->property( "X-TDE-BrowserView-HierarchicalView"); + if ( prop.isValid() && prop.toBool() ) + { + kdDebug() << "KonqView::switchView X-TDE-BrowserView-HierarchicalView -> setHierarchicalView" << endl; + setHierarchicalView( true ); // set as hierarchial + } + else + { + setHierarchicalView( false ); + } +} + +bool KonqView::changeViewMode( const TQString &serviceType, + const TQString &serviceName, + bool forceAutoEmbed ) +{ + // Caller should call stop first. + assert ( !m_bLoading ); + + kdDebug(1202) << "changeViewMode: serviceType is " << serviceType + << " serviceName is " << serviceName + << " current service name is " << m_service->desktopEntryName() << endl; + + if ( KMimeType::mimeType(serviceType)->is(m_serviceType) && (serviceName.isEmpty() || serviceName == m_service->desktopEntryName()) ) + return true; + + if ( isLockedViewMode() ) + { + //kdDebug(1202) << "This view's mode is locked - can't change" << endl; + return false; // we can't do that if our view mode is locked + } + + kdDebug(1202) << "Switching view modes..." << endl; + TDETrader::OfferList partServiceOffers, appServiceOffers; + KService::Ptr service = 0L; + KonqViewFactory viewFactory = KonqFactory::createView( serviceType, serviceName, &service, &partServiceOffers, &appServiceOffers, forceAutoEmbed ); + + if ( viewFactory.isNull() ) + { + // Revert location bar's URL to the working one + if(history().current()) + setLocationBarURL( history().current()->locationBarURL ); + return false; + } + + m_serviceType = serviceType; + m_partServiceOffers = partServiceOffers; + m_appServiceOffers = appServiceOffers; + + // Check if that's already the kind of part we have -> no need to recreate it + // Note: we should have an operator= for KService... + if ( m_service && m_service->desktopEntryPath() == service->desktopEntryPath() ) + { + kdDebug( 1202 ) << "KonqView::changeViewMode. Reusing service. Service type set to " << m_serviceType << endl; + if ( m_pMainWindow->currentView() == this ) + m_pMainWindow->updateViewModeActions(); + } + else + { + m_service = service; + + switchView( viewFactory ); + } + + if ( m_pMainWindow->viewManager()->activePart() != m_pPart ) + { + // Make the new part active. Note that we don't do it each time we + // open a URL (becomes awful in view-follows-view mode), but we do + // each time we change the view mode. + // We don't do it in switchView either because it's called from the constructor too, + // where the location bar url isn't set yet. + //kdDebug(1202) << "Giving focus to new part " << m_pPart << endl; + m_pMainWindow->viewManager()->setActivePart( m_pPart ); + } + return true; +} + +void KonqView::connectPart( ) +{ + //kdDebug(1202) << "KonqView::connectPart" << endl; + connect( m_pPart, TQT_SIGNAL( started( TDEIO::Job * ) ), + this, TQT_SLOT( slotStarted( TDEIO::Job * ) ) ); + connect( m_pPart, TQT_SIGNAL( completed() ), + this, TQT_SLOT( slotCompleted() ) ); + connect( m_pPart, TQT_SIGNAL( completed(bool) ), + this, TQT_SLOT( slotCompleted(bool) ) ); + connect( m_pPart, TQT_SIGNAL( canceled( const TQString & ) ), + this, TQT_SLOT( slotCanceled( const TQString & ) ) ); + connect( m_pPart, TQT_SIGNAL( setWindowCaption( const TQString & ) ), + this, TQT_SLOT( setCaption( const TQString & ) ) ); + + KParts::BrowserExtension *ext = browserExtension(); + + if ( ext ) + { + ext->setBrowserInterface( m_browserIface ); + + connect( ext, TQT_SIGNAL( openURLRequestDelayed( const KURL &, const KParts::URLArgs &) ), + m_pMainWindow, TQT_SLOT( slotOpenURLRequest( const KURL &, const KParts::URLArgs & ) ) ); + + if ( m_bPopupMenuEnabled ) + { + m_bPopupMenuEnabled = false; // force + enablePopupMenu( true ); + } + + connect( ext, TQT_SIGNAL( setLocationBarURL( const TQString & ) ), + this, TQT_SLOT( setLocationBarURL( const TQString & ) ) ); + + connect( ext, TQT_SIGNAL( setIconURL( const KURL & ) ), + this, TQT_SLOT( setIconURL( const KURL & ) ) ); + + connect( ext, TQT_SIGNAL( setPageSecurity( int ) ), + this, TQT_SLOT( setPageSecurity( int ) ) ); + + connect( ext, TQT_SIGNAL( createNewWindow( const KURL &, const KParts::URLArgs & ) ), + m_pMainWindow, TQT_SLOT( slotCreateNewWindow( const KURL &, const KParts::URLArgs & ) ) ); + + connect( ext, TQT_SIGNAL( createNewWindow( const KURL &, const KParts::URLArgs &, const KParts::WindowArgs &, KParts::ReadOnlyPart *& ) ), + m_pMainWindow, TQT_SLOT( slotCreateNewWindow( const KURL &, const KParts::URLArgs &, const KParts::WindowArgs &, KParts::ReadOnlyPart *& ) ) ); + + connect( ext, TQT_SIGNAL( loadingProgress( int ) ), + m_pKonqFrame->statusbar(), TQT_SLOT( slotLoadingProgress( int ) ) ); + + connect( ext, TQT_SIGNAL( speedProgress( int ) ), + m_pKonqFrame->statusbar(), TQT_SLOT( slotSpeedProgress( int ) ) ); + + connect( ext, TQT_SIGNAL( selectionInfo( const KFileItemList & ) ), + this, TQT_SLOT( slotSelectionInfo( const KFileItemList & ) ) ); + + connect( ext, TQT_SIGNAL( mouseOverInfo( const KFileItem * ) ), + this, TQT_SLOT( slotMouseOverInfo( const KFileItem * ) ) ); + + connect( ext, TQT_SIGNAL( openURLNotify() ), + this, TQT_SLOT( slotOpenURLNotify() ) ); + + connect( ext, TQT_SIGNAL( enableAction( const char *, bool ) ), + this, TQT_SLOT( slotEnableAction( const char *, bool ) ) ); + + connect( ext, TQT_SIGNAL( setActionText( const char *, const TQString& ) ), + this, TQT_SLOT( slotSetActionText( const char *, const TQString& ) ) ); + + connect( ext, TQT_SIGNAL( moveTopLevelWidget( int, int ) ), + this, TQT_SLOT( slotMoveTopLevelWidget( int, int ) ) ); + + connect( ext, TQT_SIGNAL( resizeTopLevelWidget( int, int ) ), + this, TQT_SLOT( slotResizeTopLevelWidget( int, int ) ) ); + + connect( ext, TQT_SIGNAL( requestFocus(KParts::ReadOnlyPart *) ), + this, TQT_SLOT( slotRequestFocus(KParts::ReadOnlyPart *) ) ); + + if (service()->desktopEntryName() != "konq_sidebartng") { + connect( ext, TQT_SIGNAL( infoMessage( const TQString & ) ), + m_pKonqFrame->statusbar(), TQT_SLOT( message( const TQString & ) ) ); + + connect( ext, + TQT_SIGNAL( addWebSideBar(const KURL&, const TQString&) ), + m_pMainWindow, + TQT_SLOT( slotAddWebSideBar(const KURL&, const TQString&) ) ); + } + + callExtensionBoolMethod( "setSaveViewPropertiesLocally(bool)", m_pMainWindow->saveViewPropertiesLocally() ); + } + + TQVariant urlDropHandling; + + if ( ext ) + urlDropHandling = ext->property( "urlDropHandling" ); + else + urlDropHandling = TQVariant( true ); + + // Handle url drops if + // a) either the property says "ok" + // or + // b) the part is a plain krop (no BE) + m_bURLDropHandling = ( urlDropHandling.type() == TQVariant::Bool && + urlDropHandling.toBool() ); + + m_pPart->widget()->installEventFilter( this ); + + if (m_bBackRightClick && m_pPart->widget()->inherits(TQSCROLLVIEW_OBJECT_NAME_STRING) ) + { + (static_cast(m_pPart->widget()))->viewport()->installEventFilter( this ); + } + + // KonqDirPart signal + if ( m_pPart->inherits("KonqDirPart") ) + { + connect( m_pPart, TQT_SIGNAL( findOpen( KonqDirPart * ) ), + m_pMainWindow, TQT_SLOT( slotFindOpen( KonqDirPart * ) ) ); + } +} + +void KonqView::slotEnableAction( const char * name, bool enabled ) +{ + if ( m_pMainWindow->currentView() == this ) + m_pMainWindow->enableAction( name, enabled ); + // Otherwise, we don't have to do anything, the state of the action is + // stored inside the browser-extension. +} + +void KonqView::slotSetActionText( const char* name, const TQString& text ) +{ + if ( m_pMainWindow->currentView() == this ) + m_pMainWindow->setActionText( name, text ); + // Otherwise, we don't have to do anything, the state of the action is + // stored inside the browser-extension. +} + +void KonqView::slotMoveTopLevelWidget( int x, int y ) +{ + KonqFrameContainerBase* container = frame()->parentContainer(); + // If tabs are shown, only accept to move the whole window if there's only one tab. + if ( container->frameType() != "Tabs" || static_cast(container)->count() == 1 ) + m_pMainWindow->move( x, y ); +} + +void KonqView::slotResizeTopLevelWidget( int w, int h ) +{ + KonqFrameContainerBase* container = frame()->parentContainer(); + // If tabs are shown, only accept to resize the whole window if there's only one tab. + // ### Maybe we could store the size requested by each tab and resize the window to the biggest one. + if ( container->frameType() != "Tabs" || static_cast(container)->count() == 1 ) + m_pMainWindow->resize( w, h ); +} + +void KonqView::slotStarted( TDEIO::Job * job ) +{ + //kdDebug(1202) << "KonqView::slotStarted" << job << endl; + setLoading( true ); + + if (job) + { + // Manage passwords properly... + if (m_pMainWindow) + { + kdDebug(7035) << "slotStarted: Window ID = " << m_pMainWindow->topLevelWidget()->winId() << endl; + job->setWindow (m_pMainWindow->topLevelWidget ()); + } + + connect( job, TQT_SIGNAL( percent( TDEIO::Job *, unsigned long ) ), this, TQT_SLOT( slotPercent( TDEIO::Job *, unsigned long ) ) ); + connect( job, TQT_SIGNAL( speed( TDEIO::Job *, unsigned long ) ), this, TQT_SLOT( slotSpeed( TDEIO::Job *, unsigned long ) ) ); + connect( job, TQT_SIGNAL( infoMessage( TDEIO::Job *, const TQString & ) ), this, TQT_SLOT( slotInfoMessage( TDEIO::Job *, const TQString & ) ) ); + } +} + +void KonqView::slotRequestFocus( KParts::ReadOnlyPart * ) +{ + m_pMainWindow->viewManager()->showTab(this); +} + +void KonqView::setLoading( bool loading, bool hasPending /*= false*/) +{ + //kdDebug(1202) << "KonqView::setLoading loading=" << loading << " hasPending=" << hasPending << endl; + m_bLoading = loading; + m_bPendingRedirection = hasPending; + if ( m_pMainWindow->currentView() == this ) + m_pMainWindow->updateToolBarActions( hasPending ); + + m_pMainWindow->viewManager()->setLoading( this, loading || hasPending ); +} + +void KonqView::slotPercent( TDEIO::Job *, unsigned long percent ) +{ + m_pKonqFrame->statusbar()->slotLoadingProgress( percent ); +} + +void KonqView::slotSpeed( TDEIO::Job *, unsigned long bytesPerSecond ) +{ + m_pKonqFrame->statusbar()->slotSpeedProgress( bytesPerSecond ); +} + +void KonqView::slotInfoMessage( TDEIO::Job *, const TQString &msg ) +{ + m_pKonqFrame->statusbar()->message( msg ); +} + +void KonqView::slotCompleted() +{ + slotCompleted( false ); +} + +void KonqView::slotCompleted( bool hasPending ) +{ + //kdDebug(1202) << "KonqView::slotCompleted hasPending=" << hasPending << endl; + m_pKonqFrame->statusbar()->slotLoadingProgress( -1 ); + + if ( ! m_bLockHistory ) + { + // Success... update history entry, including location bar URL + updateHistoryEntry( true ); + + if ( m_bAborted ) // remove the pending entry on error + KonqHistoryManager::kself()->removePending( url() ); + else if ( m_lstHistory.current() ) // register as proper history entry + KonqHistoryManager::kself()->confirmPending(url(), typedURL(), + m_lstHistory.current()->title); + + emit viewCompleted( this ); + } + setLoading( false, hasPending ); + + if (!m_bGotIconURL && !m_bAborted) + { + if ( KonqSettings::enableFavicon() == true ) + { + // Try to get /favicon.ico + if ( supportsServiceType( "text/html" ) && url().protocol().startsWith( "http" ) ) + KonqPixmapProvider::downloadHostIcon( url() ); + } + } +} + +void KonqView::slotCanceled( const TQString & errorMsg ) +{ + kdDebug(1202) << "KonqView::slotCanceled" << endl; + // The errorMsg comes from the ReadOnlyPart's job. + // It should probably be used in a KMessageBox + // Let's use the statusbar for now + m_pKonqFrame->statusbar()->message( errorMsg ); + m_bAborted = true; + slotCompleted(); +} + +void KonqView::slotSelectionInfo( const KFileItemList &items ) +{ + KonqFileSelectionEvent ev( items, m_pPart ); + TQApplication::sendEvent( m_pMainWindow, &ev ); +} + +void KonqView::slotMouseOverInfo( const KFileItem *item ) +{ + KonqFileMouseOverEvent ev( item, m_pPart ); + TQApplication::sendEvent( m_pMainWindow, &ev ); +} + +void KonqView::setLocationBarURL( const KURL& locationBarURL ) +{ + setLocationBarURL( locationBarURL.pathOrURL() ); +} + +void KonqView::setLocationBarURL( const TQString & locationBarURL ) +{ + //kdDebug(1202) << "KonqView::setLocationBarURL " << locationBarURL << " this=" << this << endl; + + m_sLocationBarURL = locationBarURL; + if ( m_pMainWindow->currentView() == this ) + { + //kdDebug(1202) << "is current view " << this << endl; + m_pMainWindow->setLocationBarURL( m_sLocationBarURL ); + m_pMainWindow->setPageSecurity( m_pageSecurity ); + } + if (!m_bPassiveMode) setTabIcon( KURL::fromPathOrURL( m_sLocationBarURL ) ); +} + +void KonqView::setIconURL( const KURL & iconURL ) +// This function sets the favIcon in konqui's window if enabled, +// thus it is responsible for the icon in the taskbar. +// It does not set the tab's favIcon. +{ + kdDebug(1202) << "entering KonqView::setIconURL" << endl; + if ( KonqSettings::enableFavicon() ) + { + KonqPixmapProvider::setIconForURL( KURL( m_sLocationBarURL ), iconURL ); + m_bGotIconURL = true; + } +} + +void KonqView::setPageSecurity( int pageSecurity ) +{ + m_pageSecurity = (KonqMainWindow::PageSecurity)pageSecurity; + + if ( m_pMainWindow->currentView() == this ) + m_pMainWindow->setPageSecurity( m_pageSecurity ); +} + +void KonqView::setTabIcon( const KURL &url ) +{ + if (!m_bPassiveMode) frame()->setTabIcon( url, 0L ); +} + +void KonqView::setCaption( const TQString & caption ) +{ + if (caption.isEmpty()) return; + + TQString adjustedCaption = caption; + // For local URLs we prefer to use only the directory name + if (url().isLocalFile()) + { + // Is the caption a URL? If so, is it local? If so, only display the filename! + KURL url = KURL::fromPathOrURL(caption); + if (url.isValid() && url.isLocalFile() && url.fileName() == this->url().fileName()) + adjustedCaption = url.fileName(); + } + + m_caption = adjustedCaption; + if (!m_bPassiveMode) frame()->setTitle( adjustedCaption , 0L ); +} + +void KonqView::slotOpenURLNotify() +{ +#ifdef DEBUG_HISTORY + kdDebug(1202) << "KonqView::slotOpenURLNotify" << endl; +#endif + updateHistoryEntry(true); + createHistoryEntry(); + if ( m_pMainWindow->currentView() == this ) + m_pMainWindow->updateToolBarActions(); +} + +void KonqView::createHistoryEntry() +{ + // First, remove any forward history + HistoryEntry * current = m_lstHistory.current(); + if (current) + { +#ifdef DEBUG_HISTORY + kdDebug(1202) << "Truncating history" << endl; +#endif + m_lstHistory.at( m_lstHistory.count() - 1 ); // go to last one + for ( ; m_lstHistory.current() != current ; ) + { + if ( !m_lstHistory.removeLast() ) // and remove from the end (faster and easier) + assert(0); + // go to last one. The documentation says that removeLast() + // makes current() null if it's the last item. however in qt2 + // the behaviour was different than the documentation. this is + // changed in qt3 to behave as documented ;-) (Simon) + m_lstHistory.at( m_lstHistory.count() - 1 ); + } + // Now current is the current again. + } + // Append a new entry +#ifdef DEBUG_HISTORY + kdDebug(1202) << "Append a new entry" << endl; +#endif + m_lstHistory.append( new HistoryEntry ); // made current +#ifdef DEBUG_HISTORY + kdDebug(1202) << "at=" << m_lstHistory.at() << " count=" << m_lstHistory.count() << endl; +#endif + assert( m_lstHistory.at() == (int) m_lstHistory.count() - 1 ); +} + +void KonqView::updateHistoryEntry( bool saveLocationBarURL ) +{ + Q_ASSERT( !m_bLockHistory ); // should never happen + + HistoryEntry * current = m_lstHistory.current(); + if ( !current ) + return; + + if ( browserExtension() ) + { + current->buffer = TQByteArray(); // Start with empty buffer. + TQDataStream stream( current->buffer, IO_WriteOnly ); + + browserExtension()->saveState( stream ); + } + +#ifdef DEBUG_HISTORY + kdDebug(1202) << "Saving part URL : " << m_pPart->url() << " in history position " << m_lstHistory.at() << endl; +#endif + current->url = m_pPart->url(); + + if (saveLocationBarURL) + { +#ifdef DEBUG_HISTORY + kdDebug(1202) << "Saving location bar URL : " << m_sLocationBarURL << " in history position " << m_lstHistory.at() << endl; +#endif + current->locationBarURL = m_sLocationBarURL; + current->pageSecurity = m_pageSecurity; + } +#ifdef DEBUG_HISTORY + kdDebug(1202) << "Saving title : " << m_caption << " in history position " << m_lstHistory.at() << endl; +#endif + current->title = m_caption; + current->strServiceType = m_serviceType; + current->strServiceName = m_service->desktopEntryName(); + + current->doPost = m_doPost; + current->postData = m_doPost ? m_postData : TQByteArray(); + current->postContentType = m_doPost ? m_postContentType : TQString::null; + current->pageReferrer = m_pageReferrer; +} + +void KonqView::goHistory( int steps ) +{ + // This is called by KonqBrowserInterface + if ( m_pMainWindow->currentView() == this ) + m_pMainWindow->viewManager()->setActivePart( part() ); + + // Delay the go() call (we need to return to the caller first) + m_pMainWindow->slotGoHistoryActivated( steps ); +} + +void KonqView::go( int steps ) +{ + if ( !steps ) // [WildFox] i bet there are sites on the net with stupid devs who do that :) + { +#ifdef DEBUG_HISTORY + kdDebug(1202) << "KonqView::go(0)" << endl; +#endif + // [David] and you're right. And they expect that it reloads, apparently. + // [George] I'm going to make nspluginviewer rely on this too. :-) + m_pMainWindow->slotReload(); + return; + } + + int newPos = m_lstHistory.at() + steps; +#ifdef DEBUG_HISTORY + kdDebug(1202) << "go : steps=" << steps + << " newPos=" << newPos + << " m_lstHistory.count()=" << m_lstHistory.count() + << endl; +#endif + if( newPos < 0 || (uint)newPos >= m_lstHistory.count() ) + return; + + stop(); + + // Yay, we can move there without a loop ! + HistoryEntry *currentHistoryEntry = m_lstHistory.at( newPos ); // sets current item + + assert( currentHistoryEntry ); + assert( newPos == m_lstHistory.at() ); // check we moved (i.e. if I understood the docu) + assert( currentHistoryEntry == m_lstHistory.current() ); +#ifdef DEBUG_HISTORY + kdDebug(1202) << "New position " << m_lstHistory.at() << endl; +#endif + + restoreHistory(); +} + +void KonqView::restoreHistory() +{ + HistoryEntry h( *(m_lstHistory.current()) ); // make a copy of the current history entry, as the data + // the pointer points to will change with the following calls + +#ifdef DEBUG_HISTORY + kdDebug(1202) << "Restoring servicetype/name, and location bar URL from history : " << h.locationBarURL << endl; +#endif + setLocationBarURL( h.locationBarURL ); + setPageSecurity( h.pageSecurity ); + m_sTypedURL = TQString::null; + if ( ! changeViewMode( h.strServiceType, h.strServiceName ) ) + { + kdWarning(1202) << "Couldn't change view mode to " << h.strServiceType + << " " << h.strServiceName << endl; + return /*false*/; + } + + setServiceTypeInExtension(); + + aboutToOpenURL( h.url ); + + if ( browserExtension() ) + { + //kdDebug(1202) << "Restoring view from stream" << endl; + TQDataStream stream( h.buffer, IO_ReadOnly ); + + browserExtension()->restoreState( stream ); + + m_doPost = h.doPost; + m_postContentType = h.postContentType; + m_postData = h.postData; + m_pageReferrer = h.pageReferrer; + } + else + m_pPart->openURL( h.url ); + + if ( m_pMainWindow->currentView() == this ) + m_pMainWindow->updateToolBarActions(); + +#ifdef DEBUG_HISTORY + kdDebug(1202) << "New position (2) " << m_lstHistory.at() << endl; +#endif +} + +const HistoryEntry * KonqView::historyAt(const int pos) +{ + if(pos<0 || pos>=(int)m_lstHistory.count()) + return 0L; + int oldpos = m_lstHistory.at(); + const HistoryEntry* h = m_lstHistory.at(pos); + m_lstHistory.at( oldpos ); + return h; +} + +void KonqView::copyHistory( KonqView *other ) +{ + m_lstHistory.clear(); + + TQPtrListIterator it( other->m_lstHistory ); + for (; it.current(); ++it ) + m_lstHistory.append( new HistoryEntry( *it.current() ) ); + m_lstHistory.at(other->m_lstHistory.at()); +} + +KURL KonqView::url() const +{ + assert( m_pPart ); + return m_pPart->url(); +} + +KURL KonqView::upURL() const +{ + KURL currentURL; + if ( m_pRun ) + currentURL = m_pRun->url(); + else + currentURL = KURL::fromPathOrURL( m_sLocationBarURL ); + return currentURL.upURL(); +} + +void KonqView::setRun( KonqRun * run ) +{ + if ( m_pRun ) + { + // Tell the KonqRun to abort, but don't delete it ourselves. + // It could be showing a message box right now. It will delete itself anyway. + m_pRun->abort(); + // finish() will be emitted later (when back to event loop) + // and we don't want it to call slotRunFinished (which stops the animation and stop button). + m_pRun->disconnect( m_pMainWindow ); + if ( !run ) + frame()->unsetCursor(); + } + else if ( run ) + frame()->setCursor( KCursor::workingCursor() ); + m_pRun = run; +} + +void KonqView::stop() +{ + //kdDebug(1202) << "KonqView::stop()" << endl; + m_bAborted = false; + finishedWithCurrentURL(); + if ( m_bLoading || m_bPendingRedirection ) + { + // aborted -> confirm the pending url. We might as well remove it, but + // we decided to keep it :) + KonqHistoryManager::kself()->confirmPending( url(), m_sTypedURL ); + + //kdDebug(1202) << "m_pPart->closeURL()" << endl; + m_pPart->closeURL(); + m_bAborted = true; + m_pKonqFrame->statusbar()->slotLoadingProgress( -1 ); + setLoading( false, false ); + } + if ( m_pRun ) + { + // Revert to working URL - unless the URL was typed manually + // This is duplicated with KonqMainWindow::slotRunFinished, but we can't call it + // since it relies on sender()... + if ( history().current() && m_pRun->typedURL().isEmpty() ) { // not typed + setLocationBarURL( history().current()->locationBarURL ); + setPageSecurity( history().current()->pageSecurity ); + } + + setRun( 0L ); + m_pKonqFrame->statusbar()->slotLoadingProgress( -1 ); + } + if ( !m_bLockHistory && m_lstHistory.count() > 0 ) + updateHistoryEntry(true); +} + +void KonqView::finishedWithCurrentURL() +{ + if ( !m_tempFile.isEmpty() ) + { + kdDebug(1202) << "######### Deleting tempfile after use:" << m_tempFile << endl; + TQFile::remove( m_tempFile ); + m_tempFile = TQString::null; + } +} + +void KonqView::setPassiveMode( bool mode ) +{ + // In theory, if m_bPassiveMode is true and mode is false, + // the part should be removed from the part manager, + // and if the other way round, it should be readded to the part manager... + m_bPassiveMode = mode; + + if ( mode && m_pMainWindow->viewCount() > 1 && m_pMainWindow->currentView() == this ) + { + KParts::Part * part = m_pMainWindow->viewManager()->chooseNextView( this )->part(); // switch active part + m_pMainWindow->viewManager()->setActivePart( part ); + } + + // Update statusbar stuff + m_pMainWindow->viewManager()->viewCountChanged(); +} + +void KonqView::setHierarchicalView( bool mode ) +{ + m_bHierarchicalView=mode; +} + + + +void KonqView::setLinkedView( bool mode ) +{ + m_bLinkedView = mode; + if ( m_pMainWindow->currentView() == this ) + m_pMainWindow->linkViewAction()->setChecked( mode ); + frame()->statusbar()->setLinkedView( mode ); +} + +void KonqView::setLockedLocation( bool b ) +{ + m_bLockedLocation = b; +} + +void KonqView::aboutToOpenURL( const KURL &url, const KParts::URLArgs &args ) +{ + KParts::OpenURLEvent ev( m_pPart, url, args ); + TQApplication::sendEvent( m_pMainWindow, &ev ); + + m_bGotIconURL = false; + m_bAborted = false; +} + +void KonqView::setServiceTypeInExtension() +{ + KParts::BrowserExtension *ext = browserExtension(); + if ( !ext ) + return; + + KParts::URLArgs args( ext->urlArgs() ); + args.serviceType = m_serviceType; + ext->setURLArgs( args ); +} + +TQStringList KonqView::frameNames() const +{ + return childFrameNames( m_pPart ); +} + +TQStringList KonqView::childFrameNames( KParts::ReadOnlyPart *part ) +{ + TQStringList res; + + KParts::BrowserHostExtension *hostExtension = KParts::BrowserHostExtension::childObject( part ); + + if ( !hostExtension ) + return res; + + res += hostExtension->frameNames(); + + const TQPtrList children = hostExtension->frames(); + TQPtrListIterator it( children ); + for (; it.current(); ++it ) + res += childFrameNames( it.current() ); + + return res; +} + +KParts::BrowserHostExtension* KonqView::hostExtension( KParts::ReadOnlyPart *part, const TQString &name ) +{ + KParts::BrowserHostExtension *ext = KParts::BrowserHostExtension::childObject( part ); + + if ( !ext ) + return 0; + + if ( ext->frameNames().contains( name ) ) + return ext; + + const TQPtrList children = ext->frames(); + TQPtrListIterator it( children ); + for (; it.current(); ++it ) + { + KParts::BrowserHostExtension *childHost = hostExtension( it.current(), name ); + if ( childHost ) + return childHost; + } + + return 0; +} + +bool KonqView::callExtensionMethod( const char *methodName ) +{ + TQObject *obj = KParts::BrowserExtension::childObject( m_pPart ); + if ( !obj ) // not all views have a browser extension ! + return false; + + int id = obj->metaObject()->findSlot( methodName ); + if ( id == -1 ) + return false; + TQUObject o[ 1 ]; + + obj->tqt_invoke( id, o ); + return true; +} + +bool KonqView::callExtensionBoolMethod( const char *methodName, bool value ) +{ + TQObject *obj = KParts::BrowserExtension::childObject( m_pPart ); + if ( !obj ) // not all views have a browser extension ! + return false; + + int id = obj->metaObject()->findSlot( methodName ); + if ( id == -1 ) + return false; + TQUObject o[ 2 ]; + + static_TQUType_bool.set( o + 1, value ); + + obj->tqt_invoke( id, o ); + return true; +} + +bool KonqView::callExtensionStringMethod( const char *methodName, TQString value ) +{ + TQObject *obj = KParts::BrowserExtension::childObject( m_pPart ); + if ( !obj ) // not all views have a browser extension ! + return false; + + int id = obj->metaObject()->findSlot( methodName ); + if ( id == -1 ) + return false; + TQUObject o[ 2 ]; + + static_TQUType_TQString.set( o + 1, value ); + + obj->tqt_invoke( id, o ); + return true; +} + +bool KonqView::callExtensionURLMethod( const char *methodName, const KURL& value ) +{ + TQObject *obj = KParts::BrowserExtension::childObject( m_pPart ); + if ( !obj ) // not all views have a browser extension ! + return false; + + int id = obj->metaObject()->findSlot( methodName ); + if ( id == -1 ) + return false; + TQUObject o[ 2 ]; + + static_TQUType_ptr.set( o + 1, &value ); + + obj->tqt_invoke( id, o ); + return true; +} + +void KonqView::setViewName( const TQString &name ) +{ + //kdDebug() << "KonqView::setViewName this=" << this << " name=" << name << endl; + if ( m_pPart ) + m_pPart->setName( name.local8Bit().data() ); +} + +TQString KonqView::viewName() const +{ + return m_pPart ? TQString::fromLocal8Bit( m_pPart->name() ) : TQString(); +} + +void KonqView::enablePopupMenu( bool b ) +{ + Q_ASSERT( m_pMainWindow ); + + KParts::BrowserExtension *ext = browserExtension(); + + if ( !ext ) + return; + + if ( m_bPopupMenuEnabled == b ) + return; + + // enable context popup + if ( b ) { + m_bPopupMenuEnabled = true; + + connect( ext, TQT_SIGNAL( popupMenu( const TQPoint &, const KFileItemList & ) ), + m_pMainWindow, TQT_SLOT( slotPopupMenu( const TQPoint &, const KFileItemList & ) ) ); + + connect( ext, TQT_SIGNAL( popupMenu( const TQPoint &, const KURL &, const TQString &, mode_t ) ), + m_pMainWindow, TQT_SLOT( slotPopupMenu( const TQPoint &, const KURL &, const TQString &, mode_t ) ) ); + + connect( ext, TQT_SIGNAL( popupMenu( KXMLGUIClient *, const TQPoint &, const KFileItemList & ) ), + m_pMainWindow, TQT_SLOT( slotPopupMenu( KXMLGUIClient *, const TQPoint &, const KFileItemList & ) ) ); + + connect( ext, TQT_SIGNAL( popupMenu( KXMLGUIClient *, const TQPoint &, const KFileItemList &, const KParts::URLArgs &, KParts::BrowserExtension::PopupFlags ) ), + m_pMainWindow, TQT_SLOT( slotPopupMenu( KXMLGUIClient *, const TQPoint &, const KFileItemList &, const KParts::URLArgs &, KParts::BrowserExtension::PopupFlags ) ) ); + + connect( ext, TQT_SIGNAL( popupMenu( KXMLGUIClient *, const TQPoint &, const KURL &, const TQString &, mode_t ) ), + m_pMainWindow, TQT_SLOT( slotPopupMenu( KXMLGUIClient *, const TQPoint &, const KURL &, const TQString &, mode_t ) ) ); + + connect( ext, TQT_SIGNAL( popupMenu( KXMLGUIClient *, const TQPoint &, const KURL &, const KParts::URLArgs &, KParts::BrowserExtension::PopupFlags, mode_t ) ), + m_pMainWindow, TQT_SLOT( slotPopupMenu( KXMLGUIClient *, const TQPoint &, const KURL &, const KParts::URLArgs &, KParts::BrowserExtension::PopupFlags, mode_t ) ) ); + } + else // disable context popup + { + m_bPopupMenuEnabled = false; + + disconnect( ext, TQT_SIGNAL( popupMenu( const TQPoint &, const KFileItemList & ) ), + m_pMainWindow, TQT_SLOT( slotPopupMenu( const TQPoint &, const KFileItemList & ) ) ); + + disconnect( ext, TQT_SIGNAL( popupMenu( const TQPoint &, const KURL &, const TQString &, mode_t ) ), + m_pMainWindow, TQT_SLOT( slotPopupMenu( const TQPoint &, const KURL &, const TQString &, mode_t ) ) ); + + disconnect( ext, TQT_SIGNAL( popupMenu( KXMLGUIClient *, const TQPoint &, const KFileItemList & ) ), + m_pMainWindow, TQT_SLOT( slotPopupMenu( KXMLGUIClient *, const TQPoint &, const KFileItemList & ) ) ); + + disconnect( ext, TQT_SIGNAL( popupMenu( KXMLGUIClient *, const TQPoint &, const KURL &, const TQString &, mode_t ) ), + m_pMainWindow, TQT_SLOT( slotPopupMenu( KXMLGUIClient *, const TQPoint &, const KURL &, const TQString &, mode_t ) ) ); + } + enableBackRightClick( m_bBackRightClick ); +} + +// caller should ensure that this is called only when b changed, or for new parts +void KonqView::enableBackRightClick( bool b ) +{ + m_bBackRightClick = b; + if ( b ) + connect( this, TQT_SIGNAL( backRightClick() ), + m_pMainWindow, TQT_SLOT( slotBack() ) ); + else + disconnect( this, TQT_SIGNAL( backRightClick() ), + m_pMainWindow, TQT_SLOT( slotBack() ) ); +} + +void KonqView::reparseConfiguration() +{ + callExtensionMethod( "reparseConfiguration()" ); + bool b = KonqSettings::backRightClick(); + if ( m_bBackRightClick != b ) + { + if (m_bBackRightClick && m_pPart->widget()->inherits(TQSCROLLVIEW_OBJECT_NAME_STRING) ) + { + (static_cast(m_pPart->widget()))->viewport()->installEventFilter( this ); + } + enableBackRightClick( b ); + } +} + +void KonqView::disableScrolling() +{ + m_bDisableScrolling = true; + callExtensionMethod( "disableScrolling()" ); +} + +KonqViewIface * KonqView::dcopObject() +{ + if ( !m_dcopObject ) { + TQCString dcopName = name(); + if ( dcopName.isEmpty() || dcopName == "unnamed" ) + dcopName = viewName().utf8(); + if ( dcopName.isEmpty() || dcopName == "unnamed" ) { + TQVariant dcopProperty = part()->property( "dcopObjectId" ); + if ( dcopProperty.type() == TQVariant::CString ) + dcopName = dcopProperty.toCString(); + } + dcopName += "-view"; // to avoid having the same name as the part + m_dcopObject = new KonqViewIface( this, dcopName ); + } + return m_dcopObject; +} + +bool KonqView::eventFilter( TQObject *obj, TQEvent *e ) +{ + if ( !m_pPart ) + return false; +// kdDebug() << "--" << obj->className() << "--" << e->type() << "--" << endl; + if ( e->type() == TQEvent::DragEnter && m_bURLDropHandling && TQT_BASE_OBJECT(obj) == TQT_BASE_OBJECT(m_pPart->widget()) ) + { + TQDragEnterEvent *ev = static_cast( e ); + + if ( KURLDrag::canDecode( ev ) ) + { + KURL::List lstDragURLs; + bool ok = KURLDrag::decode( ev, lstDragURLs ); + + TQObjectList *children = m_pPart->widget()->queryList( TQWIDGET_OBJECT_NAME_STRING ); + + if ( ok && + !lstDragURLs.first().url().contains( "javascript:", false ) && // ### this looks like a hack to me + ev->source() != m_pPart->widget() && + children && + children->findRef( TQT_TQOBJECT(ev->source()) ) == -1 ) + ev->acceptAction(); + + delete children; + } + } + else if ( e->type() == TQEvent::Drop && m_bURLDropHandling && TQT_BASE_OBJECT(obj) == TQT_BASE_OBJECT(m_pPart->widget()) ) + { + TQDropEvent *ev = static_cast( e ); + + KURL::List lstDragURLs; + bool ok = KURLDrag::decode( ev, lstDragURLs ); + + KParts::BrowserExtension *ext = browserExtension(); + if ( ok && ext && lstDragURLs.first().isValid() ) + emit ext->openURLRequest( lstDragURLs.first() ); // this will call m_pMainWindow::slotOpenURLRequest delayed + } + + if ( m_bBackRightClick ) + { + if ( e->type() == TQEvent::ContextMenu ) + { + TQContextMenuEvent *ev = TQT_TQCONTEXTMENUEVENT( e ); + if ( ev->reason() == TQContextMenuEvent::Mouse ) + { + return true; + } + } + else if ( e->type() == TQEvent::MouseButtonPress ) + { + TQMouseEvent *ev = TQT_TQMOUSEEVENT( e ); + if ( ev->button() == Qt::RightButton ) + { + return true; + } + } + else if ( e->type() == TQEvent::MouseButtonRelease ) + { + TQMouseEvent *ev = TQT_TQMOUSEEVENT( e ); + if ( ev->button() == Qt::RightButton ) + { + emit backRightClick(); + return true; + } + } + else if ( e->type() == TQEvent::MouseMove ) + { + TQMouseEvent *ev = TQT_TQMOUSEEVENT( e ); + if ( ev->state() == Qt::RightButton ) + { + obj->removeEventFilter( this ); + TQMouseEvent me( TQEvent::MouseButtonPress, ev->pos(), 2, 2 ); + TQApplication::sendEvent( obj, &me ); + TQContextMenuEvent ce( TQContextMenuEvent::Mouse, ev->pos(), 2 ); + TQApplication::sendEvent( obj, &ce ); + obj->installEventFilter( this ); + return true; + } + } + } + + if ( e->type() == TQEvent::FocusIn ) + { + setActiveInstance(); + } + return false; +} + +void KonqView::setActiveInstance() +{ + if ( m_bBuiltinView || !m_pPart->instance() /*never!*/) + TDEGlobal::_activeInstance = TDEGlobal::instance(); + else + TDEGlobal::_activeInstance = m_pPart->instance(); +} + +bool KonqView::prepareReload( KParts::URLArgs& args ) +{ + args.reload = true; + // Repost form data if this URL is the result of a POST HTML form. + if ( m_doPost && !args.redirectedRequest() ) + { + if ( KMessageBox::warningContinueCancel( 0, i18n( + "The page you are trying to view is the result of posted form data. " + "If you resend the data, any action the form carried out (such as search or online purchase) will be repeated. "), + i18n( "Warning" ), i18n( "Resend" ) ) == KMessageBox::Continue ) + { + args.setDoPost( true ); + args.setContentType( m_postContentType ); + args.postData = m_postData; + } + else + return false; + } + // Re-set referrer + args.metaData()["referrer"] = m_pageReferrer; + + return true; +} + +KParts::BrowserExtension * KonqView::browserExtension() const +{ + return KParts::BrowserExtension::childObject( m_pPart ); +} + +KParts::StatusBarExtension * KonqView::statusBarExtension() const +{ + return KParts::StatusBarExtension::childObject( m_pPart ); +} + +bool KonqView::supportsServiceType( const TQString &serviceType ) const +{ + const TQStringList lst = serviceTypes(); + for( TQStringList::ConstIterator it = lst.begin(); it != lst.end(); ++it ) { + if ( *it == serviceType ) + return true; + // Maybe we should keep around a list of KServiceType::Ptr? + KMimeType::Ptr mime = KMimeType::mimeType( *it ); + if ( mime && mime->is( serviceType ) ) // respect inheritance + return true; + } + return false; +} + +#include "konq_view.moc" diff --git a/konqueror/konq_viewmgr.cc b/konqueror/konq_viewmgr.cc deleted file mode 100644 index 495d267e8..000000000 --- a/konqueror/konq_viewmgr.cc +++ /dev/null @@ -1,1842 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 1999 Simon Hausmann - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -*/ - -#include "konq_viewmgr.h" -#include "konq_view.h" -#include "konq_frame.h" -#include "konq_tabs.h" -#include "konq_profiledlg.h" -#include "konq_events.h" -#include "konq_settingsxt.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -// #define DEBUG_VIEWMGR - -template class TQPtrList; - -KonqViewManager::KonqViewManager( KonqMainWindow *mainWindow ) - : KParts::PartManager( mainWindow ) -{ - m_pMainWindow = mainWindow; - m_pDocContainer = 0L; - - m_pamProfiles = 0L; - m_bProfileListDirty = true; - m_bLoadingProfile = false; - - m_activePartChangedTimer = new TQTimer(this); - connect(m_activePartChangedTimer, TQT_SIGNAL(timeout()), this, TQT_SLOT(emitActivePartChanged())); - connect( this, TQT_SIGNAL( activePartChanged ( KParts::Part * ) ), this, TQT_SLOT( slotActivePartChanged ( KParts::Part * ) ) ); -} - -KonqView* KonqViewManager::Initialize( const TQString &serviceType, const TQString &serviceName ) -{ - //kdDebug(1202) << "KonqViewManager::Initialize()" << endl; - KService::Ptr service; - TDETrader::OfferList partServiceOffers, appServiceOffers; - KonqViewFactory newViewFactory = createView( serviceType, serviceName, service, partServiceOffers, appServiceOffers, true /*forceAutoEmbed*/ ); - if ( newViewFactory.isNull() ) - { - kdDebug(1202) << "KonqViewManager::Initialize() No suitable factory found." << endl; - return 0; - } - - KonqView* childView = setupView( m_pMainWindow, newViewFactory, service, partServiceOffers, appServiceOffers, serviceType, false ); - - setActivePart( childView->part() ); - m_pDocContainer = childView->frame(); - - convertDocContainer(); - static_cast( m_pDocContainer )->setAlwaysTabbedMode(KonqSettings::alwaysTabbedMode()); - static_cast( m_pDocContainer )->setMouseWheelScroll(KonqSettings::tabsCycleWheel()); - - m_pDocContainer->widget()->show(); - return childView; -} - -KonqViewManager::~KonqViewManager() -{ - //kdDebug(1202) << "KonqViewManager::~KonqViewManager()" << endl; - clear(); -} - -KonqView* KonqViewManager::splitView ( Qt::Orientation orientation, - const TQString &serviceType, - const TQString &serviceName, - bool newOneFirst, bool forceAutoEmbed ) -{ -#ifdef DEBUG_VIEWMGR - kdDebug(1202) << "KonqViewManager::splitView(ServiceType)" << endl; - m_pMainWindow->dumpViewList(); - printFullHierarchy( m_pMainWindow ); -#endif - - KonqFrame* splitFrame = m_pMainWindow->currentView()->frame(); - - KService::Ptr service; - TDETrader::OfferList partServiceOffers, appServiceOffers; - - KonqViewFactory newViewFactory = createView( serviceType, serviceName, service, partServiceOffers, appServiceOffers, forceAutoEmbed ); - - if( newViewFactory.isNull() ) - return 0L; //do not split at all if we can't create the new view - - assert( splitFrame ); - - KonqFrameContainerBase* parentContainer = splitFrame->parentContainer(); - - bool moveNewContainer = false; - TQValueList splitterSizes; - int index= -1; - - if (parentContainer->frameType()=="Container") { - moveNewContainer = (static_cast(parentContainer)->idAfter( splitFrame->widget() ) != 0); - splitterSizes = static_cast(parentContainer)->sizes(); - } - else if (parentContainer->frameType()=="Tabs") - index = static_cast(parentContainer)->indexOf( splitFrame->widget() ); - -#ifndef NDEBUG - //printSizeInfo( splitFrame, parentContainer, "before split"); -#endif - - parentContainer->widget()->setUpdatesEnabled( false ); - - //kdDebug(1202) << "Move out child" << endl; - TQPoint pos = splitFrame->widget()->pos(); - parentContainer->removeChildFrame( splitFrame ); - splitFrame->widget()->reparent( m_pMainWindow, pos ); - - //kdDebug(1202) << "Create new Container" << endl; - KonqFrameContainer *newContainer = new KonqFrameContainer( orientation, parentContainer->widget(), parentContainer ); - connect(newContainer,TQT_SIGNAL(ctrlTabPressed()),m_pMainWindow,TQT_SLOT(slotCtrlTabPressed())); - - parentContainer->insertChildFrame( newContainer, index ); - if ( moveNewContainer ) { - static_cast(parentContainer)->moveToFirst( newContainer ); - static_cast(parentContainer)->swapChildren(); - } - - //kdDebug(1202) << "Move in child" << endl; - splitFrame->widget()->reparent( newContainer, pos ); - newContainer->insertChildFrame( splitFrame ); - -#ifndef NDEBUG - //printSizeInfo( splitFrame, parentContainer, "after reparent" ); -#endif - - //kdDebug(1202) << "Create new child" << endl; - KonqView *newView = setupView( newContainer, newViewFactory, service, partServiceOffers, appServiceOffers, serviceType, false ); - -#ifndef DEBUG - //printSizeInfo( splitFrame, parentContainer, "after child insert" ); -#endif - - if ( newOneFirst ) - { - newContainer->moveToLast( splitFrame->widget() ); - newContainer->swapChildren(); - } - - TQValueList newSplitterSizes; - newSplitterSizes << 50 << 50; - newContainer->setSizes( newSplitterSizes ); - - if (parentContainer->frameType()=="Container") { - static_cast(parentContainer)->setSizes( splitterSizes ); - } - else if (parentContainer->frameType()=="Tabs") - static_cast(parentContainer)->showPage( newContainer ); - - splitFrame->show(); - //newView->frame()->show(); - newContainer->show(); - - parentContainer->widget()->setUpdatesEnabled( true ); - - if (m_pDocContainer == splitFrame) m_pDocContainer = newContainer; - - assert( newView->frame() ); - assert( newView->part() ); - newContainer->setActiveChild( newView->frame() ); - setActivePart( newView->part(), false ); - -#ifdef DEBUG_VIEWMGR - m_pMainWindow->dumpViewList(); - printFullHierarchy( m_pMainWindow ); - kdDebug(1202) << "KonqViewManager::splitView(ServiceType) done" << endl; -#endif - - return newView; -} - -KonqView* KonqViewManager::splitWindow( Qt::Orientation orientation, - const TQString &serviceType, - const TQString &serviceName, - bool newOneFirst ) -{ - kdDebug(1202) << "KonqViewManager::splitWindow(default)" << endl; - - // Don't crash when doing things too quickly. - if (!m_pMainWindow || !m_pMainWindow->currentView()) - return 0L; - - KURL url = m_pMainWindow->currentView()->url(); - TQString locationBarURL = m_pMainWindow->currentView()->locationBarURL(); - - KService::Ptr service; - TDETrader::OfferList partServiceOffers, appServiceOffers; - - KonqViewFactory newViewFactory = createView( serviceType, serviceName, service, partServiceOffers, appServiceOffers ); - - if( newViewFactory.isNull() ) - return 0L; //do not split at all if we can't create the new view - - KonqFrameBase* mainFrame = m_pMainWindow->childFrame(); - - mainFrame->widget()->setUpdatesEnabled( false ); - - //kdDebug(1202) << "Move out child" << endl; - TQPoint pos = mainFrame->widget()->pos(); - m_pMainWindow->removeChildFrame( mainFrame ); - - KonqFrameContainer *newContainer = new KonqFrameContainer( orientation, m_pMainWindow, 0L); - connect(newContainer,TQT_SIGNAL(ctrlTabPressed()),m_pMainWindow,TQT_SLOT(slotCtrlTabPressed())); - - m_pMainWindow->insertChildFrame( newContainer ); - - newContainer->insertChildFrame( mainFrame ); - mainFrame->widget()->reparent( newContainer, pos ); - - KonqView* childView = setupView( newContainer, newViewFactory, service, partServiceOffers, appServiceOffers, serviceType, true ); - - if( newOneFirst ) { - static_cast(newContainer)->moveToFirst( childView->frame() ); - static_cast(newContainer)->swapChildren(); - } - - newContainer->show(); - - mainFrame->widget()->setUpdatesEnabled( true ); - - if( childView ) - childView->openURL( url, locationBarURL ); - - newContainer->setActiveChild( mainFrame ); - -#ifdef DEBUG_VIEWMGR - m_pMainWindow->dumpViewList(); - printFullHierarchy( m_pMainWindow ); - kdDebug(1202) << "KonqViewManager::splitWindow(default) done" << endl; -#endif - - return childView; -} - -void KonqViewManager::convertDocContainer() -{ - // Must create a tab container since one is not present, - // then insert the existing frame as a tab - - KonqFrameContainerBase* parentContainer = m_pDocContainer->parentContainer(); - - bool moveNewContainer = false; - TQValueList splitterSizes; - if (parentContainer->frameType()=="Container") { - moveNewContainer = (static_cast(parentContainer)->idAfter( m_pDocContainer->widget() ) != 0); - splitterSizes = static_cast(parentContainer)->sizes(); - } - - parentContainer->widget()->setUpdatesEnabled( false ); - - //kdDebug(1202) << "Move out child" << endl; - TQPoint pos = m_pDocContainer->widget()->pos(); - parentContainer->removeChildFrame( m_pDocContainer ); - m_pDocContainer->widget()->reparent( m_pMainWindow, pos ); - - KonqFrameTabs* newContainer = new KonqFrameTabs( parentContainer->widget() , parentContainer, this); - parentContainer->insertChildFrame( newContainer ); - connect( newContainer, TQT_SIGNAL(ctrlTabPressed()), m_pMainWindow, TQT_SLOT(slotCtrlTabPressed()) ); - - m_pDocContainer->widget()->reparent( newContainer, pos ); - newContainer->insertChildFrame( m_pDocContainer ); - - if ( moveNewContainer ) { - static_cast(parentContainer)->moveToFirst( newContainer ); - static_cast(parentContainer)->swapChildren(); - } - if (parentContainer->frameType()=="Container") - static_cast(parentContainer)->setSizes( splitterSizes ); - - newContainer->show(); - - parentContainer->widget()->setUpdatesEnabled( true ); - - m_pDocContainer = newContainer; -} - -KonqView* KonqViewManager::addTab(const TQString &serviceType, const TQString &serviceName, bool passiveMode, bool openAfterCurrentPage ) -{ -#ifdef DEBUG_VIEWMGR - kdDebug(1202) << "------------- KonqViewManager::addTab starting -------------" << endl; - m_pMainWindow->dumpViewList(); - printFullHierarchy( m_pMainWindow ); -#endif - - if (m_pDocContainer == 0L) - { - if (m_pMainWindow && - m_pMainWindow->currentView() && - m_pMainWindow->currentView()->frame()) { - m_pDocContainer = m_pMainWindow->currentView()->frame(); - } else { - kdDebug(1202) << "This view profile does not support tabs." << endl; - return 0L; - } - } - - KService::Ptr service; - TDETrader::OfferList partServiceOffers, appServiceOffers; - - KonqViewFactory newViewFactory = createView( serviceType, serviceName, service, partServiceOffers, appServiceOffers, true /*forceAutoEmbed*/ ); - - if( newViewFactory.isNull() ) - return 0L; //do not split at all if we can't create the new view - - if (m_pDocContainer->frameType() != "Tabs") convertDocContainer(); - - KonqView* childView = setupView( static_cast(m_pDocContainer), newViewFactory, service, partServiceOffers, appServiceOffers, serviceType, passiveMode, openAfterCurrentPage ); - -#ifdef DEBUG_VIEWMGR - m_pMainWindow->dumpViewList(); - printFullHierarchy( m_pMainWindow ); - kdDebug(1202) << "------------- KonqViewManager::addTab done -------------" << endl; -#endif - - return childView; -} - -KonqView* KonqViewManager::addTabFromHistory( int steps, bool openAfterCurrentPage ) -{ - if (m_pDocContainer == 0L) - { - if (m_pMainWindow && - m_pMainWindow->currentView() && - m_pMainWindow->currentView()->frame()) { - m_pDocContainer = m_pMainWindow->currentView()->frame(); - } else { - kdDebug(1202) << "This view profile does not support tabs." << endl; - return 0L; - } - } - if (m_pDocContainer->frameType() != "Tabs") convertDocContainer(); - - int oldPos = m_pMainWindow->currentView()->historyPos(); - int newPos = oldPos + steps; - - const HistoryEntry * he = m_pMainWindow->currentView()->historyAt(newPos); - if(!he) - return 0L; - - KonqView* newView = 0L; - newView = addTab( he->strServiceType, he->strServiceName, false, openAfterCurrentPage ); - - if(!newView) - return 0L; - - newView->copyHistory(m_pMainWindow->currentView()); - newView->setHistoryPos(newPos); - newView->restoreHistory(); - - return newView; -} - - -void KonqViewManager::duplicateTab( KonqFrameBase* tab, bool openAfterCurrentPage ) -{ -#ifdef DEBUG_VIEWMGR - kdDebug(1202) << "---------------- KonqViewManager::duplicateTab( " << tab << " ) --------------" << endl; - m_pMainWindow->dumpViewList(); - printFullHierarchy( m_pMainWindow ); -#endif - - if (m_pDocContainer == 0L) - { - if (m_pMainWindow && - m_pMainWindow->currentView() && - m_pMainWindow->currentView()->frame()) { - m_pDocContainer = m_pMainWindow->currentView()->frame(); - } else { - kdDebug(1202) << "This view profile does not support tabs." << endl; - return; - } - } - - if (m_pDocContainer->frameType() != "Tabs") convertDocContainer(); - - KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); - - KonqFrameBase* currentFrame; - if ( tab == 0L ) - currentFrame = tqt_dynamic_cast(tabContainer->currentPage()); - else - currentFrame = tab; - - if (!currentFrame) { - return; - } - - KTempFile tempFile; - tempFile.setAutoDelete( true ); - TDEConfig config( tempFile.name() ); - config.setGroup( "View Profile" ); - - TQString prefix = TQString::fromLatin1( currentFrame->frameType() ) + TQString::number(0); - config.writeEntry( "RootItem", prefix ); - prefix.append( '_' ); - currentFrame->saveConfig( &config, prefix, true, 0L, 0, 1); - - TQString rootItem = config.readEntry( "RootItem", "empty" ); - - if (rootItem.isNull() || rootItem == "empty") return; - - // This flag is used by KonqView, to distinguish manual view creation - // from profile loading (e.g. in switchView) - m_bLoadingProfile = true; - - loadItem( config, tabContainer, rootItem, KURL(""), true, openAfterCurrentPage ); - - m_bLoadingProfile = false; - - m_pMainWindow->enableAllActions(true); - - // This flag disables calls to viewCountChanged while creating the views, - // so we do it once at the end : - m_pMainWindow->viewCountChanged(); - - if (openAfterCurrentPage) - tabContainer->setCurrentPage( tabContainer->currentPageIndex () + 1 ); - else - tabContainer->setCurrentPage( tabContainer->count() - 1 ); - - KonqFrameBase* duplicatedFrame = tqt_dynamic_cast(tabContainer->currentPage()); - if (duplicatedFrame) - duplicatedFrame->copyHistory( currentFrame ); - -#ifdef DEBUG_VIEWMGR - m_pMainWindow->dumpViewList(); - printFullHierarchy( m_pMainWindow ); - kdDebug(1202) << "------------- KonqViewManager::duplicateTab done --------------" << endl; -#endif -} - -void KonqViewManager::breakOffTab( KonqFrameBase* tab ) -{ -#ifdef DEBUG_VIEWMGR - kdDebug(1202) << "---------------- KonqViewManager::breakOffTab( " << tab << " ) --------------" << endl; - m_pMainWindow->dumpViewList(); - printFullHierarchy( m_pMainWindow ); -#endif - - if (m_pDocContainer == 0L) return; - if (m_pDocContainer->frameType() != "Tabs") return; - - KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); - - int width = m_pMainWindow->width(); - int height = m_pMainWindow->height(); - - KonqFrameBase* currentFrame; - if ( tab == 0L ) - currentFrame = tqt_dynamic_cast(tabContainer->currentPage()); - else - currentFrame = tab; - - if (!currentFrame) { - return; - } - - KTempFile tempFile; - tempFile.setAutoDelete( true ); - TDEConfig config( tempFile.name() ); - config.setGroup( "View Profile" ); - - TQString prefix = TQString::fromLatin1( currentFrame->frameType() ) + TQString::number(0); - config.writeEntry( "RootItem", prefix ); - prefix.append( '_' ); - config.writeEntry( TQString::fromLatin1( "docContainer" ).prepend( prefix ), true ); - currentFrame->saveConfig( &config, prefix, true, 0L, 0, 1); - - KonqMainWindow *mainWindow = new KonqMainWindow( KURL(), false ); - if (mainWindow == 0L) return; - - mainWindow->viewManager()->loadViewProfile( config, "" ); - - KonqFrameBase * newDocContainer = mainWindow->viewManager()->docContainer(); - if( newDocContainer && newDocContainer->frameType() == "Tabs") - { - KonqFrameTabs *kft = static_cast(newDocContainer); - KonqFrameBase *newFrame = tqt_dynamic_cast(kft->currentPage()); - if(newFrame) - newFrame->copyHistory( currentFrame ); - } - - removeTab( currentFrame ); - - mainWindow->enableAllActions( true ); - - mainWindow->resize( width, height ); - - mainWindow->activateChild(); - - mainWindow->show(); - -#ifdef DEBUG_VIEWMGR - m_pMainWindow->dumpViewList(); - printFullHierarchy( m_pMainWindow ); - - mainWindow->dumpViewList(); - mainWindow->viewManager()->printFullHierarchy( mainWindow ); - - kdDebug(1202) << "------------- KonqViewManager::breakOffTab done --------------" << endl; -#endif -} - -void KonqViewManager::removeTab( KonqFrameBase* tab ) -{ -#ifdef DEBUG_VIEWMGR - kdDebug(1202) << "---------------- KonqViewManager::removeTab( " << tab << " ) --------------" << endl; - m_pMainWindow->dumpViewList(); - printFullHierarchy( m_pMainWindow ); -#endif - - if (m_pDocContainer == 0L) - return; - if (m_pDocContainer->frameType() != "Tabs" ) - return; - - KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); - - KonqFrameBase* currentFrame; - if ( tab != 0L ) { - currentFrame = tab; - } else { - currentFrame = tqt_dynamic_cast(tabContainer->currentPage()); - if (!currentFrame) { - return; - } - } - - if ( tabContainer->count() == 1 ) - return; - - if (currentFrame->widget() == tabContainer->currentPage()) - setActivePart( 0L, true ); - - tabContainer->removeChildFrame(currentFrame); - - TQPtrList viewList; - TQPtrListIterator it( viewList ); - - currentFrame->listViews( &viewList ); - - for ( it.toFirst(); it != 0L; ++it ) - { - if (it.current() == m_pMainWindow->currentView()) - setActivePart( 0L, true ); - m_pMainWindow->removeChildView( it.current() ); - delete it.current(); - } - - delete currentFrame; - - tabContainer->slotCurrentChanged(tabContainer->currentPage()); - -#ifdef DEBUG_VIEWMGR - m_pMainWindow->dumpViewList(); - printFullHierarchy( m_pMainWindow ); - kdDebug(1202) << "------------- KonqViewManager::removeTab done --------------" << endl; -#endif -} - -void KonqViewManager::reloadAllTabs( ) -{ - if (m_pDocContainer == 0L) return; - if (m_pDocContainer->frameType() != "Tabs") return; - - KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); - - TQPtrList frameList = *tabContainer->childFrameList(); - TQPtrListIterator it( frameList ); - - for ( it.toFirst(); it != 0L; ++it ) - { - if ( it.current()->activeChildView()) - { - if( !it.current()->activeChildView()->locationBarURL().isEmpty()) - it.current()->activeChildView()->openURL( it.current()->activeChildView()->url(),it.current()->activeChildView()->locationBarURL()); - } - } -} - -void KonqViewManager::removeOtherTabs( KonqFrameBase* tab ) -{ - - if (m_pDocContainer == 0L) return; - if (m_pDocContainer->frameType() != "Tabs") return; - - KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); - - KonqFrameBase *currentFrame; - - if ( tab == 0L ) - currentFrame = tqt_dynamic_cast(tabContainer->currentPage()); - else - currentFrame = tab; - - if (!currentFrame) { - return; - } - - TQPtrList frameList = *tabContainer->childFrameList(); - TQPtrListIterator it( frameList ); - - for ( it.toFirst(); it != 0L; ++it ) - { - if( it.current() != currentFrame ) - removeTab(it.current()); - } - -} - -void KonqViewManager::moveTabBackward() -{ - if (m_pDocContainer == 0L) return; - if (m_pDocContainer->frameType() != "Tabs") return; - KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); - if( tabContainer->count() == 1 ) return; - - int iTab = tabContainer->currentPageIndex(); - kdDebug()<<" tabContainer->currentPageIndex(); :"<moveTabBackward(iTab); -} - -void KonqViewManager::moveTabForward() -{ - if (m_pDocContainer == 0L) return; - if (m_pDocContainer->frameType() != "Tabs") return; - KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); - if( tabContainer->count() == 1 ) return; - - int iTab = tabContainer->currentPageIndex(); - tabContainer->moveTabForward(iTab); -} - -void KonqViewManager::activateNextTab() -{ - if (m_pDocContainer == 0L) return; - if (m_pDocContainer->frameType() != "Tabs") return; - - KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); - if( tabContainer->count() == 1 ) return; - - int iTab = tabContainer->currentPageIndex(); - - iTab++; - - if( iTab == tabContainer->count() ) - iTab = 0; - - tabContainer->setCurrentPage( iTab ); -} - -void KonqViewManager::activatePrevTab() -{ - if (m_pDocContainer == 0L) return; - if (m_pDocContainer->frameType() != "Tabs") return; - - KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); - if( tabContainer->count() == 1 ) return; - - int iTab = tabContainer->currentPageIndex(); - - iTab--; - - if( iTab == -1 ) - iTab = tabContainer->count() - 1; - - tabContainer->setCurrentPage( iTab ); -} - -void KonqViewManager::activateTab(int position) -{ - if (m_pDocContainer == 0L) return; - if (m_pDocContainer->frameType() != "Tabs") return; - - KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); - if (position<0 || tabContainer->count() == 1 || position>=tabContainer->count()) return; - - tabContainer->setCurrentPage( position ); -} - -void KonqViewManager::showTab( KonqView *view ) -{ - KonqFrameTabs *tabContainer = static_cast( docContainer() ); - if (tabContainer->currentPage() != view->frame()) - { - tabContainer->showPage( view->frame() ); - emitActivePartChanged(); - } -} - -void KonqViewManager::updatePixmaps() -{ - if (m_pDocContainer == 0L) return; - if (m_pDocContainer->frameType() != "Tabs") return; - - KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); - - TQPtrList viewList; - TQPtrListIterator it( viewList ); - - tabContainer->listViews( &viewList ); - for ( it.toFirst(); it != 0L; ++it ) - it.current()->setTabIcon( KURL::fromPathOrURL( it.current()->locationBarURL() ) ); -} - -void KonqViewManager::removeView( KonqView *view ) -{ -#ifdef DEBUG_VIEWMGR - kdDebug(1202) << "---------------- removeView --------------" << view << endl; - m_pMainWindow->dumpViewList(); - printFullHierarchy( m_pMainWindow ); -#endif - - if (!view) - return; - - KonqFrame* frame = view->frame(); - KonqFrameContainerBase* parentContainer = frame->parentContainer(); - - kdDebug(1202) << "view=" << view << " frame=" << frame << " parentContainer=" << parentContainer << endl; - - if (parentContainer->frameType()=="Container") - { - kdDebug(1202) << "parentContainer is a KonqFrameContainer" << endl; - - KonqFrameContainerBase* grandParentContainer = parentContainer->parentContainer(); - kdDebug(1202) << "grandParentContainer=" << grandParentContainer << endl; - - setActivePart( 0L, true ); - - int index = -1; - TQValueList splitterSizes; - bool moveOtherChild = false; - - if (grandParentContainer->frameType()=="Tabs") - index = static_cast(grandParentContainer)->indexOf( parentContainer->widget() ); - else if (grandParentContainer->frameType()=="Container") - { - moveOtherChild = (static_cast(grandParentContainer)->idAfter( parentContainer->widget() ) != 0); - splitterSizes = static_cast(grandParentContainer)->sizes(); - } - - KonqFrameBase* otherFrame = static_cast(parentContainer)->otherChild( frame ); - kdDebug(1202) << "otherFrame=" << otherFrame << endl; - - if( otherFrame == 0L ) - { - kdWarning(1202) << "KonqViewManager::removeView: This shouldn't happen!" << endl; - return; - } - - if (m_pDocContainer == parentContainer) m_pDocContainer = otherFrame; - - grandParentContainer->widget()->setUpdatesEnabled( false ); - static_cast(parentContainer)->setAboutToBeDeleted(); - - //kdDebug(1202) << "--- Reparenting otherFrame to m_pMainWindow " << m_pMainWindow << endl; - TQPoint pos = otherFrame->widget()->pos(); - otherFrame->reparentFrame( m_pMainWindow, pos ); - - //kdDebug(1202) << "--- Removing otherFrame from parentContainer" << endl; - parentContainer->removeChildFrame( otherFrame ); - - //kdDebug(1202) << "--- Removing parentContainer from grandParentContainer" << endl; - grandParentContainer->removeChildFrame( parentContainer ); - - //kdDebug(1202) << "--- Removing view from view list" << endl; - m_pMainWindow->removeChildView(view); - //kdDebug(1202) << "--- Deleting view " << view << endl; - delete view; // This deletes the view, which deletes the part, which deletes its widget - - //kdDebug(1202) << "--- Deleting parentContainer " << parentContainer - // << ". Its parent is " << parentContainer->widget()->parent() << endl; - delete parentContainer; - - //kdDebug(1202) << "--- Reparenting otherFrame to grandParentContainer" << grandParentContainer << endl; - otherFrame->reparentFrame( grandParentContainer->widget(), pos ); - - //kdDebug(1202) << "--- Inserting otherFrame into grandParentContainer" << grandParentContainer << endl; - grandParentContainer->insertChildFrame( otherFrame, index ); - - if( moveOtherChild ) - { - static_cast(grandParentContainer)->moveToFirst( otherFrame->widget() ); - static_cast(grandParentContainer)->swapChildren(); - } - - if (grandParentContainer->frameType()=="Container") - static_cast(grandParentContainer)->setSizes( splitterSizes ); - - otherFrame->widget()->show(); - - grandParentContainer->setActiveChild( otherFrame ); - grandParentContainer->activateChild(); - - grandParentContainer->widget()->setUpdatesEnabled( true ); - } - else if (parentContainer->frameType()=="Tabs") { - kdDebug(1202) << "parentContainer " << parentContainer << " is a KonqFrameTabs" << endl; - - removeTab( frame ); - } - else if (parentContainer->frameType()=="MainWindow") - kdDebug(1202) << "parentContainer is a KonqMainWindow. This shouldn't be removeable, not removing." << endl; - else - kdDebug(1202) << "Unrecognized frame type, not removing." << endl; - -#ifdef DEBUG_VIEWMGR - printFullHierarchy( m_pMainWindow ); - m_pMainWindow->dumpViewList(); - - kdDebug(1202) << "------------- removeView done --------------" << view << endl; -#endif -} - -// reimplemented from PartManager -void KonqViewManager::removePart( KParts::Part * part ) -{ - kdDebug(1202) << "KonqViewManager::removePart ( " << part << " )" << endl; - // This is called when a part auto-deletes itself (case 1), or when - // the "delete view" above deletes, in turn, the part (case 2) - - kdDebug(1202) << "Calling KParts::PartManager::removePart " << part << endl; - KParts::PartManager::removePart( part ); - - // If we were called by PartManager::slotObjectDestroyed, then the inheritance has - // been deleted already... Can't use inherits(). - - KonqView * view = m_pMainWindow->childView( static_cast(part) ); - if ( view ) // the child view still exists, so we are in case 1 - { - kdDebug(1202) << "Found a child view" << endl; - view->partDeleted(); // tell the child view that the part auto-deletes itself - if (m_pMainWindow->mainViewsCount() == 1) - { - kdDebug(1202) << "Deleting last view -> closing the window" << endl; - clear(); - kdDebug(1202) << "Closing m_pMainWindow " << m_pMainWindow << endl; - m_pMainWindow->close(); // will delete it - return; - } else { // normal case - removeView( view ); - } - } - - kdDebug(1202) << "KonqViewManager::removePart ( " << part << " ) done" << endl; -} - -void KonqViewManager::slotPassiveModePartDeleted() -{ - // Passive mode parts aren't registered to the part manager, - // so we have to handle suicidal ones ourselves - KParts::ReadOnlyPart * part = const_cast( static_cast( sender() ) ); - disconnect( part, TQT_SIGNAL( destroyed() ), this, TQT_SLOT( slotPassiveModePartDeleted() ) ); - kdDebug(1202) << "KonqViewManager::slotPassiveModePartDeleted part=" << part << endl; - KonqView * view = m_pMainWindow->childView( part ); - kdDebug(1202) << "view=" << view << endl; - if ( view != 0L) // the child view still exists, so the part suicided - { - view->partDeleted(); // tell the child view that the part deleted itself - removeView( view ); - } -} - -void KonqViewManager::viewCountChanged() -{ - bool bShowActiveViewIndicator = ( m_pMainWindow->viewCount() > 1 ); - bool bShowLinkedViewIndicator = ( m_pMainWindow->linkableViewsCount() > 1 ); - - KonqMainWindow::MapViews mapViews = m_pMainWindow->viewMap(); - KonqMainWindow::MapViews::Iterator it = mapViews.begin(); - KonqMainWindow::MapViews::Iterator end = mapViews.end(); - for ( ; it != end ; ++it ) - { - KonqFrameStatusBar* sb = it.data()->frame()->statusbar(); - sb->showActiveViewIndicator( bShowActiveViewIndicator && !it.data()->isPassiveMode() ); - sb->showLinkedViewIndicator( bShowLinkedViewIndicator && !it.data()->isFollowActive() ); - } -} - -void KonqViewManager::clear() -{ - kdDebug(1202) << "KonqViewManager::clear" << endl; - setActivePart( 0L, true /* immediate */ ); - - if (m_pMainWindow->childFrame() == 0L) return; - - TQPtrList viewList; - - m_pMainWindow->listViews( &viewList ); - - kdDebug(1202) << viewList.count() << " items" << endl; - - TQPtrListIterator it( viewList ); - for ( it.toFirst(); it.current(); ++it ) { - m_pMainWindow->removeChildView( it.current() ); - kdDebug(1202) << "Deleting " << it.current() << endl; - delete it.current(); - } - - kdDebug(1202) << "deleting mainFrame " << endl; - KonqFrameBase* frame = m_pMainWindow->childFrame(); - m_pMainWindow->removeChildFrame( frame ); // will set childFrame() to NULL - delete frame; - - m_pDocContainer = 0L; -} - -KonqView *KonqViewManager::chooseNextView( KonqView *view ) -{ - //kdDebug(1202) << "KonqViewManager(" << this << ")::chooseNextView(" << view << ")" << endl; - KonqMainWindow::MapViews mapViews = m_pMainWindow->viewMap(); - - KonqMainWindow::MapViews::Iterator it = mapViews.begin(); - KonqMainWindow::MapViews::Iterator end = mapViews.end(); - if ( view ) // find it in the map - can't use the key since view->part() might be 0L - while ( it != end && it.data() != view ) - ++it; - - // the view should always be in the list - if ( it == end ) { - if ( view ) - kdWarning() << "View " << view << " is not in list !" << endl; - it = mapViews.begin(); - if ( it == end ) - return 0L; // We have no view at all - this used to happen with totally-empty-profiles - } - - KonqMainWindow::MapViews::Iterator startIt = it; - - //kdDebug(1202) << "KonqViewManager::chooseNextView: count=" << mapViews.count() << endl; - while ( true ) - { - //kdDebug(1202) << "*KonqViewManager::chooseNextView going next" << endl; - if ( ++it == end ) // move to next - it = mapViews.begin(); // rewind on end - - if ( it == startIt && view ) - break; // no next view found - - KonqView *nextView = it.data(); - if ( nextView && !nextView->isPassiveMode() ) - return nextView; - //kdDebug(1202) << "KonqViewManager::chooseNextView nextView=" << nextView << " passive=" << nextView->isPassiveMode() << endl; - } - - //kdDebug(1202) << "KonqViewManager::chooseNextView: returning 0L" << endl; - return 0L; // no next view found -} - -KonqViewFactory KonqViewManager::createView( const TQString &serviceType, - const TQString &serviceName, - KService::Ptr &service, - TDETrader::OfferList &partServiceOffers, - TDETrader::OfferList &appServiceOffers, - bool forceAutoEmbed ) -{ - kdDebug(1202) << "KonqViewManager::createView" << endl; - KonqViewFactory viewFactory; - - if( serviceType.isEmpty() && m_pMainWindow->currentView() ) { - //clone current view - KonqView *cv = m_pMainWindow->currentView(); - TQString _serviceType, _serviceName; - if ( cv->service()->desktopEntryName() == "konq_sidebartng" ) { - _serviceType = "text/html"; - } - else { - _serviceType = cv->serviceType(); - _serviceName = cv->service()->desktopEntryName(); - } - - viewFactory = KonqFactory::createView( _serviceType, _serviceName, - &service, &partServiceOffers, &appServiceOffers, forceAutoEmbed ); - } - else { - //create view with the given servicetype - viewFactory = KonqFactory::createView( serviceType, serviceName, - &service, &partServiceOffers, &appServiceOffers, forceAutoEmbed ); - } - - return viewFactory; -} - -KonqView *KonqViewManager::setupView( KonqFrameContainerBase *parentContainer, - KonqViewFactory &viewFactory, - const KService::Ptr &service, - const TDETrader::OfferList &partServiceOffers, - const TDETrader::OfferList &appServiceOffers, - const TQString &serviceType, - bool passiveMode, - bool openAfterCurrentPage ) -{ - kdDebug(1202) << "KonqViewManager::setupView passiveMode=" << passiveMode << endl; - - TQString sType = serviceType; - - if ( sType.isEmpty() ) - sType = m_pMainWindow->currentView()->serviceType(); - - //kdDebug(1202) << "KonqViewManager::setupView creating KonqFrame with parent=" << parentContainer << endl; - KonqFrame* newViewFrame = new KonqFrame( parentContainer->widget(), parentContainer, "KonqFrame" ); - newViewFrame->setGeometry( 0, 0, m_pMainWindow->width(), m_pMainWindow->height() ); - - //kdDebug(1202) << "Creating KonqView" << endl; - KonqView *v = new KonqView( viewFactory, newViewFrame, - m_pMainWindow, service, partServiceOffers, appServiceOffers, sType, passiveMode ); - //kdDebug(1202) << "KonqView created - v=" << v << " v->part()=" << v->part() << endl; - - TQObject::connect( v, TQT_SIGNAL( sigPartChanged( KonqView *, KParts::ReadOnlyPart *, KParts::ReadOnlyPart * ) ), - m_pMainWindow, TQT_SLOT( slotPartChanged( KonqView *, KParts::ReadOnlyPart *, KParts::ReadOnlyPart * ) ) ); - - m_pMainWindow->insertChildView( v ); - - - int index = -1; - - if (m_pDocContainer && m_pDocContainer->frameType() == "Tabs") - { - KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); - if ( openAfterCurrentPage ) - index = tabContainer->currentPageIndex() +1 ; - } - - parentContainer->insertChildFrame( newViewFrame, index ); - - if (parentContainer->frameType() != "Tabs") newViewFrame->show(); - - // Don't register passive views to the part manager - if ( !v->isPassiveMode() ) // note that KonqView's constructor could set this to true even if passiveMode is false - addPart( v->part(), false ); - else - { - // Passive views aren't registered, but we still want to detect the suicidal ones - connect( v->part(), TQT_SIGNAL( destroyed() ), this, TQT_SLOT( slotPassiveModePartDeleted() ) ); - } - - //kdDebug(1202) << "KonqViewManager::setupView done" << endl; - return v; -} - -///////////////// Profile stuff //////////////// - -void KonqViewManager::saveViewProfile( const TQString & fileName, const TQString & profileName, bool saveURLs, bool saveWindowSize ) -{ - - TQString path = locateLocal( "data", TQString::fromLatin1( "konqueror/profiles/" ) + - fileName, TDEGlobal::instance() ); - - if ( TQFile::exists( path ) ) - TQFile::remove( path ); - - KSimpleConfig cfg( path ); - cfg.setGroup( "Profile" ); - if ( !profileName.isEmpty() ) - cfg.writePathEntry( "Name", profileName ); - - saveViewProfile( cfg, saveURLs, saveWindowSize ); - -} - -void KonqViewManager::saveViewProfile( TDEConfig & cfg, bool saveURLs, bool saveWindowSize ) -{ - //kdDebug(1202) << "KonqViewManager::saveViewProfile" << endl; - if( m_pMainWindow->childFrame() != 0L ) { - TQString prefix = TQString::fromLatin1( m_pMainWindow->childFrame()->frameType() ) - + TQString::number(0); - cfg.writeEntry( "RootItem", prefix ); - prefix.append( '_' ); - m_pMainWindow->saveConfig( &cfg, prefix, saveURLs, m_pDocContainer, 0, 1); - } - - cfg.writeEntry( "FullScreen", m_pMainWindow->fullScreenMode()); - cfg.writeEntry("XMLUIFile", m_pMainWindow->xmlFile()); - if ( saveWindowSize ) - { - cfg.writeEntry( "Width", m_pMainWindow->width() ); - cfg.writeEntry( "Height", m_pMainWindow->height() ); - } - - // Save menu/toolbar settings in profile. Relys on konq_mainwindow calling - // setAutoSaveSetting( "KongMainWindow", false ). The false is important, - // we do not want this call save size settings in the profile, because we - // do it ourselves. Save in a separate group than the rest of the profile. - TQString savedGroup = cfg.group(); - m_pMainWindow->saveMainWindowSettings( &cfg, "Main Window Settings" ); - cfg.setGroup( savedGroup ); - - cfg.sync(); -} - -void KonqViewManager::loadViewProfile( const TQString & path, const TQString & filename, - const KURL & forcedURL, const KonqOpenURLRequest &req, - bool resetWindow, bool openURL ) -{ - TDEConfig cfg( path, true ); - cfg.setDollarExpansion( true ); - cfg.setGroup( "Profile" ); - loadViewProfile( cfg, filename, forcedURL, req, resetWindow, openURL ); -} - -void KonqViewManager::loadViewProfile( TDEConfig &cfg, const TQString & filename, - const KURL & forcedURL, const KonqOpenURLRequest &req, - bool resetWindow, bool openURL ) -{ - if ( docContainer() && docContainer()->frameType()=="Tabs" ) - { - KonqFrameTabs* tabContainer = static_cast(docContainer()); - if ( tabContainer->count() > 1 ) - { - if ( KMessageBox::warningContinueCancel( 0, - i18n("You have multiple tabs open in this window.\n" - "Loading a view profile will close them."), - i18n("Confirmation"), - i18n("Load View Profile"), - "LoadProfileTabsConfirm" ) == KMessageBox::Cancel ) - return; - } - - KonqView *originalView = m_pMainWindow->currentView(); - TQPtrList frameList = *tabContainer->childFrameList(); - TQPtrListIterator it( frameList ); - for ( it.toFirst(); it != 0L; ++it ) - { - KonqView *view = it.current()->activeChildView(); - if (view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1)) { - TQVariant prop = view->part()->property("modified"); - if (prop.isValid() && prop.toBool()) { - showTab( view ); - if ( KMessageBox::warningContinueCancel( 0, - i18n("This tab contains changes that have not been submitted.\nLoading a profile will discard these changes."), - i18n("Discard Changes?"), i18n("&Discard Changes"), "discardchangesloadprofile") != KMessageBox::Continue ) - { - showTab( originalView ); - return; - } - } - } - } - showTab( originalView ); - } - else - { - KonqView *view = m_pMainWindow->currentView(); - if (view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1)) { - TQVariant prop = view->part()->property("modified"); - if (prop.isValid() && prop.toBool()) - if ( KMessageBox::warningContinueCancel( 0, - i18n("This page contains changes that have not been submitted.\nLoading a profile will discard these changes."), - i18n("Discard Changes?"), i18n("&Discard Changes"), "discardchangesloadprofile") != KMessageBox::Continue ) - return; - } - } - - bool alwaysTabbedMode = KonqSettings::alwaysTabbedMode(); - - m_currentProfile = filename; - m_currentProfileText = cfg.readPathEntry("Name",filename); - m_profileHomeURL = cfg.readEntry("HomeURL", TQString::null); - - m_pMainWindow->currentProfileChanged(); - KURL defaultURL; - if ( m_pMainWindow->currentView() ) - defaultURL = m_pMainWindow->currentView()->url(); - - clear(); - - TQString rootItem = cfg.readEntry( "RootItem", "empty" ); - - //kdDebug(1202) << "KonqViewManager::loadViewProfile : loading RootItem " << rootItem << - //" forcedURL " << forcedURL.url() << endl; - - if ( forcedURL.url() != "about:blank" ) - { - // This flag is used by KonqView, to distinguish manual view creation - // from profile loading (e.g. in switchView) - m_bLoadingProfile = true; - - loadItem( cfg, m_pMainWindow, rootItem, defaultURL, openURL && forcedURL.isEmpty() ); - - m_bLoadingProfile = false; - - m_pMainWindow->enableAllActions(true); - - // This flag disables calls to viewCountChanged while creating the views, - // so we do it once at the end : - m_pMainWindow->viewCountChanged(); - } - else - { - m_pMainWindow->disableActionsNoView(); - m_pMainWindow->action( "clear_location" )->activate(); - } - - //kdDebug(1202) << "KonqViewManager::loadViewProfile : after loadItem " << endl; - - if (m_pDocContainer == 0L) - { - if (m_pMainWindow && - m_pMainWindow->currentView() && - m_pMainWindow->currentView()->frame()) { - m_pDocContainer = m_pMainWindow->currentView()->frame(); - } else { - kdDebug(1202) << "This view profile does not support tabs." << endl; - return; - } - } - - - if ( m_pDocContainer->frameType() != "Tabs") - convertDocContainer(); - - static_cast( m_pDocContainer )->setAlwaysTabbedMode( alwaysTabbedMode ); - static_cast( m_pDocContainer )->setMouseWheelScroll(KonqSettings::tabsCycleWheel()); - - // Set an active part first so that we open the URL in the current view - // (to set the location bar correctly and asap) - KonqView *nextChildView = 0L; - nextChildView = m_pMainWindow->activeChildView(); - if (nextChildView == 0L) nextChildView = chooseNextView( 0L ); - setActivePart( nextChildView ? nextChildView->part() : 0L, true /* immediate */); - - // #71164 - if ( !req.args.frameName.isEmpty() && nextChildView ) { - nextChildView->setViewName( req.args.frameName ); - } - - if ( openURL && !forcedURL.isEmpty()) - { - KonqOpenURLRequest _req(req); - _req.openAfterCurrentPage = KonqSettings::openAfterCurrentPage(); - _req.forceAutoEmbed = true; // it's a new window, let's use it - - m_pMainWindow->openURL( nextChildView /* can be 0 for an empty profile */, - forcedURL, _req.args.serviceType, _req, _req.args.trustedSource ); - - // TODO choose a linked view if any (instead of just the first one), - // then open the same URL in any non-linked one - } - else - { - if ( m_pMainWindow->locationBarURL().isEmpty() ) // No URL -> the user will want to type one - m_pMainWindow->focusLocationBar(); - } - - // Window size - if ( !m_pMainWindow->initialGeometrySet() ) - { - if (cfg.readBoolEntry( "FullScreen" )) - { - // Full screen on - m_pMainWindow->showFullScreen(); - } - else - { - // Full screen off - if( m_pMainWindow->isFullScreen()) - m_pMainWindow->showNormal(); - - TQSize size = readConfigSize( cfg, m_pMainWindow ); - if ( size.isValid() ) - m_pMainWindow->resize( size ); - else // no size in the profile; use last known size - m_pMainWindow->restoreWindowSize(); - } - } - - if( resetWindow ) - { // force default settings for the GUI - m_pMainWindow->applyMainWindowSettings( TDEGlobal::config(), "KonqMainWindow", true ); - } - - // Apply menu/toolbar settings saved in profile. Read from a separate group - // so that the window doesn't try to change the size stored in the Profile group. - // (If applyMainWindowSettings finds a "Width" or "Height" entry, it - // sets them to 0,0) - TQString savedGroup = cfg.group(); - m_pMainWindow->applyMainWindowSettings( &cfg, "Main Window Settings" ); - cfg.setGroup( savedGroup ); - -#ifdef DEBUG_VIEWMGR - printFullHierarchy( m_pMainWindow ); -#endif - - //kdDebug(1202) << "KonqViewManager::loadViewProfile done" << endl; -} - -void KonqViewManager::setActivePart( KParts::Part *part, TQWidget * ) -{ - setActivePart( part, false ); -} - -void KonqViewManager::setActivePart( KParts::Part *part, bool immediate ) -{ - //kdDebug(1202) << "KonqViewManager::setActivePart " << part << endl; - //if ( part ) - // kdDebug(1202) << " " << part->className() << " " << part->name() << endl; - - // Due to the single-shot timer below, we need to also make sure that - // the mainwindow also has the right part active already - KParts::Part* mainWindowActivePart = (m_pMainWindow && m_pMainWindow->currentView()) - ? m_pMainWindow->currentView()->part() : 0; - if (part == activePart() && (!immediate || mainWindowActivePart == part)) - { - if ( part ) - kdDebug(1202) << "Part is already active!" << endl; - return; - } - - // Don't activate when part changed in non-active tab - KonqView* partView = m_pMainWindow->childView((KParts::ReadOnlyPart*)part); - if (partView) - { - KonqFrameContainerBase* parentContainer = partView->frame()->parentContainer(); - if (parentContainer->frameType()=="Tabs") - { - KonqFrameTabs* parentFrameTabs = static_cast(parentContainer); - if (partView->frame() != parentFrameTabs->currentPage()) - return; - } - } - - if (m_pMainWindow && m_pMainWindow->currentView()) - m_pMainWindow->currentView()->setLocationBarURL(m_pMainWindow->locationBarURL()); - - KParts::PartManager::setActivePart( part ); - - if (part && part->widget()) - part->widget()->setFocus(); - - if (!immediate && reason() != ReasonRightClick) { - // We use a 0s single shot timer so that when left-clicking on a part, - // we process the mouse event before rebuilding the GUI. - // Otherwise, when e.g. dragging icons, the mouse pointer can already - // be very far from where it was... - m_activePartChangedTimer->start( 0, true ); - // This is not done with right-clicking so that the part is activated before the - // popup appears (#75201) - } else { - emitActivePartChanged(); - } -} - -void KonqViewManager::slotActivePartChanged ( KParts::Part *newPart ) -{ - //kdDebug(1202) << "KonqViewManager::slotActivePartChanged " << newPart << endl; - if (newPart == 0L) { - //kdDebug(1202) << "newPart = 0L , returning" << endl; - return; - } - KonqView * view = m_pMainWindow->childView( static_cast(newPart) ); - if (view == 0L) { - kdDebug(1202) << k_funcinfo << "No view associated with this part" << endl; - return; - } - if (view->frame()->parentContainer() == 0L) return; - if (!m_bLoadingProfile) { - view->frame()->statusbar()->updateActiveStatus(); - view->frame()->parentContainer()->setActiveChild( view->frame() ); - } - //kdDebug(1202) << "KonqViewManager::slotActivePartChanged done" << endl; -} - -void KonqViewManager::emitActivePartChanged() -{ - // prevent unnecessary multiple calls to slotPartActivated: - m_activePartChangedTimer->stop(); - m_pMainWindow->slotPartActivated( activePart() ); -} - - -TQSize KonqViewManager::readConfigSize( TDEConfig &cfg, TQWidget *widget ) -{ - bool ok; - - TQString widthStr = cfg.readEntry( "Width" ); - TQString heightStr = cfg.readEntry( "Height" ); - - int width = -1; - int height = -1; - - TQRect geom = TDEGlobalSettings::desktopGeometry(widget); - - if ( widthStr.contains( '%' ) == 1 ) - { - widthStr.truncate( widthStr.length() - 1 ); - int relativeWidth = widthStr.toInt( &ok ); - if ( ok ) { - width = relativeWidth * geom.width() / 100; - } - } - else - { - width = widthStr.toInt( &ok ); - if ( !ok ) - width = -1; - } - - if ( heightStr.contains( '%' ) == 1 ) - { - heightStr.truncate( heightStr.length() - 1 ); - int relativeHeight = heightStr.toInt( &ok ); - if ( ok ) { - height = relativeHeight * geom.height() / 100; - } - } - else - { - height = heightStr.toInt( &ok ); - if ( !ok ) - height = -1; - } - - return TQSize( width, height ); -} - -void KonqViewManager::loadItem( TDEConfig &cfg, KonqFrameContainerBase *parent, - const TQString &name, const KURL & defaultURL, bool openURL, bool openAfterCurrentPage ) -{ - TQString prefix; - if( name != "InitialView" ) - prefix = name + '_'; - - //kdDebug(1202) << "KonqViewManager::loadItem: begin name " << name << " openURL " << openURL << endl; - - if( name.startsWith("View") || name == "empty" ) { - //load view config - TQString serviceType; - TQString serviceName; - if ( name == "empty" ) { - // An empty profile is an empty TDEHTML part. Makes all TDEHTML actions available, avoids crashes, - // makes it easy to DND a URL onto it, and makes it fast to load a website from there. - serviceType = "text/html"; - serviceName = "html"; - } else { - serviceType = cfg.readEntry( TQString::fromLatin1( "ServiceType" ).prepend( prefix ), "inode/directory"); - serviceName = cfg.readEntry( TQString::fromLatin1( "ServiceName" ).prepend( prefix ) ); - } - //kdDebug(1202) << "KonqViewManager::loadItem: ServiceType " << serviceType << " " << serviceName << endl; - - KService::Ptr service; - TDETrader::OfferList partServiceOffers, appServiceOffers; - - KonqViewFactory viewFactory = KonqFactory::createView( serviceType, serviceName, &service, &partServiceOffers, &appServiceOffers, true /*forceAutoEmbed*/ ); - if ( viewFactory.isNull() ) - { - kdWarning(1202) << "Profile Loading Error: View creation failed" << endl; - return; //ugh.. - } - - bool passiveMode = cfg.readBoolEntry( TQString::fromLatin1( "PassiveMode" ).prepend( prefix ), false ); - - //kdDebug(1202) << "KonqViewManager::loadItem: Creating View Stuff" << endl; - KonqView *childView = setupView( parent, viewFactory, service, partServiceOffers, appServiceOffers, serviceType, passiveMode, openAfterCurrentPage ); - - if (!childView->isFollowActive()) childView->setLinkedView( cfg.readBoolEntry( TQString::fromLatin1( "LinkedView" ).prepend( prefix ), false ) ); - childView->setToggleView( cfg.readBoolEntry( TQString::fromLatin1( "ToggleView" ).prepend( prefix ), false ) ); - if( !cfg.readBoolEntry( TQString::fromLatin1( "ShowStatusBar" ).prepend( prefix ), true ) ) - childView->frame()->statusbar()->hide(); - - if (cfg.readBoolEntry( TQString::fromLatin1( "docContainer" ).prepend( prefix ), false )) - m_pDocContainer = childView->frame(); - - if (!m_pDocContainer) - { - if (parent->frameType() == "MainWindow") - m_pDocContainer = childView->frame(); // Child view of mainWindow - - else if (parent->frameType() == "Container") - { - KonqFrameContainer* parentContainer = static_cast(parent); - KonqFrameBase* otherFrame = parentContainer->otherChild( childView->frame() ); - if (otherFrame) - { - if (childView->isPassiveMode()) - { - if (otherFrame->frameType() == "View") - { - KonqFrame* viewFrame = static_cast(otherFrame); - if (viewFrame->childView()->isPassiveMode()) - m_pDocContainer = parentContainer; // Both views are passive, shouldn't happen - else - m_pDocContainer = viewFrame; // This one is passive, the other is active - } - } - else - { - if (otherFrame->frameType() == "View") - { - KonqFrame* viewFrame = static_cast(otherFrame); - if (viewFrame->childView()->isPassiveMode()) - m_pDocContainer = childView->frame(); // This one is active, the other is passive - else - m_pDocContainer = parentContainer; // Both views are active - } - else - m_pDocContainer = parentContainer; // This one is active, the other is a Container - } - } - } - } - KonqConfigEvent ev( &cfg, prefix+"_", false/*load*/); - TQApplication::sendEvent( childView->part(), &ev ); - - childView->frame()->show(); - - TQString key = TQString::fromLatin1( "URL" ).prepend( prefix ); - if ( openURL ) - { - KURL url; - - //kdDebug(1202) << "KonqViewManager::loadItem: key " << key << endl; - if ( cfg.hasKey( key ) ) - { - TQString u = cfg.readPathEntry( key ); - if ( u.isEmpty() ) - u = TQString::fromLatin1("about:blank"); - url = u; - } - else if(key == "empty_URL") - url = TQString::fromLatin1("about:blank"); - else - url = defaultURL; - - if ( !url.isEmpty() ) - { - //kdDebug(1202) << "KonqViewManager::loadItem: calling openURL " << url.prettyURL() << endl; - //childView->openURL( url, url.prettyURL() ); - // We need view-follows-view (for the dirtree, for instance) - KonqOpenURLRequest req; - if (url.protocol() != "about") - req.typedURL = url.prettyURL(); - m_pMainWindow->openView( serviceType, url, childView, req ); - } - //else kdDebug(1202) << "KonqViewManager::loadItem: url is empty" << endl; - } - // Do this after opening the URL, so that it's actually possible to open it :) - childView->setLockedLocation( cfg.readBoolEntry( TQString::fromLatin1( "LockedLocation" ).prepend( prefix ), false ) ); - } - else if( name.startsWith("Container") ) { - //kdDebug(1202) << "KonqViewManager::loadItem Item is Container" << endl; - - //load container config - TQString ostr = cfg.readEntry( TQString::fromLatin1( "Orientation" ).prepend( prefix ) ); - //kdDebug(1202) << "Orientation: " << ostr << endl; - Qt::Orientation o; - if( ostr == "Vertical" ) - o = Qt::Vertical; - else if( ostr == "Horizontal" ) - o = Qt::Horizontal; - else { - kdWarning() << "Profile Loading Error: No orientation specified in " << name << endl; - o = Qt::Horizontal; - } - - TQValueList sizes = - cfg.readIntListEntry( TQString::fromLatin1( "SplitterSizes" ).prepend( prefix )); - - int index = cfg.readNumEntry( TQString::fromLatin1( "activeChildIndex" ).prepend(prefix), -1 ); - - TQStrList childList; - if( cfg.readListEntry( TQString::fromLatin1( "Children" ).prepend( prefix ), childList ) < 2 ) - { - kdWarning() << "Profile Loading Error: Less than two children in " << name << endl; - // fallback to defaults - loadItem( cfg, parent, "InitialView", defaultURL, openURL ); - } - else - { - KonqFrameContainer *newContainer = new KonqFrameContainer( o, parent->widget(), parent ); - connect(newContainer,TQT_SIGNAL(ctrlTabPressed()),m_pMainWindow,TQT_SLOT(slotCtrlTabPressed())); - - int tabindex = -1; - if(openAfterCurrentPage && parent->frameType() == "Tabs") // Need to honor it, if possible - tabindex = static_cast(parent)->currentPageIndex() + 1; - parent->insertChildFrame( newContainer, tabindex ); - - - if (cfg.readBoolEntry( TQString::fromLatin1( "docContainer" ).prepend( prefix ), false )) - m_pDocContainer = newContainer; - - loadItem( cfg, newContainer, childList.at(0), defaultURL, openURL ); - loadItem( cfg, newContainer, childList.at(1), defaultURL, openURL ); - - newContainer->setSizes( sizes ); - - if (index == 1) - newContainer->setActiveChild( newContainer->secondChild() ); - else if (index == 0) - newContainer->setActiveChild( newContainer->firstChild() ); - - newContainer->show(); - } - } - else if( name.startsWith("Tabs") ) - { - //kdDebug(1202) << "KonqViewManager::loadItem: Item is a Tabs" << endl; - - KonqFrameTabs *newContainer = new KonqFrameTabs( parent->widget(), parent, this ); - connect(newContainer,TQT_SIGNAL(ctrlTabPressed()),m_pMainWindow,TQT_SLOT(slotCtrlTabPressed())); - - parent->insertChildFrame( newContainer ); - m_pDocContainer = newContainer; - - int index = cfg.readNumEntry( TQString::fromLatin1( "activeChildIndex" ).prepend(prefix), 0 ); - - TQStringList childList = cfg.readListEntry( TQString::fromLatin1( "Children" ).prepend( prefix ) ); - for ( TQStringList::Iterator it = childList.begin(); it != childList.end(); ++it ) - { - loadItem( cfg, newContainer, *it, defaultURL, openURL ); - TQWidget* currentPage = newContainer->currentPage(); - if (currentPage != 0L) { - KonqView* activeChildView = tqt_dynamic_cast(currentPage)->activeChildView(); - if (activeChildView != 0L) { - activeChildView->setCaption( activeChildView->caption() ); - activeChildView->setTabIcon( activeChildView->url() ); - } - } - } - - newContainer->setActiveChild( tqt_dynamic_cast(newContainer->page(index)) ); - newContainer->setCurrentPage( index ); - - newContainer->show(); - } - else - kdWarning() << "Profile Loading Error: Unknown item " << name; - - //kdDebug(1202) << "KonqViewManager::loadItem: end" << name << endl; -} - -void KonqViewManager::setProfiles( TDEActionMenu *profiles ) -{ - m_pamProfiles = profiles; - - if ( m_pamProfiles ) - { - connect( m_pamProfiles->popupMenu(), TQT_SIGNAL( activated( int ) ), - this, TQT_SLOT( slotProfileActivated( int ) ) ); - connect( m_pamProfiles->popupMenu(), TQT_SIGNAL( aboutToShow() ), - this, TQT_SLOT( slotProfileListAboutToShow() ) ); - } - //KonqMainWindow::enableAllActions will call it anyway - //profileListDirty(); -} - -void KonqViewManager::showProfileDlg( const TQString & preselectProfile ) -{ - KonqProfileDlg dlg( this, preselectProfile, m_pMainWindow ); - dlg.exec(); - profileListDirty(); -} - -void KonqViewManager::slotProfileDlg() -{ - showProfileDlg( TQString::null ); -} - -void KonqViewManager::profileListDirty( bool broadcast ) -{ - //kdDebug(1202) << "KonqViewManager::profileListDirty()" << endl; - if ( !broadcast ) - { - m_bProfileListDirty = true; - - // #if 0 causes problems with TDevelop syntax highlighting. Converted to comments - // #if 0 - // There's always one profile at least, now... - //TQStringList profiles = KonqFactory::instance()->dirs()->findAllResources( "data", "konqueror/profiles/*", false, true ); - //if ( m_pamProfiles ) - // m_pamProfiles->setEnabled( profiles.count() > 0 ); - // #endif - return; - } - - kapp->dcopClient()->send( "konqueror*", "KonquerorIface", "updateProfileList()", TQByteArray() ); -} - -void KonqViewManager::slotProfileActivated( int id ) -{ - - TQMap::ConstIterator iter = m_mapProfileNames.begin(); - TQMap::ConstIterator end = m_mapProfileNames.end(); - - for(int i=0; iter != end; ++iter, ++i) { - if( i == id ) { - KURL u; - u.setPath( *iter ); - loadViewProfile( *iter, u.fileName() ); - break; - } - } -} - -void KonqViewManager::slotProfileListAboutToShow() -{ - if ( !m_pamProfiles || !m_bProfileListDirty ) - return; - - TQPopupMenu *popup = m_pamProfiles->popupMenu(); - popup->clear(); - - // Fetch profiles - m_mapProfileNames = KonqProfileDlg::readAllProfiles(); - - // Generate accelerators - TQStringList accel_strings; - TDEAccelGen::generateFromKeys(m_mapProfileNames, accel_strings); - - // Store menu items - TQValueListIterator iter = accel_strings.begin(); - for( int id = 0; - iter != accel_strings.end(); - ++iter, ++id ) { - popup->insertItem( *iter, id ); - } - - m_bProfileListDirty = false; -} - -void KonqViewManager::setLoading( KonqView *view, bool loading ) -{ - KonqFrameContainerBase* parentContainer = view->frame()->parentContainer(); - if ( parentContainer->frameType() == "Tabs" ) { - TQColor color; - KonqFrameTabs* konqframetabs = static_cast( parentContainer ); - if ( loading ) - color = TQColor( (TDEGlobalSettings::linkColor().red() + TDEGlobalSettings::inactiveTextColor().red())/2, - (TDEGlobalSettings::linkColor().green()+ TDEGlobalSettings::inactiveTextColor().green())/2, - (TDEGlobalSettings::linkColor().blue() + TDEGlobalSettings::inactiveTextColor().blue())/2 ); - else - { - if ( konqframetabs->currentPage() != view->frame() ) - color = TDEGlobalSettings::linkColor(); - else - color = TDEGlobalSettings::textColor(); - } - konqframetabs->setTabColor( view->frame(), color ); - } -} - -void KonqViewManager::showHTML(bool b) -{ - if (m_pDocContainer == 0L) return; - if (m_pDocContainer->frameType() != "Tabs") return; - - KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); - - TQPtrList frameList = *tabContainer->childFrameList(); - TQPtrListIterator it( frameList ); - - for ( it.toFirst(); it != 0L; ++it ) - { - if ( it.current()->activeChildView() && it.current()->activeChildView() !=m_pMainWindow->currentView()) - { - it.current()->activeChildView()->setAllowHTML( b ); - if( !it.current()->activeChildView()->locationBarURL().isEmpty()) - { - - m_pMainWindow->showHTML( it.current()->activeChildView(), b, false ); - } - } - } -} - -void KonqViewManager::reparseConfiguration() -{ - KonqFrameTabs *frameTabs=static_cast(m_pDocContainer); - if (frameTabs) - { - frameTabs->setAlwaysTabbedMode(KonqSettings::alwaysTabbedMode()); - frameTabs->setMouseWheelScroll(KonqSettings::tabsCycleWheel()); - } -} - - - -///////////////// Debug stuff //////////////// - -#ifndef NDEBUG -void KonqViewManager::printSizeInfo( KonqFrameBase* frame, - KonqFrameContainerBase* parent, - const char* msg ) -{ - TQRect r; - r = frame->widget()->geometry(); - tqDebug("Child size %s : x: %d, y: %d, w: %d, h: %d", msg, r.x(),r.y(),r.width(),r.height() ); - - if ( parent->frameType() == "Container" ) - { - TQValueList sizes; - sizes = static_cast(parent)->sizes(); - printf( "Parent sizes %s :", msg ); - TQValueList::ConstIterator it; - for( it = sizes.begin(); it != sizes.end(); ++it ) - printf( " %d", (*it) ); - printf("\n"); - } -} - -void KonqViewManager::printFullHierarchy( KonqFrameContainerBase * container ) -{ - kdDebug(1202) << "currentView=" << m_pMainWindow->currentView() << endl; - kdDebug(1202) << "docContainer=" << m_pDocContainer << endl; - - if (container) container->printFrameInfo(TQString::null); - else m_pMainWindow->printFrameInfo(TQString::null); -} -#endif - -#include "konq_viewmgr.moc" diff --git a/konqueror/konq_viewmgr.cpp b/konqueror/konq_viewmgr.cpp new file mode 100644 index 000000000..495d267e8 --- /dev/null +++ b/konqueror/konq_viewmgr.cpp @@ -0,0 +1,1842 @@ +/* This file is part of the KDE project + Copyright (C) 1999 Simon Hausmann + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +*/ + +#include "konq_viewmgr.h" +#include "konq_view.h" +#include "konq_frame.h" +#include "konq_tabs.h" +#include "konq_profiledlg.h" +#include "konq_events.h" +#include "konq_settingsxt.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +// #define DEBUG_VIEWMGR + +template class TQPtrList; + +KonqViewManager::KonqViewManager( KonqMainWindow *mainWindow ) + : KParts::PartManager( mainWindow ) +{ + m_pMainWindow = mainWindow; + m_pDocContainer = 0L; + + m_pamProfiles = 0L; + m_bProfileListDirty = true; + m_bLoadingProfile = false; + + m_activePartChangedTimer = new TQTimer(this); + connect(m_activePartChangedTimer, TQT_SIGNAL(timeout()), this, TQT_SLOT(emitActivePartChanged())); + connect( this, TQT_SIGNAL( activePartChanged ( KParts::Part * ) ), this, TQT_SLOT( slotActivePartChanged ( KParts::Part * ) ) ); +} + +KonqView* KonqViewManager::Initialize( const TQString &serviceType, const TQString &serviceName ) +{ + //kdDebug(1202) << "KonqViewManager::Initialize()" << endl; + KService::Ptr service; + TDETrader::OfferList partServiceOffers, appServiceOffers; + KonqViewFactory newViewFactory = createView( serviceType, serviceName, service, partServiceOffers, appServiceOffers, true /*forceAutoEmbed*/ ); + if ( newViewFactory.isNull() ) + { + kdDebug(1202) << "KonqViewManager::Initialize() No suitable factory found." << endl; + return 0; + } + + KonqView* childView = setupView( m_pMainWindow, newViewFactory, service, partServiceOffers, appServiceOffers, serviceType, false ); + + setActivePart( childView->part() ); + m_pDocContainer = childView->frame(); + + convertDocContainer(); + static_cast( m_pDocContainer )->setAlwaysTabbedMode(KonqSettings::alwaysTabbedMode()); + static_cast( m_pDocContainer )->setMouseWheelScroll(KonqSettings::tabsCycleWheel()); + + m_pDocContainer->widget()->show(); + return childView; +} + +KonqViewManager::~KonqViewManager() +{ + //kdDebug(1202) << "KonqViewManager::~KonqViewManager()" << endl; + clear(); +} + +KonqView* KonqViewManager::splitView ( Qt::Orientation orientation, + const TQString &serviceType, + const TQString &serviceName, + bool newOneFirst, bool forceAutoEmbed ) +{ +#ifdef DEBUG_VIEWMGR + kdDebug(1202) << "KonqViewManager::splitView(ServiceType)" << endl; + m_pMainWindow->dumpViewList(); + printFullHierarchy( m_pMainWindow ); +#endif + + KonqFrame* splitFrame = m_pMainWindow->currentView()->frame(); + + KService::Ptr service; + TDETrader::OfferList partServiceOffers, appServiceOffers; + + KonqViewFactory newViewFactory = createView( serviceType, serviceName, service, partServiceOffers, appServiceOffers, forceAutoEmbed ); + + if( newViewFactory.isNull() ) + return 0L; //do not split at all if we can't create the new view + + assert( splitFrame ); + + KonqFrameContainerBase* parentContainer = splitFrame->parentContainer(); + + bool moveNewContainer = false; + TQValueList splitterSizes; + int index= -1; + + if (parentContainer->frameType()=="Container") { + moveNewContainer = (static_cast(parentContainer)->idAfter( splitFrame->widget() ) != 0); + splitterSizes = static_cast(parentContainer)->sizes(); + } + else if (parentContainer->frameType()=="Tabs") + index = static_cast(parentContainer)->indexOf( splitFrame->widget() ); + +#ifndef NDEBUG + //printSizeInfo( splitFrame, parentContainer, "before split"); +#endif + + parentContainer->widget()->setUpdatesEnabled( false ); + + //kdDebug(1202) << "Move out child" << endl; + TQPoint pos = splitFrame->widget()->pos(); + parentContainer->removeChildFrame( splitFrame ); + splitFrame->widget()->reparent( m_pMainWindow, pos ); + + //kdDebug(1202) << "Create new Container" << endl; + KonqFrameContainer *newContainer = new KonqFrameContainer( orientation, parentContainer->widget(), parentContainer ); + connect(newContainer,TQT_SIGNAL(ctrlTabPressed()),m_pMainWindow,TQT_SLOT(slotCtrlTabPressed())); + + parentContainer->insertChildFrame( newContainer, index ); + if ( moveNewContainer ) { + static_cast(parentContainer)->moveToFirst( newContainer ); + static_cast(parentContainer)->swapChildren(); + } + + //kdDebug(1202) << "Move in child" << endl; + splitFrame->widget()->reparent( newContainer, pos ); + newContainer->insertChildFrame( splitFrame ); + +#ifndef NDEBUG + //printSizeInfo( splitFrame, parentContainer, "after reparent" ); +#endif + + //kdDebug(1202) << "Create new child" << endl; + KonqView *newView = setupView( newContainer, newViewFactory, service, partServiceOffers, appServiceOffers, serviceType, false ); + +#ifndef DEBUG + //printSizeInfo( splitFrame, parentContainer, "after child insert" ); +#endif + + if ( newOneFirst ) + { + newContainer->moveToLast( splitFrame->widget() ); + newContainer->swapChildren(); + } + + TQValueList newSplitterSizes; + newSplitterSizes << 50 << 50; + newContainer->setSizes( newSplitterSizes ); + + if (parentContainer->frameType()=="Container") { + static_cast(parentContainer)->setSizes( splitterSizes ); + } + else if (parentContainer->frameType()=="Tabs") + static_cast(parentContainer)->showPage( newContainer ); + + splitFrame->show(); + //newView->frame()->show(); + newContainer->show(); + + parentContainer->widget()->setUpdatesEnabled( true ); + + if (m_pDocContainer == splitFrame) m_pDocContainer = newContainer; + + assert( newView->frame() ); + assert( newView->part() ); + newContainer->setActiveChild( newView->frame() ); + setActivePart( newView->part(), false ); + +#ifdef DEBUG_VIEWMGR + m_pMainWindow->dumpViewList(); + printFullHierarchy( m_pMainWindow ); + kdDebug(1202) << "KonqViewManager::splitView(ServiceType) done" << endl; +#endif + + return newView; +} + +KonqView* KonqViewManager::splitWindow( Qt::Orientation orientation, + const TQString &serviceType, + const TQString &serviceName, + bool newOneFirst ) +{ + kdDebug(1202) << "KonqViewManager::splitWindow(default)" << endl; + + // Don't crash when doing things too quickly. + if (!m_pMainWindow || !m_pMainWindow->currentView()) + return 0L; + + KURL url = m_pMainWindow->currentView()->url(); + TQString locationBarURL = m_pMainWindow->currentView()->locationBarURL(); + + KService::Ptr service; + TDETrader::OfferList partServiceOffers, appServiceOffers; + + KonqViewFactory newViewFactory = createView( serviceType, serviceName, service, partServiceOffers, appServiceOffers ); + + if( newViewFactory.isNull() ) + return 0L; //do not split at all if we can't create the new view + + KonqFrameBase* mainFrame = m_pMainWindow->childFrame(); + + mainFrame->widget()->setUpdatesEnabled( false ); + + //kdDebug(1202) << "Move out child" << endl; + TQPoint pos = mainFrame->widget()->pos(); + m_pMainWindow->removeChildFrame( mainFrame ); + + KonqFrameContainer *newContainer = new KonqFrameContainer( orientation, m_pMainWindow, 0L); + connect(newContainer,TQT_SIGNAL(ctrlTabPressed()),m_pMainWindow,TQT_SLOT(slotCtrlTabPressed())); + + m_pMainWindow->insertChildFrame( newContainer ); + + newContainer->insertChildFrame( mainFrame ); + mainFrame->widget()->reparent( newContainer, pos ); + + KonqView* childView = setupView( newContainer, newViewFactory, service, partServiceOffers, appServiceOffers, serviceType, true ); + + if( newOneFirst ) { + static_cast(newContainer)->moveToFirst( childView->frame() ); + static_cast(newContainer)->swapChildren(); + } + + newContainer->show(); + + mainFrame->widget()->setUpdatesEnabled( true ); + + if( childView ) + childView->openURL( url, locationBarURL ); + + newContainer->setActiveChild( mainFrame ); + +#ifdef DEBUG_VIEWMGR + m_pMainWindow->dumpViewList(); + printFullHierarchy( m_pMainWindow ); + kdDebug(1202) << "KonqViewManager::splitWindow(default) done" << endl; +#endif + + return childView; +} + +void KonqViewManager::convertDocContainer() +{ + // Must create a tab container since one is not present, + // then insert the existing frame as a tab + + KonqFrameContainerBase* parentContainer = m_pDocContainer->parentContainer(); + + bool moveNewContainer = false; + TQValueList splitterSizes; + if (parentContainer->frameType()=="Container") { + moveNewContainer = (static_cast(parentContainer)->idAfter( m_pDocContainer->widget() ) != 0); + splitterSizes = static_cast(parentContainer)->sizes(); + } + + parentContainer->widget()->setUpdatesEnabled( false ); + + //kdDebug(1202) << "Move out child" << endl; + TQPoint pos = m_pDocContainer->widget()->pos(); + parentContainer->removeChildFrame( m_pDocContainer ); + m_pDocContainer->widget()->reparent( m_pMainWindow, pos ); + + KonqFrameTabs* newContainer = new KonqFrameTabs( parentContainer->widget() , parentContainer, this); + parentContainer->insertChildFrame( newContainer ); + connect( newContainer, TQT_SIGNAL(ctrlTabPressed()), m_pMainWindow, TQT_SLOT(slotCtrlTabPressed()) ); + + m_pDocContainer->widget()->reparent( newContainer, pos ); + newContainer->insertChildFrame( m_pDocContainer ); + + if ( moveNewContainer ) { + static_cast(parentContainer)->moveToFirst( newContainer ); + static_cast(parentContainer)->swapChildren(); + } + if (parentContainer->frameType()=="Container") + static_cast(parentContainer)->setSizes( splitterSizes ); + + newContainer->show(); + + parentContainer->widget()->setUpdatesEnabled( true ); + + m_pDocContainer = newContainer; +} + +KonqView* KonqViewManager::addTab(const TQString &serviceType, const TQString &serviceName, bool passiveMode, bool openAfterCurrentPage ) +{ +#ifdef DEBUG_VIEWMGR + kdDebug(1202) << "------------- KonqViewManager::addTab starting -------------" << endl; + m_pMainWindow->dumpViewList(); + printFullHierarchy( m_pMainWindow ); +#endif + + if (m_pDocContainer == 0L) + { + if (m_pMainWindow && + m_pMainWindow->currentView() && + m_pMainWindow->currentView()->frame()) { + m_pDocContainer = m_pMainWindow->currentView()->frame(); + } else { + kdDebug(1202) << "This view profile does not support tabs." << endl; + return 0L; + } + } + + KService::Ptr service; + TDETrader::OfferList partServiceOffers, appServiceOffers; + + KonqViewFactory newViewFactory = createView( serviceType, serviceName, service, partServiceOffers, appServiceOffers, true /*forceAutoEmbed*/ ); + + if( newViewFactory.isNull() ) + return 0L; //do not split at all if we can't create the new view + + if (m_pDocContainer->frameType() != "Tabs") convertDocContainer(); + + KonqView* childView = setupView( static_cast(m_pDocContainer), newViewFactory, service, partServiceOffers, appServiceOffers, serviceType, passiveMode, openAfterCurrentPage ); + +#ifdef DEBUG_VIEWMGR + m_pMainWindow->dumpViewList(); + printFullHierarchy( m_pMainWindow ); + kdDebug(1202) << "------------- KonqViewManager::addTab done -------------" << endl; +#endif + + return childView; +} + +KonqView* KonqViewManager::addTabFromHistory( int steps, bool openAfterCurrentPage ) +{ + if (m_pDocContainer == 0L) + { + if (m_pMainWindow && + m_pMainWindow->currentView() && + m_pMainWindow->currentView()->frame()) { + m_pDocContainer = m_pMainWindow->currentView()->frame(); + } else { + kdDebug(1202) << "This view profile does not support tabs." << endl; + return 0L; + } + } + if (m_pDocContainer->frameType() != "Tabs") convertDocContainer(); + + int oldPos = m_pMainWindow->currentView()->historyPos(); + int newPos = oldPos + steps; + + const HistoryEntry * he = m_pMainWindow->currentView()->historyAt(newPos); + if(!he) + return 0L; + + KonqView* newView = 0L; + newView = addTab( he->strServiceType, he->strServiceName, false, openAfterCurrentPage ); + + if(!newView) + return 0L; + + newView->copyHistory(m_pMainWindow->currentView()); + newView->setHistoryPos(newPos); + newView->restoreHistory(); + + return newView; +} + + +void KonqViewManager::duplicateTab( KonqFrameBase* tab, bool openAfterCurrentPage ) +{ +#ifdef DEBUG_VIEWMGR + kdDebug(1202) << "---------------- KonqViewManager::duplicateTab( " << tab << " ) --------------" << endl; + m_pMainWindow->dumpViewList(); + printFullHierarchy( m_pMainWindow ); +#endif + + if (m_pDocContainer == 0L) + { + if (m_pMainWindow && + m_pMainWindow->currentView() && + m_pMainWindow->currentView()->frame()) { + m_pDocContainer = m_pMainWindow->currentView()->frame(); + } else { + kdDebug(1202) << "This view profile does not support tabs." << endl; + return; + } + } + + if (m_pDocContainer->frameType() != "Tabs") convertDocContainer(); + + KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); + + KonqFrameBase* currentFrame; + if ( tab == 0L ) + currentFrame = tqt_dynamic_cast(tabContainer->currentPage()); + else + currentFrame = tab; + + if (!currentFrame) { + return; + } + + KTempFile tempFile; + tempFile.setAutoDelete( true ); + TDEConfig config( tempFile.name() ); + config.setGroup( "View Profile" ); + + TQString prefix = TQString::fromLatin1( currentFrame->frameType() ) + TQString::number(0); + config.writeEntry( "RootItem", prefix ); + prefix.append( '_' ); + currentFrame->saveConfig( &config, prefix, true, 0L, 0, 1); + + TQString rootItem = config.readEntry( "RootItem", "empty" ); + + if (rootItem.isNull() || rootItem == "empty") return; + + // This flag is used by KonqView, to distinguish manual view creation + // from profile loading (e.g. in switchView) + m_bLoadingProfile = true; + + loadItem( config, tabContainer, rootItem, KURL(""), true, openAfterCurrentPage ); + + m_bLoadingProfile = false; + + m_pMainWindow->enableAllActions(true); + + // This flag disables calls to viewCountChanged while creating the views, + // so we do it once at the end : + m_pMainWindow->viewCountChanged(); + + if (openAfterCurrentPage) + tabContainer->setCurrentPage( tabContainer->currentPageIndex () + 1 ); + else + tabContainer->setCurrentPage( tabContainer->count() - 1 ); + + KonqFrameBase* duplicatedFrame = tqt_dynamic_cast(tabContainer->currentPage()); + if (duplicatedFrame) + duplicatedFrame->copyHistory( currentFrame ); + +#ifdef DEBUG_VIEWMGR + m_pMainWindow->dumpViewList(); + printFullHierarchy( m_pMainWindow ); + kdDebug(1202) << "------------- KonqViewManager::duplicateTab done --------------" << endl; +#endif +} + +void KonqViewManager::breakOffTab( KonqFrameBase* tab ) +{ +#ifdef DEBUG_VIEWMGR + kdDebug(1202) << "---------------- KonqViewManager::breakOffTab( " << tab << " ) --------------" << endl; + m_pMainWindow->dumpViewList(); + printFullHierarchy( m_pMainWindow ); +#endif + + if (m_pDocContainer == 0L) return; + if (m_pDocContainer->frameType() != "Tabs") return; + + KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); + + int width = m_pMainWindow->width(); + int height = m_pMainWindow->height(); + + KonqFrameBase* currentFrame; + if ( tab == 0L ) + currentFrame = tqt_dynamic_cast(tabContainer->currentPage()); + else + currentFrame = tab; + + if (!currentFrame) { + return; + } + + KTempFile tempFile; + tempFile.setAutoDelete( true ); + TDEConfig config( tempFile.name() ); + config.setGroup( "View Profile" ); + + TQString prefix = TQString::fromLatin1( currentFrame->frameType() ) + TQString::number(0); + config.writeEntry( "RootItem", prefix ); + prefix.append( '_' ); + config.writeEntry( TQString::fromLatin1( "docContainer" ).prepend( prefix ), true ); + currentFrame->saveConfig( &config, prefix, true, 0L, 0, 1); + + KonqMainWindow *mainWindow = new KonqMainWindow( KURL(), false ); + if (mainWindow == 0L) return; + + mainWindow->viewManager()->loadViewProfile( config, "" ); + + KonqFrameBase * newDocContainer = mainWindow->viewManager()->docContainer(); + if( newDocContainer && newDocContainer->frameType() == "Tabs") + { + KonqFrameTabs *kft = static_cast(newDocContainer); + KonqFrameBase *newFrame = tqt_dynamic_cast(kft->currentPage()); + if(newFrame) + newFrame->copyHistory( currentFrame ); + } + + removeTab( currentFrame ); + + mainWindow->enableAllActions( true ); + + mainWindow->resize( width, height ); + + mainWindow->activateChild(); + + mainWindow->show(); + +#ifdef DEBUG_VIEWMGR + m_pMainWindow->dumpViewList(); + printFullHierarchy( m_pMainWindow ); + + mainWindow->dumpViewList(); + mainWindow->viewManager()->printFullHierarchy( mainWindow ); + + kdDebug(1202) << "------------- KonqViewManager::breakOffTab done --------------" << endl; +#endif +} + +void KonqViewManager::removeTab( KonqFrameBase* tab ) +{ +#ifdef DEBUG_VIEWMGR + kdDebug(1202) << "---------------- KonqViewManager::removeTab( " << tab << " ) --------------" << endl; + m_pMainWindow->dumpViewList(); + printFullHierarchy( m_pMainWindow ); +#endif + + if (m_pDocContainer == 0L) + return; + if (m_pDocContainer->frameType() != "Tabs" ) + return; + + KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); + + KonqFrameBase* currentFrame; + if ( tab != 0L ) { + currentFrame = tab; + } else { + currentFrame = tqt_dynamic_cast(tabContainer->currentPage()); + if (!currentFrame) { + return; + } + } + + if ( tabContainer->count() == 1 ) + return; + + if (currentFrame->widget() == tabContainer->currentPage()) + setActivePart( 0L, true ); + + tabContainer->removeChildFrame(currentFrame); + + TQPtrList viewList; + TQPtrListIterator it( viewList ); + + currentFrame->listViews( &viewList ); + + for ( it.toFirst(); it != 0L; ++it ) + { + if (it.current() == m_pMainWindow->currentView()) + setActivePart( 0L, true ); + m_pMainWindow->removeChildView( it.current() ); + delete it.current(); + } + + delete currentFrame; + + tabContainer->slotCurrentChanged(tabContainer->currentPage()); + +#ifdef DEBUG_VIEWMGR + m_pMainWindow->dumpViewList(); + printFullHierarchy( m_pMainWindow ); + kdDebug(1202) << "------------- KonqViewManager::removeTab done --------------" << endl; +#endif +} + +void KonqViewManager::reloadAllTabs( ) +{ + if (m_pDocContainer == 0L) return; + if (m_pDocContainer->frameType() != "Tabs") return; + + KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); + + TQPtrList frameList = *tabContainer->childFrameList(); + TQPtrListIterator it( frameList ); + + for ( it.toFirst(); it != 0L; ++it ) + { + if ( it.current()->activeChildView()) + { + if( !it.current()->activeChildView()->locationBarURL().isEmpty()) + it.current()->activeChildView()->openURL( it.current()->activeChildView()->url(),it.current()->activeChildView()->locationBarURL()); + } + } +} + +void KonqViewManager::removeOtherTabs( KonqFrameBase* tab ) +{ + + if (m_pDocContainer == 0L) return; + if (m_pDocContainer->frameType() != "Tabs") return; + + KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); + + KonqFrameBase *currentFrame; + + if ( tab == 0L ) + currentFrame = tqt_dynamic_cast(tabContainer->currentPage()); + else + currentFrame = tab; + + if (!currentFrame) { + return; + } + + TQPtrList frameList = *tabContainer->childFrameList(); + TQPtrListIterator it( frameList ); + + for ( it.toFirst(); it != 0L; ++it ) + { + if( it.current() != currentFrame ) + removeTab(it.current()); + } + +} + +void KonqViewManager::moveTabBackward() +{ + if (m_pDocContainer == 0L) return; + if (m_pDocContainer->frameType() != "Tabs") return; + KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); + if( tabContainer->count() == 1 ) return; + + int iTab = tabContainer->currentPageIndex(); + kdDebug()<<" tabContainer->currentPageIndex(); :"<moveTabBackward(iTab); +} + +void KonqViewManager::moveTabForward() +{ + if (m_pDocContainer == 0L) return; + if (m_pDocContainer->frameType() != "Tabs") return; + KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); + if( tabContainer->count() == 1 ) return; + + int iTab = tabContainer->currentPageIndex(); + tabContainer->moveTabForward(iTab); +} + +void KonqViewManager::activateNextTab() +{ + if (m_pDocContainer == 0L) return; + if (m_pDocContainer->frameType() != "Tabs") return; + + KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); + if( tabContainer->count() == 1 ) return; + + int iTab = tabContainer->currentPageIndex(); + + iTab++; + + if( iTab == tabContainer->count() ) + iTab = 0; + + tabContainer->setCurrentPage( iTab ); +} + +void KonqViewManager::activatePrevTab() +{ + if (m_pDocContainer == 0L) return; + if (m_pDocContainer->frameType() != "Tabs") return; + + KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); + if( tabContainer->count() == 1 ) return; + + int iTab = tabContainer->currentPageIndex(); + + iTab--; + + if( iTab == -1 ) + iTab = tabContainer->count() - 1; + + tabContainer->setCurrentPage( iTab ); +} + +void KonqViewManager::activateTab(int position) +{ + if (m_pDocContainer == 0L) return; + if (m_pDocContainer->frameType() != "Tabs") return; + + KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); + if (position<0 || tabContainer->count() == 1 || position>=tabContainer->count()) return; + + tabContainer->setCurrentPage( position ); +} + +void KonqViewManager::showTab( KonqView *view ) +{ + KonqFrameTabs *tabContainer = static_cast( docContainer() ); + if (tabContainer->currentPage() != view->frame()) + { + tabContainer->showPage( view->frame() ); + emitActivePartChanged(); + } +} + +void KonqViewManager::updatePixmaps() +{ + if (m_pDocContainer == 0L) return; + if (m_pDocContainer->frameType() != "Tabs") return; + + KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); + + TQPtrList viewList; + TQPtrListIterator it( viewList ); + + tabContainer->listViews( &viewList ); + for ( it.toFirst(); it != 0L; ++it ) + it.current()->setTabIcon( KURL::fromPathOrURL( it.current()->locationBarURL() ) ); +} + +void KonqViewManager::removeView( KonqView *view ) +{ +#ifdef DEBUG_VIEWMGR + kdDebug(1202) << "---------------- removeView --------------" << view << endl; + m_pMainWindow->dumpViewList(); + printFullHierarchy( m_pMainWindow ); +#endif + + if (!view) + return; + + KonqFrame* frame = view->frame(); + KonqFrameContainerBase* parentContainer = frame->parentContainer(); + + kdDebug(1202) << "view=" << view << " frame=" << frame << " parentContainer=" << parentContainer << endl; + + if (parentContainer->frameType()=="Container") + { + kdDebug(1202) << "parentContainer is a KonqFrameContainer" << endl; + + KonqFrameContainerBase* grandParentContainer = parentContainer->parentContainer(); + kdDebug(1202) << "grandParentContainer=" << grandParentContainer << endl; + + setActivePart( 0L, true ); + + int index = -1; + TQValueList splitterSizes; + bool moveOtherChild = false; + + if (grandParentContainer->frameType()=="Tabs") + index = static_cast(grandParentContainer)->indexOf( parentContainer->widget() ); + else if (grandParentContainer->frameType()=="Container") + { + moveOtherChild = (static_cast(grandParentContainer)->idAfter( parentContainer->widget() ) != 0); + splitterSizes = static_cast(grandParentContainer)->sizes(); + } + + KonqFrameBase* otherFrame = static_cast(parentContainer)->otherChild( frame ); + kdDebug(1202) << "otherFrame=" << otherFrame << endl; + + if( otherFrame == 0L ) + { + kdWarning(1202) << "KonqViewManager::removeView: This shouldn't happen!" << endl; + return; + } + + if (m_pDocContainer == parentContainer) m_pDocContainer = otherFrame; + + grandParentContainer->widget()->setUpdatesEnabled( false ); + static_cast(parentContainer)->setAboutToBeDeleted(); + + //kdDebug(1202) << "--- Reparenting otherFrame to m_pMainWindow " << m_pMainWindow << endl; + TQPoint pos = otherFrame->widget()->pos(); + otherFrame->reparentFrame( m_pMainWindow, pos ); + + //kdDebug(1202) << "--- Removing otherFrame from parentContainer" << endl; + parentContainer->removeChildFrame( otherFrame ); + + //kdDebug(1202) << "--- Removing parentContainer from grandParentContainer" << endl; + grandParentContainer->removeChildFrame( parentContainer ); + + //kdDebug(1202) << "--- Removing view from view list" << endl; + m_pMainWindow->removeChildView(view); + //kdDebug(1202) << "--- Deleting view " << view << endl; + delete view; // This deletes the view, which deletes the part, which deletes its widget + + //kdDebug(1202) << "--- Deleting parentContainer " << parentContainer + // << ". Its parent is " << parentContainer->widget()->parent() << endl; + delete parentContainer; + + //kdDebug(1202) << "--- Reparenting otherFrame to grandParentContainer" << grandParentContainer << endl; + otherFrame->reparentFrame( grandParentContainer->widget(), pos ); + + //kdDebug(1202) << "--- Inserting otherFrame into grandParentContainer" << grandParentContainer << endl; + grandParentContainer->insertChildFrame( otherFrame, index ); + + if( moveOtherChild ) + { + static_cast(grandParentContainer)->moveToFirst( otherFrame->widget() ); + static_cast(grandParentContainer)->swapChildren(); + } + + if (grandParentContainer->frameType()=="Container") + static_cast(grandParentContainer)->setSizes( splitterSizes ); + + otherFrame->widget()->show(); + + grandParentContainer->setActiveChild( otherFrame ); + grandParentContainer->activateChild(); + + grandParentContainer->widget()->setUpdatesEnabled( true ); + } + else if (parentContainer->frameType()=="Tabs") { + kdDebug(1202) << "parentContainer " << parentContainer << " is a KonqFrameTabs" << endl; + + removeTab( frame ); + } + else if (parentContainer->frameType()=="MainWindow") + kdDebug(1202) << "parentContainer is a KonqMainWindow. This shouldn't be removeable, not removing." << endl; + else + kdDebug(1202) << "Unrecognized frame type, not removing." << endl; + +#ifdef DEBUG_VIEWMGR + printFullHierarchy( m_pMainWindow ); + m_pMainWindow->dumpViewList(); + + kdDebug(1202) << "------------- removeView done --------------" << view << endl; +#endif +} + +// reimplemented from PartManager +void KonqViewManager::removePart( KParts::Part * part ) +{ + kdDebug(1202) << "KonqViewManager::removePart ( " << part << " )" << endl; + // This is called when a part auto-deletes itself (case 1), or when + // the "delete view" above deletes, in turn, the part (case 2) + + kdDebug(1202) << "Calling KParts::PartManager::removePart " << part << endl; + KParts::PartManager::removePart( part ); + + // If we were called by PartManager::slotObjectDestroyed, then the inheritance has + // been deleted already... Can't use inherits(). + + KonqView * view = m_pMainWindow->childView( static_cast(part) ); + if ( view ) // the child view still exists, so we are in case 1 + { + kdDebug(1202) << "Found a child view" << endl; + view->partDeleted(); // tell the child view that the part auto-deletes itself + if (m_pMainWindow->mainViewsCount() == 1) + { + kdDebug(1202) << "Deleting last view -> closing the window" << endl; + clear(); + kdDebug(1202) << "Closing m_pMainWindow " << m_pMainWindow << endl; + m_pMainWindow->close(); // will delete it + return; + } else { // normal case + removeView( view ); + } + } + + kdDebug(1202) << "KonqViewManager::removePart ( " << part << " ) done" << endl; +} + +void KonqViewManager::slotPassiveModePartDeleted() +{ + // Passive mode parts aren't registered to the part manager, + // so we have to handle suicidal ones ourselves + KParts::ReadOnlyPart * part = const_cast( static_cast( sender() ) ); + disconnect( part, TQT_SIGNAL( destroyed() ), this, TQT_SLOT( slotPassiveModePartDeleted() ) ); + kdDebug(1202) << "KonqViewManager::slotPassiveModePartDeleted part=" << part << endl; + KonqView * view = m_pMainWindow->childView( part ); + kdDebug(1202) << "view=" << view << endl; + if ( view != 0L) // the child view still exists, so the part suicided + { + view->partDeleted(); // tell the child view that the part deleted itself + removeView( view ); + } +} + +void KonqViewManager::viewCountChanged() +{ + bool bShowActiveViewIndicator = ( m_pMainWindow->viewCount() > 1 ); + bool bShowLinkedViewIndicator = ( m_pMainWindow->linkableViewsCount() > 1 ); + + KonqMainWindow::MapViews mapViews = m_pMainWindow->viewMap(); + KonqMainWindow::MapViews::Iterator it = mapViews.begin(); + KonqMainWindow::MapViews::Iterator end = mapViews.end(); + for ( ; it != end ; ++it ) + { + KonqFrameStatusBar* sb = it.data()->frame()->statusbar(); + sb->showActiveViewIndicator( bShowActiveViewIndicator && !it.data()->isPassiveMode() ); + sb->showLinkedViewIndicator( bShowLinkedViewIndicator && !it.data()->isFollowActive() ); + } +} + +void KonqViewManager::clear() +{ + kdDebug(1202) << "KonqViewManager::clear" << endl; + setActivePart( 0L, true /* immediate */ ); + + if (m_pMainWindow->childFrame() == 0L) return; + + TQPtrList viewList; + + m_pMainWindow->listViews( &viewList ); + + kdDebug(1202) << viewList.count() << " items" << endl; + + TQPtrListIterator it( viewList ); + for ( it.toFirst(); it.current(); ++it ) { + m_pMainWindow->removeChildView( it.current() ); + kdDebug(1202) << "Deleting " << it.current() << endl; + delete it.current(); + } + + kdDebug(1202) << "deleting mainFrame " << endl; + KonqFrameBase* frame = m_pMainWindow->childFrame(); + m_pMainWindow->removeChildFrame( frame ); // will set childFrame() to NULL + delete frame; + + m_pDocContainer = 0L; +} + +KonqView *KonqViewManager::chooseNextView( KonqView *view ) +{ + //kdDebug(1202) << "KonqViewManager(" << this << ")::chooseNextView(" << view << ")" << endl; + KonqMainWindow::MapViews mapViews = m_pMainWindow->viewMap(); + + KonqMainWindow::MapViews::Iterator it = mapViews.begin(); + KonqMainWindow::MapViews::Iterator end = mapViews.end(); + if ( view ) // find it in the map - can't use the key since view->part() might be 0L + while ( it != end && it.data() != view ) + ++it; + + // the view should always be in the list + if ( it == end ) { + if ( view ) + kdWarning() << "View " << view << " is not in list !" << endl; + it = mapViews.begin(); + if ( it == end ) + return 0L; // We have no view at all - this used to happen with totally-empty-profiles + } + + KonqMainWindow::MapViews::Iterator startIt = it; + + //kdDebug(1202) << "KonqViewManager::chooseNextView: count=" << mapViews.count() << endl; + while ( true ) + { + //kdDebug(1202) << "*KonqViewManager::chooseNextView going next" << endl; + if ( ++it == end ) // move to next + it = mapViews.begin(); // rewind on end + + if ( it == startIt && view ) + break; // no next view found + + KonqView *nextView = it.data(); + if ( nextView && !nextView->isPassiveMode() ) + return nextView; + //kdDebug(1202) << "KonqViewManager::chooseNextView nextView=" << nextView << " passive=" << nextView->isPassiveMode() << endl; + } + + //kdDebug(1202) << "KonqViewManager::chooseNextView: returning 0L" << endl; + return 0L; // no next view found +} + +KonqViewFactory KonqViewManager::createView( const TQString &serviceType, + const TQString &serviceName, + KService::Ptr &service, + TDETrader::OfferList &partServiceOffers, + TDETrader::OfferList &appServiceOffers, + bool forceAutoEmbed ) +{ + kdDebug(1202) << "KonqViewManager::createView" << endl; + KonqViewFactory viewFactory; + + if( serviceType.isEmpty() && m_pMainWindow->currentView() ) { + //clone current view + KonqView *cv = m_pMainWindow->currentView(); + TQString _serviceType, _serviceName; + if ( cv->service()->desktopEntryName() == "konq_sidebartng" ) { + _serviceType = "text/html"; + } + else { + _serviceType = cv->serviceType(); + _serviceName = cv->service()->desktopEntryName(); + } + + viewFactory = KonqFactory::createView( _serviceType, _serviceName, + &service, &partServiceOffers, &appServiceOffers, forceAutoEmbed ); + } + else { + //create view with the given servicetype + viewFactory = KonqFactory::createView( serviceType, serviceName, + &service, &partServiceOffers, &appServiceOffers, forceAutoEmbed ); + } + + return viewFactory; +} + +KonqView *KonqViewManager::setupView( KonqFrameContainerBase *parentContainer, + KonqViewFactory &viewFactory, + const KService::Ptr &service, + const TDETrader::OfferList &partServiceOffers, + const TDETrader::OfferList &appServiceOffers, + const TQString &serviceType, + bool passiveMode, + bool openAfterCurrentPage ) +{ + kdDebug(1202) << "KonqViewManager::setupView passiveMode=" << passiveMode << endl; + + TQString sType = serviceType; + + if ( sType.isEmpty() ) + sType = m_pMainWindow->currentView()->serviceType(); + + //kdDebug(1202) << "KonqViewManager::setupView creating KonqFrame with parent=" << parentContainer << endl; + KonqFrame* newViewFrame = new KonqFrame( parentContainer->widget(), parentContainer, "KonqFrame" ); + newViewFrame->setGeometry( 0, 0, m_pMainWindow->width(), m_pMainWindow->height() ); + + //kdDebug(1202) << "Creating KonqView" << endl; + KonqView *v = new KonqView( viewFactory, newViewFrame, + m_pMainWindow, service, partServiceOffers, appServiceOffers, sType, passiveMode ); + //kdDebug(1202) << "KonqView created - v=" << v << " v->part()=" << v->part() << endl; + + TQObject::connect( v, TQT_SIGNAL( sigPartChanged( KonqView *, KParts::ReadOnlyPart *, KParts::ReadOnlyPart * ) ), + m_pMainWindow, TQT_SLOT( slotPartChanged( KonqView *, KParts::ReadOnlyPart *, KParts::ReadOnlyPart * ) ) ); + + m_pMainWindow->insertChildView( v ); + + + int index = -1; + + if (m_pDocContainer && m_pDocContainer->frameType() == "Tabs") + { + KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); + if ( openAfterCurrentPage ) + index = tabContainer->currentPageIndex() +1 ; + } + + parentContainer->insertChildFrame( newViewFrame, index ); + + if (parentContainer->frameType() != "Tabs") newViewFrame->show(); + + // Don't register passive views to the part manager + if ( !v->isPassiveMode() ) // note that KonqView's constructor could set this to true even if passiveMode is false + addPart( v->part(), false ); + else + { + // Passive views aren't registered, but we still want to detect the suicidal ones + connect( v->part(), TQT_SIGNAL( destroyed() ), this, TQT_SLOT( slotPassiveModePartDeleted() ) ); + } + + //kdDebug(1202) << "KonqViewManager::setupView done" << endl; + return v; +} + +///////////////// Profile stuff //////////////// + +void KonqViewManager::saveViewProfile( const TQString & fileName, const TQString & profileName, bool saveURLs, bool saveWindowSize ) +{ + + TQString path = locateLocal( "data", TQString::fromLatin1( "konqueror/profiles/" ) + + fileName, TDEGlobal::instance() ); + + if ( TQFile::exists( path ) ) + TQFile::remove( path ); + + KSimpleConfig cfg( path ); + cfg.setGroup( "Profile" ); + if ( !profileName.isEmpty() ) + cfg.writePathEntry( "Name", profileName ); + + saveViewProfile( cfg, saveURLs, saveWindowSize ); + +} + +void KonqViewManager::saveViewProfile( TDEConfig & cfg, bool saveURLs, bool saveWindowSize ) +{ + //kdDebug(1202) << "KonqViewManager::saveViewProfile" << endl; + if( m_pMainWindow->childFrame() != 0L ) { + TQString prefix = TQString::fromLatin1( m_pMainWindow->childFrame()->frameType() ) + + TQString::number(0); + cfg.writeEntry( "RootItem", prefix ); + prefix.append( '_' ); + m_pMainWindow->saveConfig( &cfg, prefix, saveURLs, m_pDocContainer, 0, 1); + } + + cfg.writeEntry( "FullScreen", m_pMainWindow->fullScreenMode()); + cfg.writeEntry("XMLUIFile", m_pMainWindow->xmlFile()); + if ( saveWindowSize ) + { + cfg.writeEntry( "Width", m_pMainWindow->width() ); + cfg.writeEntry( "Height", m_pMainWindow->height() ); + } + + // Save menu/toolbar settings in profile. Relys on konq_mainwindow calling + // setAutoSaveSetting( "KongMainWindow", false ). The false is important, + // we do not want this call save size settings in the profile, because we + // do it ourselves. Save in a separate group than the rest of the profile. + TQString savedGroup = cfg.group(); + m_pMainWindow->saveMainWindowSettings( &cfg, "Main Window Settings" ); + cfg.setGroup( savedGroup ); + + cfg.sync(); +} + +void KonqViewManager::loadViewProfile( const TQString & path, const TQString & filename, + const KURL & forcedURL, const KonqOpenURLRequest &req, + bool resetWindow, bool openURL ) +{ + TDEConfig cfg( path, true ); + cfg.setDollarExpansion( true ); + cfg.setGroup( "Profile" ); + loadViewProfile( cfg, filename, forcedURL, req, resetWindow, openURL ); +} + +void KonqViewManager::loadViewProfile( TDEConfig &cfg, const TQString & filename, + const KURL & forcedURL, const KonqOpenURLRequest &req, + bool resetWindow, bool openURL ) +{ + if ( docContainer() && docContainer()->frameType()=="Tabs" ) + { + KonqFrameTabs* tabContainer = static_cast(docContainer()); + if ( tabContainer->count() > 1 ) + { + if ( KMessageBox::warningContinueCancel( 0, + i18n("You have multiple tabs open in this window.\n" + "Loading a view profile will close them."), + i18n("Confirmation"), + i18n("Load View Profile"), + "LoadProfileTabsConfirm" ) == KMessageBox::Cancel ) + return; + } + + KonqView *originalView = m_pMainWindow->currentView(); + TQPtrList frameList = *tabContainer->childFrameList(); + TQPtrListIterator it( frameList ); + for ( it.toFirst(); it != 0L; ++it ) + { + KonqView *view = it.current()->activeChildView(); + if (view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1)) { + TQVariant prop = view->part()->property("modified"); + if (prop.isValid() && prop.toBool()) { + showTab( view ); + if ( KMessageBox::warningContinueCancel( 0, + i18n("This tab contains changes that have not been submitted.\nLoading a profile will discard these changes."), + i18n("Discard Changes?"), i18n("&Discard Changes"), "discardchangesloadprofile") != KMessageBox::Continue ) + { + showTab( originalView ); + return; + } + } + } + } + showTab( originalView ); + } + else + { + KonqView *view = m_pMainWindow->currentView(); + if (view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1)) { + TQVariant prop = view->part()->property("modified"); + if (prop.isValid() && prop.toBool()) + if ( KMessageBox::warningContinueCancel( 0, + i18n("This page contains changes that have not been submitted.\nLoading a profile will discard these changes."), + i18n("Discard Changes?"), i18n("&Discard Changes"), "discardchangesloadprofile") != KMessageBox::Continue ) + return; + } + } + + bool alwaysTabbedMode = KonqSettings::alwaysTabbedMode(); + + m_currentProfile = filename; + m_currentProfileText = cfg.readPathEntry("Name",filename); + m_profileHomeURL = cfg.readEntry("HomeURL", TQString::null); + + m_pMainWindow->currentProfileChanged(); + KURL defaultURL; + if ( m_pMainWindow->currentView() ) + defaultURL = m_pMainWindow->currentView()->url(); + + clear(); + + TQString rootItem = cfg.readEntry( "RootItem", "empty" ); + + //kdDebug(1202) << "KonqViewManager::loadViewProfile : loading RootItem " << rootItem << + //" forcedURL " << forcedURL.url() << endl; + + if ( forcedURL.url() != "about:blank" ) + { + // This flag is used by KonqView, to distinguish manual view creation + // from profile loading (e.g. in switchView) + m_bLoadingProfile = true; + + loadItem( cfg, m_pMainWindow, rootItem, defaultURL, openURL && forcedURL.isEmpty() ); + + m_bLoadingProfile = false; + + m_pMainWindow->enableAllActions(true); + + // This flag disables calls to viewCountChanged while creating the views, + // so we do it once at the end : + m_pMainWindow->viewCountChanged(); + } + else + { + m_pMainWindow->disableActionsNoView(); + m_pMainWindow->action( "clear_location" )->activate(); + } + + //kdDebug(1202) << "KonqViewManager::loadViewProfile : after loadItem " << endl; + + if (m_pDocContainer == 0L) + { + if (m_pMainWindow && + m_pMainWindow->currentView() && + m_pMainWindow->currentView()->frame()) { + m_pDocContainer = m_pMainWindow->currentView()->frame(); + } else { + kdDebug(1202) << "This view profile does not support tabs." << endl; + return; + } + } + + + if ( m_pDocContainer->frameType() != "Tabs") + convertDocContainer(); + + static_cast( m_pDocContainer )->setAlwaysTabbedMode( alwaysTabbedMode ); + static_cast( m_pDocContainer )->setMouseWheelScroll(KonqSettings::tabsCycleWheel()); + + // Set an active part first so that we open the URL in the current view + // (to set the location bar correctly and asap) + KonqView *nextChildView = 0L; + nextChildView = m_pMainWindow->activeChildView(); + if (nextChildView == 0L) nextChildView = chooseNextView( 0L ); + setActivePart( nextChildView ? nextChildView->part() : 0L, true /* immediate */); + + // #71164 + if ( !req.args.frameName.isEmpty() && nextChildView ) { + nextChildView->setViewName( req.args.frameName ); + } + + if ( openURL && !forcedURL.isEmpty()) + { + KonqOpenURLRequest _req(req); + _req.openAfterCurrentPage = KonqSettings::openAfterCurrentPage(); + _req.forceAutoEmbed = true; // it's a new window, let's use it + + m_pMainWindow->openURL( nextChildView /* can be 0 for an empty profile */, + forcedURL, _req.args.serviceType, _req, _req.args.trustedSource ); + + // TODO choose a linked view if any (instead of just the first one), + // then open the same URL in any non-linked one + } + else + { + if ( m_pMainWindow->locationBarURL().isEmpty() ) // No URL -> the user will want to type one + m_pMainWindow->focusLocationBar(); + } + + // Window size + if ( !m_pMainWindow->initialGeometrySet() ) + { + if (cfg.readBoolEntry( "FullScreen" )) + { + // Full screen on + m_pMainWindow->showFullScreen(); + } + else + { + // Full screen off + if( m_pMainWindow->isFullScreen()) + m_pMainWindow->showNormal(); + + TQSize size = readConfigSize( cfg, m_pMainWindow ); + if ( size.isValid() ) + m_pMainWindow->resize( size ); + else // no size in the profile; use last known size + m_pMainWindow->restoreWindowSize(); + } + } + + if( resetWindow ) + { // force default settings for the GUI + m_pMainWindow->applyMainWindowSettings( TDEGlobal::config(), "KonqMainWindow", true ); + } + + // Apply menu/toolbar settings saved in profile. Read from a separate group + // so that the window doesn't try to change the size stored in the Profile group. + // (If applyMainWindowSettings finds a "Width" or "Height" entry, it + // sets them to 0,0) + TQString savedGroup = cfg.group(); + m_pMainWindow->applyMainWindowSettings( &cfg, "Main Window Settings" ); + cfg.setGroup( savedGroup ); + +#ifdef DEBUG_VIEWMGR + printFullHierarchy( m_pMainWindow ); +#endif + + //kdDebug(1202) << "KonqViewManager::loadViewProfile done" << endl; +} + +void KonqViewManager::setActivePart( KParts::Part *part, TQWidget * ) +{ + setActivePart( part, false ); +} + +void KonqViewManager::setActivePart( KParts::Part *part, bool immediate ) +{ + //kdDebug(1202) << "KonqViewManager::setActivePart " << part << endl; + //if ( part ) + // kdDebug(1202) << " " << part->className() << " " << part->name() << endl; + + // Due to the single-shot timer below, we need to also make sure that + // the mainwindow also has the right part active already + KParts::Part* mainWindowActivePart = (m_pMainWindow && m_pMainWindow->currentView()) + ? m_pMainWindow->currentView()->part() : 0; + if (part == activePart() && (!immediate || mainWindowActivePart == part)) + { + if ( part ) + kdDebug(1202) << "Part is already active!" << endl; + return; + } + + // Don't activate when part changed in non-active tab + KonqView* partView = m_pMainWindow->childView((KParts::ReadOnlyPart*)part); + if (partView) + { + KonqFrameContainerBase* parentContainer = partView->frame()->parentContainer(); + if (parentContainer->frameType()=="Tabs") + { + KonqFrameTabs* parentFrameTabs = static_cast(parentContainer); + if (partView->frame() != parentFrameTabs->currentPage()) + return; + } + } + + if (m_pMainWindow && m_pMainWindow->currentView()) + m_pMainWindow->currentView()->setLocationBarURL(m_pMainWindow->locationBarURL()); + + KParts::PartManager::setActivePart( part ); + + if (part && part->widget()) + part->widget()->setFocus(); + + if (!immediate && reason() != ReasonRightClick) { + // We use a 0s single shot timer so that when left-clicking on a part, + // we process the mouse event before rebuilding the GUI. + // Otherwise, when e.g. dragging icons, the mouse pointer can already + // be very far from where it was... + m_activePartChangedTimer->start( 0, true ); + // This is not done with right-clicking so that the part is activated before the + // popup appears (#75201) + } else { + emitActivePartChanged(); + } +} + +void KonqViewManager::slotActivePartChanged ( KParts::Part *newPart ) +{ + //kdDebug(1202) << "KonqViewManager::slotActivePartChanged " << newPart << endl; + if (newPart == 0L) { + //kdDebug(1202) << "newPart = 0L , returning" << endl; + return; + } + KonqView * view = m_pMainWindow->childView( static_cast(newPart) ); + if (view == 0L) { + kdDebug(1202) << k_funcinfo << "No view associated with this part" << endl; + return; + } + if (view->frame()->parentContainer() == 0L) return; + if (!m_bLoadingProfile) { + view->frame()->statusbar()->updateActiveStatus(); + view->frame()->parentContainer()->setActiveChild( view->frame() ); + } + //kdDebug(1202) << "KonqViewManager::slotActivePartChanged done" << endl; +} + +void KonqViewManager::emitActivePartChanged() +{ + // prevent unnecessary multiple calls to slotPartActivated: + m_activePartChangedTimer->stop(); + m_pMainWindow->slotPartActivated( activePart() ); +} + + +TQSize KonqViewManager::readConfigSize( TDEConfig &cfg, TQWidget *widget ) +{ + bool ok; + + TQString widthStr = cfg.readEntry( "Width" ); + TQString heightStr = cfg.readEntry( "Height" ); + + int width = -1; + int height = -1; + + TQRect geom = TDEGlobalSettings::desktopGeometry(widget); + + if ( widthStr.contains( '%' ) == 1 ) + { + widthStr.truncate( widthStr.length() - 1 ); + int relativeWidth = widthStr.toInt( &ok ); + if ( ok ) { + width = relativeWidth * geom.width() / 100; + } + } + else + { + width = widthStr.toInt( &ok ); + if ( !ok ) + width = -1; + } + + if ( heightStr.contains( '%' ) == 1 ) + { + heightStr.truncate( heightStr.length() - 1 ); + int relativeHeight = heightStr.toInt( &ok ); + if ( ok ) { + height = relativeHeight * geom.height() / 100; + } + } + else + { + height = heightStr.toInt( &ok ); + if ( !ok ) + height = -1; + } + + return TQSize( width, height ); +} + +void KonqViewManager::loadItem( TDEConfig &cfg, KonqFrameContainerBase *parent, + const TQString &name, const KURL & defaultURL, bool openURL, bool openAfterCurrentPage ) +{ + TQString prefix; + if( name != "InitialView" ) + prefix = name + '_'; + + //kdDebug(1202) << "KonqViewManager::loadItem: begin name " << name << " openURL " << openURL << endl; + + if( name.startsWith("View") || name == "empty" ) { + //load view config + TQString serviceType; + TQString serviceName; + if ( name == "empty" ) { + // An empty profile is an empty TDEHTML part. Makes all TDEHTML actions available, avoids crashes, + // makes it easy to DND a URL onto it, and makes it fast to load a website from there. + serviceType = "text/html"; + serviceName = "html"; + } else { + serviceType = cfg.readEntry( TQString::fromLatin1( "ServiceType" ).prepend( prefix ), "inode/directory"); + serviceName = cfg.readEntry( TQString::fromLatin1( "ServiceName" ).prepend( prefix ) ); + } + //kdDebug(1202) << "KonqViewManager::loadItem: ServiceType " << serviceType << " " << serviceName << endl; + + KService::Ptr service; + TDETrader::OfferList partServiceOffers, appServiceOffers; + + KonqViewFactory viewFactory = KonqFactory::createView( serviceType, serviceName, &service, &partServiceOffers, &appServiceOffers, true /*forceAutoEmbed*/ ); + if ( viewFactory.isNull() ) + { + kdWarning(1202) << "Profile Loading Error: View creation failed" << endl; + return; //ugh.. + } + + bool passiveMode = cfg.readBoolEntry( TQString::fromLatin1( "PassiveMode" ).prepend( prefix ), false ); + + //kdDebug(1202) << "KonqViewManager::loadItem: Creating View Stuff" << endl; + KonqView *childView = setupView( parent, viewFactory, service, partServiceOffers, appServiceOffers, serviceType, passiveMode, openAfterCurrentPage ); + + if (!childView->isFollowActive()) childView->setLinkedView( cfg.readBoolEntry( TQString::fromLatin1( "LinkedView" ).prepend( prefix ), false ) ); + childView->setToggleView( cfg.readBoolEntry( TQString::fromLatin1( "ToggleView" ).prepend( prefix ), false ) ); + if( !cfg.readBoolEntry( TQString::fromLatin1( "ShowStatusBar" ).prepend( prefix ), true ) ) + childView->frame()->statusbar()->hide(); + + if (cfg.readBoolEntry( TQString::fromLatin1( "docContainer" ).prepend( prefix ), false )) + m_pDocContainer = childView->frame(); + + if (!m_pDocContainer) + { + if (parent->frameType() == "MainWindow") + m_pDocContainer = childView->frame(); // Child view of mainWindow + + else if (parent->frameType() == "Container") + { + KonqFrameContainer* parentContainer = static_cast(parent); + KonqFrameBase* otherFrame = parentContainer->otherChild( childView->frame() ); + if (otherFrame) + { + if (childView->isPassiveMode()) + { + if (otherFrame->frameType() == "View") + { + KonqFrame* viewFrame = static_cast(otherFrame); + if (viewFrame->childView()->isPassiveMode()) + m_pDocContainer = parentContainer; // Both views are passive, shouldn't happen + else + m_pDocContainer = viewFrame; // This one is passive, the other is active + } + } + else + { + if (otherFrame->frameType() == "View") + { + KonqFrame* viewFrame = static_cast(otherFrame); + if (viewFrame->childView()->isPassiveMode()) + m_pDocContainer = childView->frame(); // This one is active, the other is passive + else + m_pDocContainer = parentContainer; // Both views are active + } + else + m_pDocContainer = parentContainer; // This one is active, the other is a Container + } + } + } + } + KonqConfigEvent ev( &cfg, prefix+"_", false/*load*/); + TQApplication::sendEvent( childView->part(), &ev ); + + childView->frame()->show(); + + TQString key = TQString::fromLatin1( "URL" ).prepend( prefix ); + if ( openURL ) + { + KURL url; + + //kdDebug(1202) << "KonqViewManager::loadItem: key " << key << endl; + if ( cfg.hasKey( key ) ) + { + TQString u = cfg.readPathEntry( key ); + if ( u.isEmpty() ) + u = TQString::fromLatin1("about:blank"); + url = u; + } + else if(key == "empty_URL") + url = TQString::fromLatin1("about:blank"); + else + url = defaultURL; + + if ( !url.isEmpty() ) + { + //kdDebug(1202) << "KonqViewManager::loadItem: calling openURL " << url.prettyURL() << endl; + //childView->openURL( url, url.prettyURL() ); + // We need view-follows-view (for the dirtree, for instance) + KonqOpenURLRequest req; + if (url.protocol() != "about") + req.typedURL = url.prettyURL(); + m_pMainWindow->openView( serviceType, url, childView, req ); + } + //else kdDebug(1202) << "KonqViewManager::loadItem: url is empty" << endl; + } + // Do this after opening the URL, so that it's actually possible to open it :) + childView->setLockedLocation( cfg.readBoolEntry( TQString::fromLatin1( "LockedLocation" ).prepend( prefix ), false ) ); + } + else if( name.startsWith("Container") ) { + //kdDebug(1202) << "KonqViewManager::loadItem Item is Container" << endl; + + //load container config + TQString ostr = cfg.readEntry( TQString::fromLatin1( "Orientation" ).prepend( prefix ) ); + //kdDebug(1202) << "Orientation: " << ostr << endl; + Qt::Orientation o; + if( ostr == "Vertical" ) + o = Qt::Vertical; + else if( ostr == "Horizontal" ) + o = Qt::Horizontal; + else { + kdWarning() << "Profile Loading Error: No orientation specified in " << name << endl; + o = Qt::Horizontal; + } + + TQValueList sizes = + cfg.readIntListEntry( TQString::fromLatin1( "SplitterSizes" ).prepend( prefix )); + + int index = cfg.readNumEntry( TQString::fromLatin1( "activeChildIndex" ).prepend(prefix), -1 ); + + TQStrList childList; + if( cfg.readListEntry( TQString::fromLatin1( "Children" ).prepend( prefix ), childList ) < 2 ) + { + kdWarning() << "Profile Loading Error: Less than two children in " << name << endl; + // fallback to defaults + loadItem( cfg, parent, "InitialView", defaultURL, openURL ); + } + else + { + KonqFrameContainer *newContainer = new KonqFrameContainer( o, parent->widget(), parent ); + connect(newContainer,TQT_SIGNAL(ctrlTabPressed()),m_pMainWindow,TQT_SLOT(slotCtrlTabPressed())); + + int tabindex = -1; + if(openAfterCurrentPage && parent->frameType() == "Tabs") // Need to honor it, if possible + tabindex = static_cast(parent)->currentPageIndex() + 1; + parent->insertChildFrame( newContainer, tabindex ); + + + if (cfg.readBoolEntry( TQString::fromLatin1( "docContainer" ).prepend( prefix ), false )) + m_pDocContainer = newContainer; + + loadItem( cfg, newContainer, childList.at(0), defaultURL, openURL ); + loadItem( cfg, newContainer, childList.at(1), defaultURL, openURL ); + + newContainer->setSizes( sizes ); + + if (index == 1) + newContainer->setActiveChild( newContainer->secondChild() ); + else if (index == 0) + newContainer->setActiveChild( newContainer->firstChild() ); + + newContainer->show(); + } + } + else if( name.startsWith("Tabs") ) + { + //kdDebug(1202) << "KonqViewManager::loadItem: Item is a Tabs" << endl; + + KonqFrameTabs *newContainer = new KonqFrameTabs( parent->widget(), parent, this ); + connect(newContainer,TQT_SIGNAL(ctrlTabPressed()),m_pMainWindow,TQT_SLOT(slotCtrlTabPressed())); + + parent->insertChildFrame( newContainer ); + m_pDocContainer = newContainer; + + int index = cfg.readNumEntry( TQString::fromLatin1( "activeChildIndex" ).prepend(prefix), 0 ); + + TQStringList childList = cfg.readListEntry( TQString::fromLatin1( "Children" ).prepend( prefix ) ); + for ( TQStringList::Iterator it = childList.begin(); it != childList.end(); ++it ) + { + loadItem( cfg, newContainer, *it, defaultURL, openURL ); + TQWidget* currentPage = newContainer->currentPage(); + if (currentPage != 0L) { + KonqView* activeChildView = tqt_dynamic_cast(currentPage)->activeChildView(); + if (activeChildView != 0L) { + activeChildView->setCaption( activeChildView->caption() ); + activeChildView->setTabIcon( activeChildView->url() ); + } + } + } + + newContainer->setActiveChild( tqt_dynamic_cast(newContainer->page(index)) ); + newContainer->setCurrentPage( index ); + + newContainer->show(); + } + else + kdWarning() << "Profile Loading Error: Unknown item " << name; + + //kdDebug(1202) << "KonqViewManager::loadItem: end" << name << endl; +} + +void KonqViewManager::setProfiles( TDEActionMenu *profiles ) +{ + m_pamProfiles = profiles; + + if ( m_pamProfiles ) + { + connect( m_pamProfiles->popupMenu(), TQT_SIGNAL( activated( int ) ), + this, TQT_SLOT( slotProfileActivated( int ) ) ); + connect( m_pamProfiles->popupMenu(), TQT_SIGNAL( aboutToShow() ), + this, TQT_SLOT( slotProfileListAboutToShow() ) ); + } + //KonqMainWindow::enableAllActions will call it anyway + //profileListDirty(); +} + +void KonqViewManager::showProfileDlg( const TQString & preselectProfile ) +{ + KonqProfileDlg dlg( this, preselectProfile, m_pMainWindow ); + dlg.exec(); + profileListDirty(); +} + +void KonqViewManager::slotProfileDlg() +{ + showProfileDlg( TQString::null ); +} + +void KonqViewManager::profileListDirty( bool broadcast ) +{ + //kdDebug(1202) << "KonqViewManager::profileListDirty()" << endl; + if ( !broadcast ) + { + m_bProfileListDirty = true; + + // #if 0 causes problems with TDevelop syntax highlighting. Converted to comments + // #if 0 + // There's always one profile at least, now... + //TQStringList profiles = KonqFactory::instance()->dirs()->findAllResources( "data", "konqueror/profiles/*", false, true ); + //if ( m_pamProfiles ) + // m_pamProfiles->setEnabled( profiles.count() > 0 ); + // #endif + return; + } + + kapp->dcopClient()->send( "konqueror*", "KonquerorIface", "updateProfileList()", TQByteArray() ); +} + +void KonqViewManager::slotProfileActivated( int id ) +{ + + TQMap::ConstIterator iter = m_mapProfileNames.begin(); + TQMap::ConstIterator end = m_mapProfileNames.end(); + + for(int i=0; iter != end; ++iter, ++i) { + if( i == id ) { + KURL u; + u.setPath( *iter ); + loadViewProfile( *iter, u.fileName() ); + break; + } + } +} + +void KonqViewManager::slotProfileListAboutToShow() +{ + if ( !m_pamProfiles || !m_bProfileListDirty ) + return; + + TQPopupMenu *popup = m_pamProfiles->popupMenu(); + popup->clear(); + + // Fetch profiles + m_mapProfileNames = KonqProfileDlg::readAllProfiles(); + + // Generate accelerators + TQStringList accel_strings; + TDEAccelGen::generateFromKeys(m_mapProfileNames, accel_strings); + + // Store menu items + TQValueListIterator iter = accel_strings.begin(); + for( int id = 0; + iter != accel_strings.end(); + ++iter, ++id ) { + popup->insertItem( *iter, id ); + } + + m_bProfileListDirty = false; +} + +void KonqViewManager::setLoading( KonqView *view, bool loading ) +{ + KonqFrameContainerBase* parentContainer = view->frame()->parentContainer(); + if ( parentContainer->frameType() == "Tabs" ) { + TQColor color; + KonqFrameTabs* konqframetabs = static_cast( parentContainer ); + if ( loading ) + color = TQColor( (TDEGlobalSettings::linkColor().red() + TDEGlobalSettings::inactiveTextColor().red())/2, + (TDEGlobalSettings::linkColor().green()+ TDEGlobalSettings::inactiveTextColor().green())/2, + (TDEGlobalSettings::linkColor().blue() + TDEGlobalSettings::inactiveTextColor().blue())/2 ); + else + { + if ( konqframetabs->currentPage() != view->frame() ) + color = TDEGlobalSettings::linkColor(); + else + color = TDEGlobalSettings::textColor(); + } + konqframetabs->setTabColor( view->frame(), color ); + } +} + +void KonqViewManager::showHTML(bool b) +{ + if (m_pDocContainer == 0L) return; + if (m_pDocContainer->frameType() != "Tabs") return; + + KonqFrameTabs* tabContainer = static_cast(m_pDocContainer); + + TQPtrList frameList = *tabContainer->childFrameList(); + TQPtrListIterator it( frameList ); + + for ( it.toFirst(); it != 0L; ++it ) + { + if ( it.current()->activeChildView() && it.current()->activeChildView() !=m_pMainWindow->currentView()) + { + it.current()->activeChildView()->setAllowHTML( b ); + if( !it.current()->activeChildView()->locationBarURL().isEmpty()) + { + + m_pMainWindow->showHTML( it.current()->activeChildView(), b, false ); + } + } + } +} + +void KonqViewManager::reparseConfiguration() +{ + KonqFrameTabs *frameTabs=static_cast(m_pDocContainer); + if (frameTabs) + { + frameTabs->setAlwaysTabbedMode(KonqSettings::alwaysTabbedMode()); + frameTabs->setMouseWheelScroll(KonqSettings::tabsCycleWheel()); + } +} + + + +///////////////// Debug stuff //////////////// + +#ifndef NDEBUG +void KonqViewManager::printSizeInfo( KonqFrameBase* frame, + KonqFrameContainerBase* parent, + const char* msg ) +{ + TQRect r; + r = frame->widget()->geometry(); + tqDebug("Child size %s : x: %d, y: %d, w: %d, h: %d", msg, r.x(),r.y(),r.width(),r.height() ); + + if ( parent->frameType() == "Container" ) + { + TQValueList sizes; + sizes = static_cast(parent)->sizes(); + printf( "Parent sizes %s :", msg ); + TQValueList::ConstIterator it; + for( it = sizes.begin(); it != sizes.end(); ++it ) + printf( " %d", (*it) ); + printf("\n"); + } +} + +void KonqViewManager::printFullHierarchy( KonqFrameContainerBase * container ) +{ + kdDebug(1202) << "currentView=" << m_pMainWindow->currentView() << endl; + kdDebug(1202) << "docContainer=" << m_pDocContainer << endl; + + if (container) container->printFrameInfo(TQString::null); + else m_pMainWindow->printFrameInfo(TQString::null); +} +#endif + +#include "konq_viewmgr.moc" diff --git a/konqueror/konqueror.kcfg b/konqueror/konqueror.kcfg index ec4728e03..4049e8791 100644 --- a/konqueror/konqueror.kcfg +++ b/konqueror/konqueror.kcfg @@ -158,14 +158,14 @@ - + true - + false @@ -282,7 +282,7 @@ - + true @@ -502,7 +502,7 @@ PATH_JAVA - + @@ -526,7 +526,7 @@ PATH_JAVA - + false diff --git a/konqueror/listview/CMakeLists.txt b/konqueror/listview/CMakeLists.txt index dd60407da..01fc5f0ec 100644 --- a/konqueror/listview/CMakeLists.txt +++ b/konqueror/listview/CMakeLists.txt @@ -45,10 +45,10 @@ install( FILES konq_listview.kcfg DESTINATION ${KCFG_INSTALL_DIR} ) set( target konq_listview ) set( ${target}_SRCS - konq_listview.cc konq_listviewwidget.cc konq_listviewitems.cc - konq_treeviewwidget.cc konq_treeviewitem.cc konq_textviewwidget.cc - konq_textviewitem.cc konq_infolistviewwidget.cc - konq_infolistviewitem.cc konq_listviewsettings.kcfgc + konq_listview.cpp konq_listviewwidget.cpp konq_listviewitems.cpp + konq_treeviewwidget.cpp konq_treeviewitem.cpp konq_textviewwidget.cpp + konq_textviewitem.cpp konq_infolistviewwidget.cpp + konq_infolistviewitem.cpp konq_listviewsettings.kcfgc ) tde_add_kpart( ${target} AUTOMOC diff --git a/konqueror/listview/Makefile.am b/konqueror/listview/Makefile.am index 91dd33a10..c190de7df 100644 --- a/konqueror/listview/Makefile.am +++ b/konqueror/listview/Makefile.am @@ -5,11 +5,11 @@ kde_module_LTLIBRARIES = konq_listview.la METASOURCES = AUTO -konq_listview_la_SOURCES = konq_listview.cc \ - konq_listviewwidget.cc konq_listviewitems.cc \ - konq_treeviewwidget.cc konq_treeviewitem.cc \ - konq_textviewwidget.cc konq_textviewitem.cc \ - konq_infolistviewwidget.cc konq_infolistviewitem.cc \ +konq_listview_la_SOURCES = konq_listview.cpp \ + konq_listviewwidget.cpp konq_listviewitems.cpp \ + konq_treeviewwidget.cpp konq_treeviewitem.cpp \ + konq_textviewwidget.cpp konq_textviewitem.cpp \ + konq_infolistviewwidget.cpp konq_infolistviewitem.cpp \ konq_listviewsettings.kcfgc konq_listview_la_LDFLAGS = $(all_libraries) $(KDE_PLUGIN) -module diff --git a/konqueror/listview/konq_infolistviewitem.cc b/konqueror/listview/konq_infolistviewitem.cc deleted file mode 100644 index 18efb3f8f..000000000 --- a/konqueror/listview/konq_infolistviewitem.cc +++ /dev/null @@ -1,280 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2002 Rolf Magnus - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation version 2.0 - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - -*/ - -#include "konq_listview.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "konq_infolistviewitem.h" -#include "konq_infolistviewwidget.h" - -/************************************************************** - * - * KonqInfoListViewItem - * - **************************************************************/ -KonqInfoListViewItem::KonqInfoListViewItem( KonqInfoListViewWidget *_widget, KonqInfoListViewItem * _parent, KFileItem* _fileitem ) -:KonqBaseListViewItem( _widget,_parent,_fileitem ), m_ILVWidget(_widget) -{ - updateContents(); -} - -KonqInfoListViewItem::KonqInfoListViewItem( KonqInfoListViewWidget *_listViewWidget, KFileItem* _fileitem ) -:KonqBaseListViewItem(_listViewWidget,_fileitem), m_ILVWidget(_listViewWidget) -{ - updateContents(); -} - -void KonqInfoListViewItem::updateContents() -{ - // Set the pixmap - setDisabled( m_bDisabled ); - - // Set the text of each column - setText(0,m_fileitem->text()); - -#if 0 - if (S_ISDIR(m_fileitem->mode())) - sortChar='0'; - //now we have the first column, so let's do the rest - - for (unsigned int i=0; i(listView())->columnConfigInfo()[i]; - if (tmpColumn->displayThisOne) - { - switch (tmpColumn->udsId) - { - case TDEIO::UDS_USER: - setText(tmpColumn->displayInColumn,m_fileitem->user()); - break; - case TDEIO::UDS_GROUP: - setText(tmpColumn->displayInColumn,m_fileitem->group()); - break; - case TDEIO::UDS_FILE_TYPE: - setText(tmpColumn->displayInColumn,m_fileitem->mimeComment()); - break; - case TDEIO::UDS_MIME_TYPE: - setText(tmpColumn->displayInColumn,m_fileitem->mimetype()); - break; - case TDEIO::UDS_URL: - setText(tmpColumn->displayInColumn,m_fileitem->url().prettyURL()); - break; - case TDEIO::UDS_LINK_DEST: - setText(tmpColumn->displayInColumn,m_fileitem->linkDest()); - break; - case TDEIO::UDS_SIZE: - if ( static_cast(listView())->m_pSettings->fileSizeInBytes() ) - setText(tmpColumn->displayInColumn,TDEGlobal::locale()->formatNumber( m_fileitem->size(),0)+" "); - else - setText(tmpColumn->displayInColumn,TDEIO::convertSize(m_fileitem->size())+" "); - break; - case TDEIO::UDS_ACCESS: - setText(tmpColumn->displayInColumn,m_fileitem->permissionsString()); - break; - case TDEIO::UDS_MODIFICATION_TIME: - case TDEIO::UDS_ACCESS_TIME: - case TDEIO::UDS_CREATION_TIME: - { - TQDateTime dt; - time_t _time = m_fileitem->time( tmpColumn->udsId ); - if ( _time != 0 ) - { - dt.setTime_t( _time ); - setText(tmpColumn->displayInColumn,TDEGlobal::locale()->formatDateTime(dt)); - } - } - break; - default: - break; - }; - }; - }; -#endif -} - -void KonqInfoListViewItem::gotMetaInfo() -{ - KFileMetaInfo info = item()->metaInfo(false); - - if (!info.isValid()) return; - - TQStringList::ConstIterator it = m_ILVWidget->columnKeys().begin(); - for (int i = 1; it != m_ILVWidget->columnKeys().end(); ++it, ++i) - { - KFileMetaInfoItem kfmii = info.item(*it); - - m_columnTypes.append(kfmii.type()); - m_columnValues.append(kfmii.value()); - - if (!kfmii.isValid()) - continue; - - TQString s = kfmii.string().simplifyWhiteSpace(); - setText(i, s.isNull() ? TQString("") : s); - } -} - -int KonqInfoListViewItem::compare( TQListViewItem *item, int col, bool ascending ) const -{ - if ( col == 0 ) - return KonqBaseListViewItem::compare( item, 0, ascending ); - - KonqInfoListViewItem *i = static_cast(item); - - int size1 = m_columnValues.size(); - int size2 = i->m_columnValues.size(); - - if ( size1 < col || size2 < col ) - return ascending ? ( size2 - size1 ) : ( size1 - size2 ); - - TQVariant value1 = m_columnValues[ col-1 ]; - TQVariant value2 = i->m_columnValues[ col-1 ]; - TQVariant::Type type1 = m_columnTypes[ col-1 ]; - TQVariant::Type type2 = i->m_columnTypes[ col-1 ]; - - if ( type1 != type2 ) - return ascending ? ( type1 - type2 ) : ( type2 - type1 ); - -#define KONQ_CASE( x ) \ - case TQVariant::x:\ - return ( value1.to##x() > value2.to##x() ) ? 1 : ( value1.to##x() == value2.to##x() ) ? 0 : -1; - - switch( type1 ) { - KONQ_CASE( Bool ) - KONQ_CASE( Int ) - KONQ_CASE( LongLong ) - KONQ_CASE( UInt ) - KONQ_CASE( ULongLong ) - KONQ_CASE( Double ) - KONQ_CASE( Date ) - KONQ_CASE( Time ) - KONQ_CASE( DateTime ) - case TQVariant::Size: - { - int w1 = value1.toSize().width(); - int w2 = value2.toSize().width(); - if ( w1 != w2 ) - return ( w1 > w2 ) ? 1 : -1; - int h1 = value1.toSize().height(); - int h2 = value2.toSize().height(); - return ( h1 > h2 ) ? 1 : ( h1 == h2 ) ? 0 : -1; - } - default: - break; - } -#undef KONQ_CASE - - TQString text1 = text(col); - TQString text2 = i->text(col); - - if ( text1.isEmpty() ) - return ascending ? 1 : -1; - if ( text2.isEmpty() ) - return ascending ? -1 : 1; - - return text1.lower().localeAwareCompare(text2.lower()); -} - -void KonqInfoListViewItem::setDisabled( bool disabled ) -{ - KonqBaseListViewItem::setDisabled( disabled ); - int iconSize = static_cast(listView())->iconSize(); - iconSize = iconSize ? iconSize : TDEGlobal::iconLoader()->currentSize( TDEIcon::Small ); // Default = small - setPixmap( 0, m_fileitem->pixmap( iconSize, state() ) ); -} - -void KonqInfoListViewItem::paintCell( TQPainter *_painter, const TQColorGroup & _cg, int _column, int _width, int _alignment ) -{ - TQColorGroup cg( _cg ); - - if ( _column == 0 ) - { - _painter->setFont( m_pListViewWidget->itemFont() ); - } - - cg.setColor( TQColorGroup::Text, m_pListViewWidget->itemColor() ); - - TDEListView *lv = static_cast< TDEListView* >( listView() ); - const TQPixmap *pm = TQT_TQPIXMAP_CONST(lv->viewport()->paletteBackgroundPixmap()); - if ( _column == 0 && isSelected() && !lv->allColumnsShowFocus() ) - { - int newWidth = width( lv->fontMetrics(), lv, _column ); - if ( newWidth > _width ) - newWidth = _width; - if ( pm && !pm->isNull() ) - { - cg.setBrush( TQColorGroup::Base, TQBrush( backgroundColor(_column), *pm ) ); - TQPoint o = _painter->brushOrigin(); - _painter->setBrushOrigin( o.x() - lv->contentsX(), o.y() - lv->contentsY() ); - const TQColorGroup::ColorRole crole = - TQPalette::backgroundRoleFromMode( lv->viewport()->backgroundMode() ); - _painter->fillRect( newWidth, 0, _width - newWidth, height(), cg.brush( crole ) ); - _painter->setBrushOrigin( o ); - } - else - { - _painter->fillRect( newWidth, 0, _width - newWidth, height(), backgroundColor(_column) ); - } - - _width = newWidth; - } - - TDEListViewItem::paintCell( _painter, cg, _column, _width, _alignment ); -} - -void KonqInfoListViewItem::paintFocus( TQPainter * _painter, const TQColorGroup & cg, const TQRect & _r ) -{ - TQRect r( _r ); - TQListView *lv = static_cast< TQListView * >( listView() ); - r.setWidth( width( lv->fontMetrics(), lv, 0 ) ); - if ( r.right() > lv->header()->sectionRect( 0 ).right() ) - r.setRight( lv->header()->sectionRect( 0 ).right() ); - TQListViewItem::paintFocus( _painter, cg, r ); -} - -void KonqInfoListViewItem::mimetypeFound() -{ -#if 0 - // Update icon - setDisabled( m_bDisabled ); - uint done = 0; - KonqBaseListViewWidget * lv = m_pListViewWidget; - for (unsigned int i=0; iNumberOfAtoms && done < 2; i++) - { - ColumnInfo *tmpColumn=&lv->columnConfigInfo()[i]; - if (lv->columnConfigInfo()[i].udsId==TDEIO::UDS_FILE_TYPE && tmpColumn->displayThisOne) - { - setText(tmpColumn->displayInColumn, m_fileitem->mimeComment()); - done++; - } - if (lv->columnConfigInfo()[i].udsId==TDEIO::UDS_MIME_TYPE && tmpColumn->displayThisOne) - { - setText(tmpColumn->displayInColumn, m_fileitem->mimetype()); - done++; - } - } -#endif -} diff --git a/konqueror/listview/konq_infolistviewitem.cpp b/konqueror/listview/konq_infolistviewitem.cpp new file mode 100644 index 000000000..18efb3f8f --- /dev/null +++ b/konqueror/listview/konq_infolistviewitem.cpp @@ -0,0 +1,280 @@ +/* This file is part of the KDE project + Copyright (C) 2002 Rolf Magnus + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation version 2.0 + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. + +*/ + +#include "konq_listview.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "konq_infolistviewitem.h" +#include "konq_infolistviewwidget.h" + +/************************************************************** + * + * KonqInfoListViewItem + * + **************************************************************/ +KonqInfoListViewItem::KonqInfoListViewItem( KonqInfoListViewWidget *_widget, KonqInfoListViewItem * _parent, KFileItem* _fileitem ) +:KonqBaseListViewItem( _widget,_parent,_fileitem ), m_ILVWidget(_widget) +{ + updateContents(); +} + +KonqInfoListViewItem::KonqInfoListViewItem( KonqInfoListViewWidget *_listViewWidget, KFileItem* _fileitem ) +:KonqBaseListViewItem(_listViewWidget,_fileitem), m_ILVWidget(_listViewWidget) +{ + updateContents(); +} + +void KonqInfoListViewItem::updateContents() +{ + // Set the pixmap + setDisabled( m_bDisabled ); + + // Set the text of each column + setText(0,m_fileitem->text()); + +#if 0 + if (S_ISDIR(m_fileitem->mode())) + sortChar='0'; + //now we have the first column, so let's do the rest + + for (unsigned int i=0; i(listView())->columnConfigInfo()[i]; + if (tmpColumn->displayThisOne) + { + switch (tmpColumn->udsId) + { + case TDEIO::UDS_USER: + setText(tmpColumn->displayInColumn,m_fileitem->user()); + break; + case TDEIO::UDS_GROUP: + setText(tmpColumn->displayInColumn,m_fileitem->group()); + break; + case TDEIO::UDS_FILE_TYPE: + setText(tmpColumn->displayInColumn,m_fileitem->mimeComment()); + break; + case TDEIO::UDS_MIME_TYPE: + setText(tmpColumn->displayInColumn,m_fileitem->mimetype()); + break; + case TDEIO::UDS_URL: + setText(tmpColumn->displayInColumn,m_fileitem->url().prettyURL()); + break; + case TDEIO::UDS_LINK_DEST: + setText(tmpColumn->displayInColumn,m_fileitem->linkDest()); + break; + case TDEIO::UDS_SIZE: + if ( static_cast(listView())->m_pSettings->fileSizeInBytes() ) + setText(tmpColumn->displayInColumn,TDEGlobal::locale()->formatNumber( m_fileitem->size(),0)+" "); + else + setText(tmpColumn->displayInColumn,TDEIO::convertSize(m_fileitem->size())+" "); + break; + case TDEIO::UDS_ACCESS: + setText(tmpColumn->displayInColumn,m_fileitem->permissionsString()); + break; + case TDEIO::UDS_MODIFICATION_TIME: + case TDEIO::UDS_ACCESS_TIME: + case TDEIO::UDS_CREATION_TIME: + { + TQDateTime dt; + time_t _time = m_fileitem->time( tmpColumn->udsId ); + if ( _time != 0 ) + { + dt.setTime_t( _time ); + setText(tmpColumn->displayInColumn,TDEGlobal::locale()->formatDateTime(dt)); + } + } + break; + default: + break; + }; + }; + }; +#endif +} + +void KonqInfoListViewItem::gotMetaInfo() +{ + KFileMetaInfo info = item()->metaInfo(false); + + if (!info.isValid()) return; + + TQStringList::ConstIterator it = m_ILVWidget->columnKeys().begin(); + for (int i = 1; it != m_ILVWidget->columnKeys().end(); ++it, ++i) + { + KFileMetaInfoItem kfmii = info.item(*it); + + m_columnTypes.append(kfmii.type()); + m_columnValues.append(kfmii.value()); + + if (!kfmii.isValid()) + continue; + + TQString s = kfmii.string().simplifyWhiteSpace(); + setText(i, s.isNull() ? TQString("") : s); + } +} + +int KonqInfoListViewItem::compare( TQListViewItem *item, int col, bool ascending ) const +{ + if ( col == 0 ) + return KonqBaseListViewItem::compare( item, 0, ascending ); + + KonqInfoListViewItem *i = static_cast(item); + + int size1 = m_columnValues.size(); + int size2 = i->m_columnValues.size(); + + if ( size1 < col || size2 < col ) + return ascending ? ( size2 - size1 ) : ( size1 - size2 ); + + TQVariant value1 = m_columnValues[ col-1 ]; + TQVariant value2 = i->m_columnValues[ col-1 ]; + TQVariant::Type type1 = m_columnTypes[ col-1 ]; + TQVariant::Type type2 = i->m_columnTypes[ col-1 ]; + + if ( type1 != type2 ) + return ascending ? ( type1 - type2 ) : ( type2 - type1 ); + +#define KONQ_CASE( x ) \ + case TQVariant::x:\ + return ( value1.to##x() > value2.to##x() ) ? 1 : ( value1.to##x() == value2.to##x() ) ? 0 : -1; + + switch( type1 ) { + KONQ_CASE( Bool ) + KONQ_CASE( Int ) + KONQ_CASE( LongLong ) + KONQ_CASE( UInt ) + KONQ_CASE( ULongLong ) + KONQ_CASE( Double ) + KONQ_CASE( Date ) + KONQ_CASE( Time ) + KONQ_CASE( DateTime ) + case TQVariant::Size: + { + int w1 = value1.toSize().width(); + int w2 = value2.toSize().width(); + if ( w1 != w2 ) + return ( w1 > w2 ) ? 1 : -1; + int h1 = value1.toSize().height(); + int h2 = value2.toSize().height(); + return ( h1 > h2 ) ? 1 : ( h1 == h2 ) ? 0 : -1; + } + default: + break; + } +#undef KONQ_CASE + + TQString text1 = text(col); + TQString text2 = i->text(col); + + if ( text1.isEmpty() ) + return ascending ? 1 : -1; + if ( text2.isEmpty() ) + return ascending ? -1 : 1; + + return text1.lower().localeAwareCompare(text2.lower()); +} + +void KonqInfoListViewItem::setDisabled( bool disabled ) +{ + KonqBaseListViewItem::setDisabled( disabled ); + int iconSize = static_cast(listView())->iconSize(); + iconSize = iconSize ? iconSize : TDEGlobal::iconLoader()->currentSize( TDEIcon::Small ); // Default = small + setPixmap( 0, m_fileitem->pixmap( iconSize, state() ) ); +} + +void KonqInfoListViewItem::paintCell( TQPainter *_painter, const TQColorGroup & _cg, int _column, int _width, int _alignment ) +{ + TQColorGroup cg( _cg ); + + if ( _column == 0 ) + { + _painter->setFont( m_pListViewWidget->itemFont() ); + } + + cg.setColor( TQColorGroup::Text, m_pListViewWidget->itemColor() ); + + TDEListView *lv = static_cast< TDEListView* >( listView() ); + const TQPixmap *pm = TQT_TQPIXMAP_CONST(lv->viewport()->paletteBackgroundPixmap()); + if ( _column == 0 && isSelected() && !lv->allColumnsShowFocus() ) + { + int newWidth = width( lv->fontMetrics(), lv, _column ); + if ( newWidth > _width ) + newWidth = _width; + if ( pm && !pm->isNull() ) + { + cg.setBrush( TQColorGroup::Base, TQBrush( backgroundColor(_column), *pm ) ); + TQPoint o = _painter->brushOrigin(); + _painter->setBrushOrigin( o.x() - lv->contentsX(), o.y() - lv->contentsY() ); + const TQColorGroup::ColorRole crole = + TQPalette::backgroundRoleFromMode( lv->viewport()->backgroundMode() ); + _painter->fillRect( newWidth, 0, _width - newWidth, height(), cg.brush( crole ) ); + _painter->setBrushOrigin( o ); + } + else + { + _painter->fillRect( newWidth, 0, _width - newWidth, height(), backgroundColor(_column) ); + } + + _width = newWidth; + } + + TDEListViewItem::paintCell( _painter, cg, _column, _width, _alignment ); +} + +void KonqInfoListViewItem::paintFocus( TQPainter * _painter, const TQColorGroup & cg, const TQRect & _r ) +{ + TQRect r( _r ); + TQListView *lv = static_cast< TQListView * >( listView() ); + r.setWidth( width( lv->fontMetrics(), lv, 0 ) ); + if ( r.right() > lv->header()->sectionRect( 0 ).right() ) + r.setRight( lv->header()->sectionRect( 0 ).right() ); + TQListViewItem::paintFocus( _painter, cg, r ); +} + +void KonqInfoListViewItem::mimetypeFound() +{ +#if 0 + // Update icon + setDisabled( m_bDisabled ); + uint done = 0; + KonqBaseListViewWidget * lv = m_pListViewWidget; + for (unsigned int i=0; iNumberOfAtoms && done < 2; i++) + { + ColumnInfo *tmpColumn=&lv->columnConfigInfo()[i]; + if (lv->columnConfigInfo()[i].udsId==TDEIO::UDS_FILE_TYPE && tmpColumn->displayThisOne) + { + setText(tmpColumn->displayInColumn, m_fileitem->mimeComment()); + done++; + } + if (lv->columnConfigInfo()[i].udsId==TDEIO::UDS_MIME_TYPE && tmpColumn->displayThisOne) + { + setText(tmpColumn->displayInColumn, m_fileitem->mimetype()); + done++; + } + } +#endif +} diff --git a/konqueror/listview/konq_infolistviewwidget.cc b/konqueror/listview/konq_infolistviewwidget.cc deleted file mode 100644 index e835f1cb3..000000000 --- a/konqueror/listview/konq_infolistviewwidget.cc +++ /dev/null @@ -1,384 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2002 Rolf Magnus - Copyright (C) 2003 Waldo Bastian - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation version 2.0 - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ -#include "konq_infolistviewwidget.h" -#include "konq_infolistviewwidget.moc" -#include "konq_infolistviewitem.h" -#include "konq_listview.h" - -#include -#include -#include -#include -#include -#include -#include - -#include - -KonqInfoListViewWidget::KonqInfoListViewWidget( KonqListView* parent, - TQWidget* parentWidget) - : KonqBaseListViewWidget(parent, parentWidget) -{ - m_metaInfoJob = 0; - - m_mtSelector = new TDESelectAction(i18n("View &As"), 0, TQT_TQOBJECT(this), - TQT_SLOT(slotSelectMimeType()), - parent->actionCollection(), "view_as" ); - - kdDebug(1203) << "created info list view\n"; -} - -KonqInfoListViewWidget::~KonqInfoListViewWidget() -{ - delete m_mtSelector; - delete m_metaInfoJob; -} - -void KonqInfoListViewWidget::slotSelectMimeType() -{ - TQString comment = m_mtSelector->currentText(); - - // find the mime type by comment - TQMapIterator it; - for (it = m_counts.begin(); it!=m_counts.end(); ++it) - { - if ((*it).mimetype->comment() == comment) - { - m_favorite = *it; - createFavoriteColumns(); - rebuildView(); - break; - } - } - -} - -void KonqInfoListViewWidget::createColumns() -{ - if (columns()<1) - { - // we can only create the minimum columns here, because we don't get the - // items, from which we determine the columns yet. - addColumn(i18n("Filename"), m_filenameColumnWidth); - } -} - -void KonqInfoListViewWidget::createFavoriteColumns() -{ - while (columns()>1) - { - kdDebug(1203) << "removing column " << columnText(columns()-1) << endl; - removeColumn(columns()-1); - } - - // we need to get the preferred keys of the favorite - const KFileMimeTypeInfo* mimeTypeInfo; - - if (m_favorite.mimetype && - (mimeTypeInfo = KFileMetaInfoProvider::self() - ->mimeTypeInfo(m_favorite.mimetype->name()))) - { - TQStringList preferredCols = mimeTypeInfo->preferredKeys(); - m_columnKeys.clear(); //We create the columnKeys as we're creating - //the actual columns, to make sure they're synced - - // get the translations - TQStringList groups = mimeTypeInfo->preferredGroups(); - if (groups.isEmpty()) groups = mimeTypeInfo->supportedGroups(); - - TQStringList::Iterator prefKey = preferredCols.begin(); - for (; prefKey != preferredCols.end(); ++prefKey) - { - TQStringList::Iterator group = groups.begin(); - for (; group != groups.end(); ++group) - { - const KFileMimeTypeInfo::GroupInfo* groupInfo = - mimeTypeInfo->groupInfo(*group); - if(groupInfo) - { - TQStringList keys = groupInfo->supportedKeys(); - TQStringList::Iterator key = keys.begin(); - for (; key != keys.end(); ++key) - { - if ( *key == *prefKey ) - { - const KFileMimeTypeInfo::ItemInfo* itemInfo = - groupInfo->itemInfo(*key); - addColumn(itemInfo->translatedKey()); - m_columnKeys.append(*key); - } - } - } - } - } - } - else - { - KonqBaseListViewWidget::createColumns(); - } - -} - -bool KonqInfoListViewWidget::openURL( const KURL &url ) -{ - bool ret = KonqBaseListViewWidget::openURL(url); - m_bTopLevelComplete = true; - return ret; -} - -void KonqInfoListViewWidget::rebuildView() -{ - // make a KFileItemList from all our Items - KFileItemList list; - - TQListViewItemIterator it(this); - for (; it.current(); ++it) - { - list.append(static_cast(it.current())->item()); - } - - // now we can remove all the listview items - clear(); - - // and rebuild them - for (TQPtrListIterator kit(list); kit.current(); ++kit) - { - KonqInfoListViewItem* tmp = new KonqInfoListViewItem( this, *kit ); -// if (m_goToFirstItem==false) -// if (m_itemFound==false) -// if (tmp->text(0)==m_itemToGoTo) -// { -//kdDebug() << "Line " << __LINE__ << endl; -// setCurrentItem(tmp); -//kdDebug() << "Line " << __LINE__ << endl; -// ensureItemVisible(tmp); -//kdDebug() << "Line " << __LINE__ << endl; -// emit selectionChanged(); - //selectCurrentItemAndEnableSelectedBySimpleMoveMode(); -// m_itemFound=true; -//kdDebug() << "Line " << __LINE__ << endl; -// }; - - tmp->gotMetaInfo(); - } - - - if ( !viewport()->isUpdatesEnabled() ) - { - viewport()->setUpdatesEnabled( true ); - setUpdatesEnabled( true ); - triggerUpdate(); - } -} - -void KonqInfoListViewWidget::slotNewItems( const KFileItemList& list) -{ - slotStarted(); // ############# WHY? - for (TQPtrListIterator kit ( list ); kit.current(); ++kit ) - { - KonqInfoListViewItem * tmp = new KonqInfoListViewItem( this, *kit ); - - if (!m_itemFound && tmp->text(0)==m_itemToGoTo) - { - setCurrentItem(tmp); - m_itemFound=true; - } - - if ( !m_itemsToSelect.isEmpty() ) { - TQStringList::Iterator tsit = m_itemsToSelect.find( (*kit)->name() ); - if ( tsit != m_itemsToSelect.end() ) { - m_itemsToSelect.remove( tsit ); - setSelected( tmp, true ); - } - } - - if ( !(*kit)->isMimeTypeKnown() ) { - m_pBrowserView->lstPendingMimeIconItems().append( tmp ); - } - } - m_pBrowserView->newItems( list ); - - if ( !viewport()->isUpdatesEnabled() ) - { - viewport()->setUpdatesEnabled( true ); - setUpdatesEnabled( true ); - triggerUpdate(); - } - - slotUpdateBackground(); - - if ( !m_favorite.mimetype ) - determineCounts(list); - - kdDebug(1203) << " ------------------------ startin metainfo job ------\n"; - - // start getting metainfo from the files - if (m_metaInfoJob) - { - for (TQPtrListIterator kit ( list ); kit.current(); ++kit ) - m_metaInfoTodo.append(kit.current()); - } - else - { - m_metaInfoJob = TDEIO::fileMetaInfo(list); - connect( m_metaInfoJob, TQT_SIGNAL( gotMetaInfo( const KFileItem*)), - this, TQT_SLOT( slotMetaInfo( const KFileItem*))); - connect( m_metaInfoJob, TQT_SIGNAL( result( TDEIO::Job*)), - this, TQT_SLOT( slotMetaInfoResult())); - } -} - -void KonqInfoListViewWidget::slotRefreshItems( const KFileItemList& list) -{ - kdDebug(1203) << " ------------------------ startin metainfo job ------\n"; - - // start getting metainfo from the files - if (m_metaInfoJob) - { - for (TQPtrListIterator kit ( list ); kit.current(); ++kit ) - m_metaInfoTodo.append(kit.current()); - } - else - { - m_metaInfoJob = TDEIO::fileMetaInfo(list); - connect( m_metaInfoJob, TQT_SIGNAL( gotMetaInfo( const KFileItem*)), - this, TQT_SLOT( slotMetaInfo( const KFileItem*))); - connect( m_metaInfoJob, TQT_SIGNAL( result( TDEIO::Job*)), - this, TQT_SLOT( slotMetaInfoResult())); - } - KonqBaseListViewWidget::slotRefreshItems(list); -} - -void KonqInfoListViewWidget::slotDeleteItem( KFileItem * item ) -{ - m_metaInfoTodo.removeRef(item); - if (m_metaInfoJob) - m_metaInfoJob->removeItem(item); - - KonqBaseListViewWidget::slotDeleteItem(item); -} - -void KonqInfoListViewWidget::slotClear() -{ - m_metaInfoTodo.clear(); - delete m_metaInfoJob; - m_metaInfoJob = 0; - m_favorite = KonqILVMimeType(); - - KonqBaseListViewWidget::slotClear(); -} - -void KonqInfoListViewWidget::slotMetaInfo(const KFileItem* item) -{ - // need to search for the item (any better way?) - TQListViewItemIterator it(this); - for (; it.current(); ++it) - { - if (static_cast(it.current())->item()==item) - { - static_cast(it.current())->gotMetaInfo(); - return; - } - } - - // we should never reach this place - Q_ASSERT(false); -} - -void KonqInfoListViewWidget::slotMetaInfoResult() -{ - m_metaInfoJob = 0; - if (m_metaInfoTodo.isEmpty()) - { - m_bTopLevelComplete = false; - kdDebug(1203) << "emitting completed!!!!!!!!!!!!!!!!\n"; - slotCompleted(); - } - else - { - m_metaInfoJob = TDEIO::fileMetaInfo(m_metaInfoTodo); - connect( m_metaInfoJob, TQT_SIGNAL( gotMetaInfo( const KFileItem*)), - this, TQT_SLOT( slotMetaInfo( const KFileItem*))); - connect( m_metaInfoJob, TQT_SIGNAL( result( TDEIO::Job*)), - this, TQT_SLOT( slotMetaInfoResult())); - m_metaInfoTodo.clear(); - } -} - -void KonqInfoListViewWidget::determineCounts(const KFileItemList& list) -{ - m_counts.clear(); - m_favorite = KonqILVMimeType(); - // get the counts - for (KFileItemListIterator it(list); it.current(); ++it) - { - TQString mt = it.current()->mimetype(); - m_counts[mt].count++; - if (!m_counts[mt].mimetype) - m_counts[mt].mimetype = it.current()->determineMimeType(); - } - - // and look for the plugins - kdDebug(1203) << "counts are:\n"; - - KFileMetaInfoProvider* prov = KFileMetaInfoProvider::self(); - - TQStringList mtlist; - - TQMapIterator it; - for (it = m_counts.begin(); it!=m_counts.end(); ++it) - { - // look if there is a plugin for this mimetype - // and look for the "favorite" mimetype -#ifdef _GNUC -#warning ### change this -#endif - // this will load the plugin which we don't need because we delegate - // the job to the tdeioslave - (*it).hasPlugin = prov->plugin(it.key()); - - if ( (*it).hasPlugin) - { - mtlist << (*it).mimetype->comment(); - if (m_favorite.count <= (*it).count) - m_favorite = *it; - } - - kdDebug(1203) << it.key() << " -> " << (*it).count - << " item(s) / plugin: " - << ((*it).hasPlugin ? "yes" : "no ") << endl; - } - - m_mtSelector->setItems(mtlist); -// TQPopupMenu* menu = m_mtSelector->popupMenu(); - - // insert the icons -// for (int i=0; icount(); ++i) -// { -// menu->changeItem(i, TQIconSet(blah)); -// } - - if (m_favorite.mimetype) - { - m_mtSelector->setCurrentItem(mtlist.findIndex(m_favorite.mimetype->comment())); - kdDebug(1203) << "favorite mimetype is " << m_favorite.mimetype->name() << endl; - } - createFavoriteColumns(); -} - diff --git a/konqueror/listview/konq_infolistviewwidget.cpp b/konqueror/listview/konq_infolistviewwidget.cpp new file mode 100644 index 000000000..e835f1cb3 --- /dev/null +++ b/konqueror/listview/konq_infolistviewwidget.cpp @@ -0,0 +1,384 @@ +/* This file is part of the KDE project + Copyright (C) 2002 Rolf Magnus + Copyright (C) 2003 Waldo Bastian + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation version 2.0 + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ +#include "konq_infolistviewwidget.h" +#include "konq_infolistviewwidget.moc" +#include "konq_infolistviewitem.h" +#include "konq_listview.h" + +#include +#include +#include +#include +#include +#include +#include + +#include + +KonqInfoListViewWidget::KonqInfoListViewWidget( KonqListView* parent, + TQWidget* parentWidget) + : KonqBaseListViewWidget(parent, parentWidget) +{ + m_metaInfoJob = 0; + + m_mtSelector = new TDESelectAction(i18n("View &As"), 0, TQT_TQOBJECT(this), + TQT_SLOT(slotSelectMimeType()), + parent->actionCollection(), "view_as" ); + + kdDebug(1203) << "created info list view\n"; +} + +KonqInfoListViewWidget::~KonqInfoListViewWidget() +{ + delete m_mtSelector; + delete m_metaInfoJob; +} + +void KonqInfoListViewWidget::slotSelectMimeType() +{ + TQString comment = m_mtSelector->currentText(); + + // find the mime type by comment + TQMapIterator it; + for (it = m_counts.begin(); it!=m_counts.end(); ++it) + { + if ((*it).mimetype->comment() == comment) + { + m_favorite = *it; + createFavoriteColumns(); + rebuildView(); + break; + } + } + +} + +void KonqInfoListViewWidget::createColumns() +{ + if (columns()<1) + { + // we can only create the minimum columns here, because we don't get the + // items, from which we determine the columns yet. + addColumn(i18n("Filename"), m_filenameColumnWidth); + } +} + +void KonqInfoListViewWidget::createFavoriteColumns() +{ + while (columns()>1) + { + kdDebug(1203) << "removing column " << columnText(columns()-1) << endl; + removeColumn(columns()-1); + } + + // we need to get the preferred keys of the favorite + const KFileMimeTypeInfo* mimeTypeInfo; + + if (m_favorite.mimetype && + (mimeTypeInfo = KFileMetaInfoProvider::self() + ->mimeTypeInfo(m_favorite.mimetype->name()))) + { + TQStringList preferredCols = mimeTypeInfo->preferredKeys(); + m_columnKeys.clear(); //We create the columnKeys as we're creating + //the actual columns, to make sure they're synced + + // get the translations + TQStringList groups = mimeTypeInfo->preferredGroups(); + if (groups.isEmpty()) groups = mimeTypeInfo->supportedGroups(); + + TQStringList::Iterator prefKey = preferredCols.begin(); + for (; prefKey != preferredCols.end(); ++prefKey) + { + TQStringList::Iterator group = groups.begin(); + for (; group != groups.end(); ++group) + { + const KFileMimeTypeInfo::GroupInfo* groupInfo = + mimeTypeInfo->groupInfo(*group); + if(groupInfo) + { + TQStringList keys = groupInfo->supportedKeys(); + TQStringList::Iterator key = keys.begin(); + for (; key != keys.end(); ++key) + { + if ( *key == *prefKey ) + { + const KFileMimeTypeInfo::ItemInfo* itemInfo = + groupInfo->itemInfo(*key); + addColumn(itemInfo->translatedKey()); + m_columnKeys.append(*key); + } + } + } + } + } + } + else + { + KonqBaseListViewWidget::createColumns(); + } + +} + +bool KonqInfoListViewWidget::openURL( const KURL &url ) +{ + bool ret = KonqBaseListViewWidget::openURL(url); + m_bTopLevelComplete = true; + return ret; +} + +void KonqInfoListViewWidget::rebuildView() +{ + // make a KFileItemList from all our Items + KFileItemList list; + + TQListViewItemIterator it(this); + for (; it.current(); ++it) + { + list.append(static_cast(it.current())->item()); + } + + // now we can remove all the listview items + clear(); + + // and rebuild them + for (TQPtrListIterator kit(list); kit.current(); ++kit) + { + KonqInfoListViewItem* tmp = new KonqInfoListViewItem( this, *kit ); +// if (m_goToFirstItem==false) +// if (m_itemFound==false) +// if (tmp->text(0)==m_itemToGoTo) +// { +//kdDebug() << "Line " << __LINE__ << endl; +// setCurrentItem(tmp); +//kdDebug() << "Line " << __LINE__ << endl; +// ensureItemVisible(tmp); +//kdDebug() << "Line " << __LINE__ << endl; +// emit selectionChanged(); + //selectCurrentItemAndEnableSelectedBySimpleMoveMode(); +// m_itemFound=true; +//kdDebug() << "Line " << __LINE__ << endl; +// }; + + tmp->gotMetaInfo(); + } + + + if ( !viewport()->isUpdatesEnabled() ) + { + viewport()->setUpdatesEnabled( true ); + setUpdatesEnabled( true ); + triggerUpdate(); + } +} + +void KonqInfoListViewWidget::slotNewItems( const KFileItemList& list) +{ + slotStarted(); // ############# WHY? + for (TQPtrListIterator kit ( list ); kit.current(); ++kit ) + { + KonqInfoListViewItem * tmp = new KonqInfoListViewItem( this, *kit ); + + if (!m_itemFound && tmp->text(0)==m_itemToGoTo) + { + setCurrentItem(tmp); + m_itemFound=true; + } + + if ( !m_itemsToSelect.isEmpty() ) { + TQStringList::Iterator tsit = m_itemsToSelect.find( (*kit)->name() ); + if ( tsit != m_itemsToSelect.end() ) { + m_itemsToSelect.remove( tsit ); + setSelected( tmp, true ); + } + } + + if ( !(*kit)->isMimeTypeKnown() ) { + m_pBrowserView->lstPendingMimeIconItems().append( tmp ); + } + } + m_pBrowserView->newItems( list ); + + if ( !viewport()->isUpdatesEnabled() ) + { + viewport()->setUpdatesEnabled( true ); + setUpdatesEnabled( true ); + triggerUpdate(); + } + + slotUpdateBackground(); + + if ( !m_favorite.mimetype ) + determineCounts(list); + + kdDebug(1203) << " ------------------------ startin metainfo job ------\n"; + + // start getting metainfo from the files + if (m_metaInfoJob) + { + for (TQPtrListIterator kit ( list ); kit.current(); ++kit ) + m_metaInfoTodo.append(kit.current()); + } + else + { + m_metaInfoJob = TDEIO::fileMetaInfo(list); + connect( m_metaInfoJob, TQT_SIGNAL( gotMetaInfo( const KFileItem*)), + this, TQT_SLOT( slotMetaInfo( const KFileItem*))); + connect( m_metaInfoJob, TQT_SIGNAL( result( TDEIO::Job*)), + this, TQT_SLOT( slotMetaInfoResult())); + } +} + +void KonqInfoListViewWidget::slotRefreshItems( const KFileItemList& list) +{ + kdDebug(1203) << " ------------------------ startin metainfo job ------\n"; + + // start getting metainfo from the files + if (m_metaInfoJob) + { + for (TQPtrListIterator kit ( list ); kit.current(); ++kit ) + m_metaInfoTodo.append(kit.current()); + } + else + { + m_metaInfoJob = TDEIO::fileMetaInfo(list); + connect( m_metaInfoJob, TQT_SIGNAL( gotMetaInfo( const KFileItem*)), + this, TQT_SLOT( slotMetaInfo( const KFileItem*))); + connect( m_metaInfoJob, TQT_SIGNAL( result( TDEIO::Job*)), + this, TQT_SLOT( slotMetaInfoResult())); + } + KonqBaseListViewWidget::slotRefreshItems(list); +} + +void KonqInfoListViewWidget::slotDeleteItem( KFileItem * item ) +{ + m_metaInfoTodo.removeRef(item); + if (m_metaInfoJob) + m_metaInfoJob->removeItem(item); + + KonqBaseListViewWidget::slotDeleteItem(item); +} + +void KonqInfoListViewWidget::slotClear() +{ + m_metaInfoTodo.clear(); + delete m_metaInfoJob; + m_metaInfoJob = 0; + m_favorite = KonqILVMimeType(); + + KonqBaseListViewWidget::slotClear(); +} + +void KonqInfoListViewWidget::slotMetaInfo(const KFileItem* item) +{ + // need to search for the item (any better way?) + TQListViewItemIterator it(this); + for (; it.current(); ++it) + { + if (static_cast(it.current())->item()==item) + { + static_cast(it.current())->gotMetaInfo(); + return; + } + } + + // we should never reach this place + Q_ASSERT(false); +} + +void KonqInfoListViewWidget::slotMetaInfoResult() +{ + m_metaInfoJob = 0; + if (m_metaInfoTodo.isEmpty()) + { + m_bTopLevelComplete = false; + kdDebug(1203) << "emitting completed!!!!!!!!!!!!!!!!\n"; + slotCompleted(); + } + else + { + m_metaInfoJob = TDEIO::fileMetaInfo(m_metaInfoTodo); + connect( m_metaInfoJob, TQT_SIGNAL( gotMetaInfo( const KFileItem*)), + this, TQT_SLOT( slotMetaInfo( const KFileItem*))); + connect( m_metaInfoJob, TQT_SIGNAL( result( TDEIO::Job*)), + this, TQT_SLOT( slotMetaInfoResult())); + m_metaInfoTodo.clear(); + } +} + +void KonqInfoListViewWidget::determineCounts(const KFileItemList& list) +{ + m_counts.clear(); + m_favorite = KonqILVMimeType(); + // get the counts + for (KFileItemListIterator it(list); it.current(); ++it) + { + TQString mt = it.current()->mimetype(); + m_counts[mt].count++; + if (!m_counts[mt].mimetype) + m_counts[mt].mimetype = it.current()->determineMimeType(); + } + + // and look for the plugins + kdDebug(1203) << "counts are:\n"; + + KFileMetaInfoProvider* prov = KFileMetaInfoProvider::self(); + + TQStringList mtlist; + + TQMapIterator it; + for (it = m_counts.begin(); it!=m_counts.end(); ++it) + { + // look if there is a plugin for this mimetype + // and look for the "favorite" mimetype +#ifdef _GNUC +#warning ### change this +#endif + // this will load the plugin which we don't need because we delegate + // the job to the tdeioslave + (*it).hasPlugin = prov->plugin(it.key()); + + if ( (*it).hasPlugin) + { + mtlist << (*it).mimetype->comment(); + if (m_favorite.count <= (*it).count) + m_favorite = *it; + } + + kdDebug(1203) << it.key() << " -> " << (*it).count + << " item(s) / plugin: " + << ((*it).hasPlugin ? "yes" : "no ") << endl; + } + + m_mtSelector->setItems(mtlist); +// TQPopupMenu* menu = m_mtSelector->popupMenu(); + + // insert the icons +// for (int i=0; icount(); ++i) +// { +// menu->changeItem(i, TQIconSet(blah)); +// } + + if (m_favorite.mimetype) + { + m_mtSelector->setCurrentItem(mtlist.findIndex(m_favorite.mimetype->comment())); + kdDebug(1203) << "favorite mimetype is " << m_favorite.mimetype->name() << endl; + } + createFavoriteColumns(); +} + diff --git a/konqueror/listview/konq_listview.cc b/konqueror/listview/konq_listview.cc deleted file mode 100644 index 67da49c6d..000000000 --- a/konqueror/listview/konq_listview.cc +++ /dev/null @@ -1,731 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 1998, 1999 Torben Weis - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "konq_listview.h" -#include "konq_textviewwidget.h" -#include "konq_treeviewwidget.h" -#include "konq_infolistviewwidget.h" -#include "konq_listviewsettings.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -KonqListViewFactory::KonqListViewFactory() -{ - s_instance = 0; - s_defaultViewProps = 0; -} - -KonqListViewFactory::~KonqListViewFactory() -{ - delete s_instance; - delete s_defaultViewProps; - - s_instance = 0; - s_defaultViewProps = 0; -} - -KParts::Part* KonqListViewFactory::createPartObject( TQWidget *parentWidget, const char *, TQObject *parent, const char *name, const char*, const TQStringList &args ) -{ - if( args.count() < 1 ) - kdWarning() << "KonqListView: Missing Parameter" << endl; - - KParts::Part *obj = new KonqListView( parentWidget, parent, name, args.first() ); - return obj; -} - -TDEInstance *KonqListViewFactory::instance() -{ - if ( !s_instance ) - s_instance = new TDEInstance( "konqlistview" ); - return s_instance; -} - -KonqPropsView *KonqListViewFactory::defaultViewProps() -{ - if ( !s_defaultViewProps ) - s_defaultViewProps = new KonqPropsView( instance(),0L ); - //s_defaultViewProps = KonqPropsView::defaultProps( instance() ); - - return s_defaultViewProps; -} - -TDEInstance *KonqListViewFactory::s_instance = 0; -KonqPropsView *KonqListViewFactory::s_defaultViewProps = 0; - -K_EXPORT_COMPONENT_FACTORY( konq_listview, KonqListViewFactory ) - -ListViewBrowserExtension::ListViewBrowserExtension( KonqListView *listView ) - : KonqDirPartBrowserExtension( listView ) -{ - m_listView = listView; -} - -int ListViewBrowserExtension::xOffset() -{ - //kdDebug(1202) << k_funcinfo << endl; - return m_listView->listViewWidget()->contentsX(); -} - -int ListViewBrowserExtension::yOffset() -{ - //kdDebug(1202) << k_funcinfo << endl; - return m_listView->listViewWidget()->contentsY(); -} - -void ListViewBrowserExtension::updateActions() -{ - // This code is very related to KonqIconViewWidget::slotSelectionChanged - int canCopy = 0; - int canDel = 0; - int canTrash = 0; - bool bInTrash = false; - KFileItemList lstItems = m_listView->selectedFileItems(); - - for (KFileItem *item = lstItems.first(); item; item = lstItems.next()) - { - canCopy++; - KURL url = item->url(); - if ( url.directory(false) == TDEGlobalSettings::trashPath() ) - bInTrash = true; - if ( KProtocolInfo::supportsDeleting( url ) ) - canDel++; - if ( !item->localPath().isEmpty() ) - canTrash++; - } - - emit enableAction( "copy", canCopy > 0 ); - emit enableAction( "cut", canDel > 0 ); - emit enableAction( "trash", canDel > 0 && !bInTrash && canDel == canTrash ); - emit enableAction( "del", canDel > 0 ); - emit enableAction( "properties", lstItems.count() > 0 && KPropertiesDialog::canDisplay( lstItems ) ); - emit enableAction( "editMimeType", ( lstItems.count() == 1 ) ); - emit enableAction( "rename", ( m_listView->listViewWidget()->currentItem() != 0 ) && !bInTrash ); -} - -void ListViewBrowserExtension::copySelection( bool move ) -{ - KonqDrag *urlData = new KonqDrag( m_listView->listViewWidget()->selectedUrls(false), m_listView->listViewWidget()->selectedUrls(true), move ); - TQApplication::clipboard()->setData( urlData ); -} - -void ListViewBrowserExtension::paste() -{ - KonqOperations::doPaste( m_listView->listViewWidget(), m_listView->url() ); -} - -void ListViewBrowserExtension::pasteTo( const KURL& url ) -{ - KonqOperations::doPaste( m_listView->listViewWidget(), url ); -} - -void ListViewBrowserExtension::rename() -{ - TQListViewItem* item = m_listView->listViewWidget()->currentItem(); - Q_ASSERT ( item ); - - // Update shurtcuts for the 'rename and move' actions. Must be done every time since the - // shortcuts may have been changed by the user in the meanwhile - const TDEShortcut moveNextSC=m_listView->m_paRenameMoveNext->shortcut(); - const TDEShortcut movePrevSC=m_listView->m_paRenameMovePrev->shortcut(); - m_listView->listViewWidget()->setRenameSettings(TDEListViewRenameSettings( - !(moveNextSC.isNull() && movePrevSC.isNull()), moveNextSC, movePrevSC)); - - m_listView->listViewWidget()->rename( item, 0 ); - - // Enhanced rename: Don't highlight the file extension. - KLineEdit* le = m_listView->listViewWidget()->renameLineEdit(); - if ( le ) { - const TQString txt = le->text(); - TQString pattern; - KMimeType::diagnoseFileName( txt, pattern ); - if (!pattern.isEmpty() && pattern.at(0)=='*' && pattern.find('*',1)==-1) - le->setSelection(0, txt.length()-pattern.stripWhiteSpace().length()+1); - else - { - int lastDot = txt.findRev('.'); - if (lastDot > 0) - le->setSelection(0, lastDot); - } - } -} - -void ListViewBrowserExtension::trash() -{ - KonqOperations::del(m_listView->listViewWidget(), - KonqOperations::TRASH, - m_listView->listViewWidget()->selectedUrls( true )); -} - -void ListViewBrowserExtension::reparseConfiguration() -{ - // m_pProps is a problem here (what is local, what is global ?) - // but settings is easy : - m_listView->listViewWidget()->initConfig(); -} - -void ListViewBrowserExtension::setSaveViewPropertiesLocally(bool value) -{ - m_listView->props()->setSaveViewPropertiesLocally( value ); -} - -void ListViewBrowserExtension::setNameFilter( const TQString &nameFilter ) -{ - m_listView->setNameFilter( nameFilter ); -} - -void ListViewBrowserExtension::properties() -{ - (void) new KPropertiesDialog( m_listView->selectedFileItems() ); -} - -void ListViewBrowserExtension::editMimeType() -{ - KFileItemList items = m_listView->selectedFileItems(); - assert ( items.count() == 1 ); - KonqOperations::editMimeType( items.first()->mimetype() ); -} - -KonqListView::KonqListView( TQWidget *parentWidget, TQObject *parent, const char *name, const TQString& mode ) - : KonqDirPart( parent, name ) -,m_headerTimer(0) -{ - setInstance( KonqListViewFactory::instance(), false ); - - // Create a properties instance for this view - // All the listview view modes inherit the same properties defaults... - m_pProps = new KonqPropsView( KonqListViewFactory::instance(), KonqListViewFactory::defaultViewProps() ); - - setBrowserExtension( new ListViewBrowserExtension( this ) ); - - TQString xmlFile; - - if (mode=="TextView") - { - kdDebug(1202) << "Creating KonqTextViewWidget" << endl; - xmlFile = "konq_textview.rc"; - m_pListView=new KonqTextViewWidget(this, parentWidget); - } - else if (mode=="MixedTree") - { - kdDebug(1202) << "Creating KonqTreeViewWidget" << endl; - xmlFile = "konq_treeview.rc"; - m_pListView=new KonqTreeViewWidget(this,parentWidget); - } - else if (mode=="InfoListView") - { - kdDebug(1202) << "Creating KonqInfoListViewWidget" << endl; - xmlFile = "konq_infolistview.rc"; - m_pListView=new KonqInfoListViewWidget(this,parentWidget); - } - else - { - kdDebug(1202) << "Creating KonqDetailedListViewWidget" << endl; - xmlFile = "konq_detailedlistview.rc"; - m_pListView = new KonqBaseListViewWidget( this, parentWidget); - } - setWidget( m_pListView ); - setDirLister( m_pListView->m_dirLister ); - - m_mimeTypeResolver = new KMimeTypeResolver(this); - - setXMLFile( xmlFile ); - - setupActions(); - - m_pListView->confColumns.resize( 11 ); - m_pListView->confColumns[0].setData(I18N_NOOP("MimeType"),"Type",TDEIO::UDS_MIME_TYPE,m_paShowMimeType); - m_pListView->confColumns[1].setData(I18N_NOOP("Size"),"Size",TDEIO::UDS_SIZE,m_paShowSize); - m_pListView->confColumns[2].setData(I18N_NOOP("Modified"),"Date",TDEIO::UDS_MODIFICATION_TIME,m_paShowTime); - m_pListView->confColumns[3].setData(I18N_NOOP("Accessed"),"AccessDate",TDEIO::UDS_ACCESS_TIME,m_paShowAccessTime); - m_pListView->confColumns[4].setData(I18N_NOOP("Created"),"CreationDate",TDEIO::UDS_CREATION_TIME,m_paShowCreateTime); - m_pListView->confColumns[5].setData(I18N_NOOP("Permissions"),"Access",TDEIO::UDS_ACCESS,m_paShowPermissions); - m_pListView->confColumns[6].setData(I18N_NOOP("Owner"),"Owner",TDEIO::UDS_USER,m_paShowOwner); - m_pListView->confColumns[7].setData(I18N_NOOP("Group"),"Group",TDEIO::UDS_GROUP,m_paShowGroup); - m_pListView->confColumns[8].setData(I18N_NOOP("Link"),"Link",TDEIO::UDS_LINK_DEST,m_paShowLinkDest); - m_pListView->confColumns[9].setData(I18N_NOOP("URL"),"URL",TDEIO::UDS_URL,m_paShowURL); - // Note: File Type is in fact the mimetype comment. We use UDS_FILE_TYPE but that's not what we show in fact :/ - m_pListView->confColumns[10].setData(I18N_NOOP("File Type"),"Type",TDEIO::UDS_FILE_TYPE,m_paShowType); - - - connect( m_pListView, TQT_SIGNAL( selectionChanged() ), - m_extension, TQT_SLOT( updateActions() ) ); - connect( m_pListView, TQT_SIGNAL( selectionChanged() ), - this, TQT_SLOT( slotSelectionChanged() ) ); - - connect( m_pListView, TQT_SIGNAL( currentChanged(TQListViewItem*) ), - m_extension, TQT_SLOT( updateActions() ) ); - connect(m_pListView->header(),TQT_SIGNAL(indexChange(int,int,int)),this,TQT_SLOT(headerDragged(int,int,int))); - connect(m_pListView->header(),TQT_SIGNAL(clicked(int)),this,TQT_SLOT(slotHeaderClicked(int))); - connect(m_pListView->header(),TQT_SIGNAL(sizeChange(int,int,int)),TQT_SLOT(slotHeaderSizeChanged())); - - // signals from konqdirpart (for BC reasons) - connect( this, TQT_SIGNAL( findOpened( KonqDirPart * ) ), TQT_SLOT( slotKFindOpened() ) ); - connect( this, TQT_SIGNAL( findClosed( KonqDirPart * ) ), TQT_SLOT( slotKFindClosed() ) ); - - loadPlugins( this, this, instance() ); -} - -KonqListView::~KonqListView() -{ - delete m_mimeTypeResolver; - delete m_pProps; -} - -void KonqListView::guiActivateEvent( KParts::GUIActivateEvent *event ) -{ - KonqDirPart::guiActivateEvent(event ); - //ReadOnlyPart::guiActivateEvent(event ); - ((ListViewBrowserExtension*)m_extension)->updateActions(); -} - -bool KonqListView::doOpenURL( const KURL &url ) -{ - KURL u( url ); - const TQString prettyURL = url.pathOrURL(); - emit setWindowCaption( prettyURL ); - return m_pListView->openURL( url ); -} - -bool KonqListView::doCloseURL() -{ - m_pListView->stop(); - m_mimeTypeResolver->m_lstPendingMimeIconItems.clear(); - return true; -} - -void KonqListView::listingComplete() -{ - m_mimeTypeResolver->start( /*10*/ 0 ); -} - -void KonqListView::determineIcon( KonqBaseListViewItem * item ) -{ - //int oldSerial = item->pixmap(0)->serialNumber(); - - (void) item->item()->determineMimeType(); - - //TQPixmap newIcon = item->item()->pixmap( m_parent->iconSize(), - // item->state() ); - //if ( oldSerial != newIcon.serialNumber() ) - // item->setPixmap( 0, newIcon ); - - if (item->item()->isMimeTypeKnown()) { - item->mimetypeFound(); - } - - // We also have columns to update, not only the icon - item->updateContents(); -} - -void KonqListView::saveState( TQDataStream &stream ) -{ - //kdDebug(1202) << k_funcinfo << endl; - KonqDirPart::saveState( stream ); - m_pListView->saveState( stream ); -} - -void KonqListView::restoreState( TQDataStream &stream ) -{ - //kdDebug(1202) << k_funcinfo << endl; - KonqDirPart::restoreState( stream ); - m_pListView->restoreState( stream ); -} - -void KonqListView::disableIcons( const KURL::List &lst ) -{ - m_pListView->disableIcons( lst ); -} - -void KonqListView::slotSelect() -{ - bool ok; - TQString pattern = KInputDialog::getText( TQString::null, - i18n( "Select files:" ), "*", &ok, m_pListView ); - if ( !ok ) - return; - - TQRegExp re( pattern, true, true ); - - m_pListView->blockSignals( true ); - - for (KonqBaseListViewWidget::iterator it = m_pListView->begin(); it != m_pListView->end(); it++ ) - { - if ((m_pListView->automaticSelection()) && (it->isSelected())) { - it->setSelected(FALSE); - //the following line is to prevent that more than one item were selected - //and now get deselected and automaticSelection() was true, this shouldn't happen - //but who knows, aleXXX - m_pListView->deactivateAutomaticSelection(); - } - if ( it->isVisible() ) { - if ( re.exactMatch( it->text(0) ) ) { - it->setSelected(TRUE); - } - } - else { - it->setSelected(FALSE); - } - } - m_pListView->blockSignals( false ); - m_pListView->deactivateAutomaticSelection(); - emit m_pListView->selectionChanged(); - m_pListView->viewport()->update(); -} - -void KonqListView::slotUnselect() -{ - bool ok; - TQString pattern = KInputDialog::getText( TQString::null, - i18n( "Unselect files:" ), "*", &ok, m_pListView ); - if ( !ok ) - return; - - TQRegExp re( pattern, TRUE, TRUE ); - - m_pListView->blockSignals(TRUE); - - for (KonqBaseListViewWidget::iterator it = m_pListView->begin(); it != m_pListView->end(); it++ ) { - if ( it->isVisible() ) { - if ( re.exactMatch( it->text(0) ) ) { - it->setSelected(FALSE); - } - } - else { - it->setSelected(FALSE); - } - } - - m_pListView->blockSignals(FALSE); - m_pListView->deactivateAutomaticSelection(); - emit m_pListView->selectionChanged(); - m_pListView->viewport()->update(); -} - -void KonqListView::slotSelectAll() -{ - m_pListView->selectAll(TRUE); - m_pListView->deactivateAutomaticSelection(); - emit m_pListView->selectionChanged(); -} - -void KonqListView::slotUnselectAll() -{ - m_pListView->selectAll(FALSE); - m_pListView->deactivateAutomaticSelection(); - emit m_pListView->selectionChanged(); -} - - -void KonqListView::slotInvertSelection() -{ - if ((m_pListView->automaticSelection()) - && (m_pListView->currentItem()!=0) - && (m_pListView->currentItem()->isSelected())) - m_pListView->currentItem()->setSelected(FALSE); - - m_pListView->invertSelection(); - m_pListView->deactivateAutomaticSelection(); - emit m_pListView->selectionChanged(); - m_pListView->viewport()->update(); -} - -void KonqListView::newIconSize( int size ) -{ - KonqDirPart::newIconSize( size ); - m_pListView->updateListContents(); -} - -void KonqListView::slotShowDot() -{ - m_pProps->setShowingDotFiles( m_paShowDot->isChecked() ); - m_pListView->m_dirLister->setShowingDotFiles( m_pProps->isShowingDotFiles() ); - m_pListView->m_dirLister->emitChanges(); -} - -void KonqListView::slotCaseInsensitive() -{ - m_pProps->setCaseInsensitiveSort( m_paCaseInsensitive->isChecked() ); - m_pListView->sort(); -} - -void KonqListView::slotColumnToggled() -{ - kdDebug(1202) << "::slotColumnToggled" << endl; - for (uint i=0; iNumberOfAtoms; i++) - { - m_pListView->confColumns[i].displayThisOne=!m_pListView->confColumns[i].toggleThisOne - || (m_pListView->confColumns[i].toggleThisOne->isChecked()&&m_pListView->confColumns[i].toggleThisOne->isEnabled()); - //this column has been enabled, the columns after it slide one column back - if ((m_pListView->confColumns[i].displayThisOne) && (m_pListView->confColumns[i].displayInColumn==-1)) - { - int maxColumn(0); - for (uint j=0; jNumberOfAtoms; j++) - if ((m_pListView->confColumns[j].displayInColumn>maxColumn) && (m_pListView->confColumns[j].displayThisOne)) - maxColumn=m_pListView->confColumns[j].displayInColumn; - m_pListView->confColumns[i].displayInColumn=maxColumn+1; - } - //this column has been disabled, the columns after it slide one column - if ((!m_pListView->confColumns[i].displayThisOne) && (m_pListView->confColumns[i].displayInColumn!=-1)) - { - for (uint j=0; jNumberOfAtoms; j++) - if (m_pListView->confColumns[j].displayInColumn>m_pListView->confColumns[i].displayInColumn) - m_pListView->confColumns[j].displayInColumn--; - m_pListView->confColumns[i].displayInColumn=-1; - } - } - - //create the new list contents - m_pListView->createColumns(); - m_pListView->updateListContents(); - - //save the config - TQStringList lstColumns; - int currentColumn(m_pListView->m_filenameColumn+1); - for (int i=0; i<(int)m_pListView->NumberOfAtoms; i++) - { - kdDebug(1202)<<"checking: -"<confColumns[i].name<<"-"<confColumns[i].displayThisOne) && (currentColumn==m_pListView->confColumns[i].displayInColumn)) - { - lstColumns.append(m_pListView->confColumns[i].name); - kdDebug(1202)<<" adding"<url().protocol() ); - config.readConfig(); - config.setColumns( lstColumns ); - config.writeConfig(); - - // Update column sizes - slotHeaderSizeChanged(); -} - -void KonqListView::slotHeaderClicked(int sec) -{ - kdDebug(1202)<<"section: "<NumberOfAtoms; i++) - if (m_pListView->confColumns[i].displayInColumn==sec) clickedColumn=i; - kdDebug(1202)<<"atom index "<confColumns[clickedColumn].desktopFileName; - - if (nameOfSortColumn!=m_pListView->sortedByColumn) - { - m_pListView->sortedByColumn=nameOfSortColumn; - m_pListView->setAscending(TRUE); - } - else - m_pListView->setAscending(!m_pListView->ascending()); - - KonqListViewSettings config( m_pListView->url().protocol() ); - config.readConfig(); - config.setSortBy( nameOfSortColumn ); - config.setSortOrder( m_pListView->ascending() ); - config.writeConfig(); -} - -void KonqListView::headerDragged(int sec, int from, int to) -{ - kdDebug(1202)<<"section: "<currentItem()==0) - return 0L; - return static_cast(m_pListView->currentItem())->item(); -} - -void KonqListView::slotSaveAfterHeaderDrag() -{ - TQStringList lstColumns; - - for ( int i=0; i < m_pListView->columns(); i++ ) - { - int section = m_pListView->header()->mapToSection( i ); - - // look for section - for ( uint j=0; j < m_pListView->NumberOfAtoms; j++ ) - { - if ( m_pListView->confColumns[j].displayInColumn == section ) - { - lstColumns.append( m_pListView->confColumns[j].name ); - break; - } - } - } - KonqListViewSettings config( m_pListView->url().protocol() ); - config.readConfig(); - config.setColumns( lstColumns ); - config.writeConfig(); - - // Update column sizes - slotHeaderSizeChanged(); -} - -void KonqListView::slotSaveColumnWidths() -{ - TQValueList lstColumnWidths; - - for ( int i=0; i < m_pListView->columns(); i++ ) - { - int section = m_pListView->header()->mapToSection( i ); - - // look for section - for ( uint j=0; j < m_pListView->NumberOfAtoms; j++ ) - { - // Save size only if the column is found - if ( m_pListView->confColumns[j].displayInColumn == section ) - { - m_pListView->confColumns[j].width = m_pListView->columnWidth(section); - lstColumnWidths.append( m_pListView->confColumns[j].width ); - break; - } - } - } - KonqListViewSettings config( m_pListView->url().protocol() ); - config.readConfig(); - config.setColumnWidths( lstColumnWidths ); - - // size of current filename column - config.setFileNameColumnWidth( m_pListView->columnWidth(0) ); - config.writeConfig(); -} - -void KonqListView::slotHeaderSizeChanged() -{ - if ( !m_headerTimer ) - { - m_headerTimer = new TQTimer( this ); - connect( m_headerTimer, TQT_SIGNAL( timeout() ), this, TQT_SLOT( slotSaveColumnWidths() ) ); - } - else - m_headerTimer->stop(); - - m_headerTimer->start( 250, true ); -} - -void KonqListView::slotKFindOpened() -{ - if ( m_pListView->m_dirLister ) - m_pListView->m_dirLister->setAutoUpdate( false ); -} - -void KonqListView::slotKFindClosed() -{ - if ( m_pListView->m_dirLister ) - m_pListView->m_dirLister->setAutoUpdate( true ); -} - -void KonqListView::setupActions() -{ - m_paShowTime=new TDEToggleAction(i18n("Show &Modification Time"), 0,this, TQT_SLOT(slotColumnToggled()), actionCollection(), "show_time" ); - m_paShowTime->setCheckedState(i18n("Hide &Modification Time")); - m_paShowType=new TDEToggleAction(i18n("Show &File Type"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_type" ); - m_paShowType->setCheckedState(i18n("Hide &File Type")); - m_paShowMimeType=new TDEToggleAction(i18n("Show MimeType"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_mimetype" ); - m_paShowMimeType->setCheckedState(i18n("Hide MimeType")); - m_paShowAccessTime=new TDEToggleAction(i18n("Show &Access Time"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_access_time" ); - m_paShowAccessTime->setCheckedState(i18n("Hide &Access Time")); - m_paShowCreateTime=new TDEToggleAction(i18n("Show &Creation Time"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_creation_time" ); - m_paShowCreateTime->setCheckedState(i18n("Hide &Creation Time")); - m_paShowLinkDest=new TDEToggleAction(i18n("Show &Link Destination"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_link_dest" ); - m_paShowLinkDest->setCheckedState(i18n("Hide &Link Destination")); - m_paShowSize=new TDEToggleAction(i18n("Show Filesize"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_size" ); - m_paShowSize->setCheckedState(i18n("Hide Filesize")); - m_paShowOwner=new TDEToggleAction(i18n("Show Owner"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_owner" ); - m_paShowOwner->setCheckedState(i18n("Hide Owner")); - m_paShowGroup=new TDEToggleAction(i18n("Show Group"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_group" ); - m_paShowGroup->setCheckedState(i18n("Hide Group")); - m_paShowPermissions=new TDEToggleAction(i18n("Show Permissions"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_permissions" ); - m_paShowPermissions->setCheckedState(i18n("Hide Permissions")); - m_paShowURL=new TDEToggleAction(i18n("Show URL"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_url" ); - - m_paSelect = new TDEAction( i18n( "Se&lect..." ), CTRL+Key_Plus, this, TQT_SLOT( slotSelect() ), actionCollection(), "select" ); - m_paUnselect = new TDEAction( i18n( "Unselect..." ), CTRL+Key_Minus, this, TQT_SLOT( slotUnselect() ), actionCollection(), "unselect" ); - m_paSelectAll = KStdAction::selectAll( this, TQT_SLOT( slotSelectAll() ), actionCollection(), "selectall" ); - m_paUnselectAll = new TDEAction( i18n( "Unselect All" ), CTRL+Key_U, this, TQT_SLOT( slotUnselectAll() ), actionCollection(), "unselectall" ); - m_paInvertSelection = new TDEAction( i18n( "&Invert Selection" ), CTRL+Key_Asterisk, this, TQT_SLOT( slotInvertSelection() ), actionCollection(), "invertselection" ); - - // These 2 actions are 'fake' actions. They are defined so that the keyboard shortcuts - // can be set from the 'Configure Shortcuts..." dialog. - // The real actions are performed in the TDEListViewLineEdit::keyPressEvent() in tdeui - m_paRenameMoveNext = new TDEAction(i18n( "&Rename and move to next item" ), Key_Tab, - NULL, NULL, actionCollection(), "renameMoveNext" ); - m_paRenameMoveNext->setWhatsThis(i18n("Pressing this button completes the current rename operation," - "moves to the next item and starts a new rename operation.")); - m_paRenameMoveNext->setToolTip( i18n("Complete rename operation and move the next item")); - m_paRenameMoveNext->setEnabled(false); - m_paRenameMovePrev = new TDEAction( i18n( "&Rename and move to previous item" ), SHIFT+Key_BackTab, - NULL, NULL, actionCollection(), "renameMovePrev" ); - m_paRenameMovePrev->setWhatsThis(i18n("Pressing this button completes the current rename operation," - "moves to the previous item and starts a new rename operation.")); - m_paRenameMovePrev->setToolTip( i18n("Complete rename operation and move the previous item")); - m_paRenameMovePrev->setEnabled(false); - - m_paShowDot = new TDEToggleAction( i18n( "Show &Hidden Files" ), 0, this, TQT_SLOT( slotShowDot() ), actionCollection(), "show_dot" ); -// m_paShowDot->setCheckedState(i18n("Hide &Hidden Files")); - m_paCaseInsensitive = new TDEToggleAction(i18n("Case Insensitive Sort"), 0, this, TQT_SLOT(slotCaseInsensitive()),actionCollection(), "sort_caseinsensitive" ); - - newIconSize( TDEIcon::SizeSmall /* default size */ ); -} - -void KonqListView::slotSelectionChanged() -{ - bool itemSelected = selectedFileItems().count()>0; - m_paUnselect->setEnabled( itemSelected ); - m_paUnselectAll->setEnabled( itemSelected ); -// m_paInvertSelection->setEnabled( itemSelected ); -} - -#include "konq_listview.moc" - - diff --git a/konqueror/listview/konq_listview.cpp b/konqueror/listview/konq_listview.cpp new file mode 100644 index 000000000..67da49c6d --- /dev/null +++ b/konqueror/listview/konq_listview.cpp @@ -0,0 +1,731 @@ +/* This file is part of the KDE project + Copyright (C) 1998, 1999 Torben Weis + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "konq_listview.h" +#include "konq_textviewwidget.h" +#include "konq_treeviewwidget.h" +#include "konq_infolistviewwidget.h" +#include "konq_listviewsettings.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +KonqListViewFactory::KonqListViewFactory() +{ + s_instance = 0; + s_defaultViewProps = 0; +} + +KonqListViewFactory::~KonqListViewFactory() +{ + delete s_instance; + delete s_defaultViewProps; + + s_instance = 0; + s_defaultViewProps = 0; +} + +KParts::Part* KonqListViewFactory::createPartObject( TQWidget *parentWidget, const char *, TQObject *parent, const char *name, const char*, const TQStringList &args ) +{ + if( args.count() < 1 ) + kdWarning() << "KonqListView: Missing Parameter" << endl; + + KParts::Part *obj = new KonqListView( parentWidget, parent, name, args.first() ); + return obj; +} + +TDEInstance *KonqListViewFactory::instance() +{ + if ( !s_instance ) + s_instance = new TDEInstance( "konqlistview" ); + return s_instance; +} + +KonqPropsView *KonqListViewFactory::defaultViewProps() +{ + if ( !s_defaultViewProps ) + s_defaultViewProps = new KonqPropsView( instance(),0L ); + //s_defaultViewProps = KonqPropsView::defaultProps( instance() ); + + return s_defaultViewProps; +} + +TDEInstance *KonqListViewFactory::s_instance = 0; +KonqPropsView *KonqListViewFactory::s_defaultViewProps = 0; + +K_EXPORT_COMPONENT_FACTORY( konq_listview, KonqListViewFactory ) + +ListViewBrowserExtension::ListViewBrowserExtension( KonqListView *listView ) + : KonqDirPartBrowserExtension( listView ) +{ + m_listView = listView; +} + +int ListViewBrowserExtension::xOffset() +{ + //kdDebug(1202) << k_funcinfo << endl; + return m_listView->listViewWidget()->contentsX(); +} + +int ListViewBrowserExtension::yOffset() +{ + //kdDebug(1202) << k_funcinfo << endl; + return m_listView->listViewWidget()->contentsY(); +} + +void ListViewBrowserExtension::updateActions() +{ + // This code is very related to KonqIconViewWidget::slotSelectionChanged + int canCopy = 0; + int canDel = 0; + int canTrash = 0; + bool bInTrash = false; + KFileItemList lstItems = m_listView->selectedFileItems(); + + for (KFileItem *item = lstItems.first(); item; item = lstItems.next()) + { + canCopy++; + KURL url = item->url(); + if ( url.directory(false) == TDEGlobalSettings::trashPath() ) + bInTrash = true; + if ( KProtocolInfo::supportsDeleting( url ) ) + canDel++; + if ( !item->localPath().isEmpty() ) + canTrash++; + } + + emit enableAction( "copy", canCopy > 0 ); + emit enableAction( "cut", canDel > 0 ); + emit enableAction( "trash", canDel > 0 && !bInTrash && canDel == canTrash ); + emit enableAction( "del", canDel > 0 ); + emit enableAction( "properties", lstItems.count() > 0 && KPropertiesDialog::canDisplay( lstItems ) ); + emit enableAction( "editMimeType", ( lstItems.count() == 1 ) ); + emit enableAction( "rename", ( m_listView->listViewWidget()->currentItem() != 0 ) && !bInTrash ); +} + +void ListViewBrowserExtension::copySelection( bool move ) +{ + KonqDrag *urlData = new KonqDrag( m_listView->listViewWidget()->selectedUrls(false), m_listView->listViewWidget()->selectedUrls(true), move ); + TQApplication::clipboard()->setData( urlData ); +} + +void ListViewBrowserExtension::paste() +{ + KonqOperations::doPaste( m_listView->listViewWidget(), m_listView->url() ); +} + +void ListViewBrowserExtension::pasteTo( const KURL& url ) +{ + KonqOperations::doPaste( m_listView->listViewWidget(), url ); +} + +void ListViewBrowserExtension::rename() +{ + TQListViewItem* item = m_listView->listViewWidget()->currentItem(); + Q_ASSERT ( item ); + + // Update shurtcuts for the 'rename and move' actions. Must be done every time since the + // shortcuts may have been changed by the user in the meanwhile + const TDEShortcut moveNextSC=m_listView->m_paRenameMoveNext->shortcut(); + const TDEShortcut movePrevSC=m_listView->m_paRenameMovePrev->shortcut(); + m_listView->listViewWidget()->setRenameSettings(TDEListViewRenameSettings( + !(moveNextSC.isNull() && movePrevSC.isNull()), moveNextSC, movePrevSC)); + + m_listView->listViewWidget()->rename( item, 0 ); + + // Enhanced rename: Don't highlight the file extension. + KLineEdit* le = m_listView->listViewWidget()->renameLineEdit(); + if ( le ) { + const TQString txt = le->text(); + TQString pattern; + KMimeType::diagnoseFileName( txt, pattern ); + if (!pattern.isEmpty() && pattern.at(0)=='*' && pattern.find('*',1)==-1) + le->setSelection(0, txt.length()-pattern.stripWhiteSpace().length()+1); + else + { + int lastDot = txt.findRev('.'); + if (lastDot > 0) + le->setSelection(0, lastDot); + } + } +} + +void ListViewBrowserExtension::trash() +{ + KonqOperations::del(m_listView->listViewWidget(), + KonqOperations::TRASH, + m_listView->listViewWidget()->selectedUrls( true )); +} + +void ListViewBrowserExtension::reparseConfiguration() +{ + // m_pProps is a problem here (what is local, what is global ?) + // but settings is easy : + m_listView->listViewWidget()->initConfig(); +} + +void ListViewBrowserExtension::setSaveViewPropertiesLocally(bool value) +{ + m_listView->props()->setSaveViewPropertiesLocally( value ); +} + +void ListViewBrowserExtension::setNameFilter( const TQString &nameFilter ) +{ + m_listView->setNameFilter( nameFilter ); +} + +void ListViewBrowserExtension::properties() +{ + (void) new KPropertiesDialog( m_listView->selectedFileItems() ); +} + +void ListViewBrowserExtension::editMimeType() +{ + KFileItemList items = m_listView->selectedFileItems(); + assert ( items.count() == 1 ); + KonqOperations::editMimeType( items.first()->mimetype() ); +} + +KonqListView::KonqListView( TQWidget *parentWidget, TQObject *parent, const char *name, const TQString& mode ) + : KonqDirPart( parent, name ) +,m_headerTimer(0) +{ + setInstance( KonqListViewFactory::instance(), false ); + + // Create a properties instance for this view + // All the listview view modes inherit the same properties defaults... + m_pProps = new KonqPropsView( KonqListViewFactory::instance(), KonqListViewFactory::defaultViewProps() ); + + setBrowserExtension( new ListViewBrowserExtension( this ) ); + + TQString xmlFile; + + if (mode=="TextView") + { + kdDebug(1202) << "Creating KonqTextViewWidget" << endl; + xmlFile = "konq_textview.rc"; + m_pListView=new KonqTextViewWidget(this, parentWidget); + } + else if (mode=="MixedTree") + { + kdDebug(1202) << "Creating KonqTreeViewWidget" << endl; + xmlFile = "konq_treeview.rc"; + m_pListView=new KonqTreeViewWidget(this,parentWidget); + } + else if (mode=="InfoListView") + { + kdDebug(1202) << "Creating KonqInfoListViewWidget" << endl; + xmlFile = "konq_infolistview.rc"; + m_pListView=new KonqInfoListViewWidget(this,parentWidget); + } + else + { + kdDebug(1202) << "Creating KonqDetailedListViewWidget" << endl; + xmlFile = "konq_detailedlistview.rc"; + m_pListView = new KonqBaseListViewWidget( this, parentWidget); + } + setWidget( m_pListView ); + setDirLister( m_pListView->m_dirLister ); + + m_mimeTypeResolver = new KMimeTypeResolver(this); + + setXMLFile( xmlFile ); + + setupActions(); + + m_pListView->confColumns.resize( 11 ); + m_pListView->confColumns[0].setData(I18N_NOOP("MimeType"),"Type",TDEIO::UDS_MIME_TYPE,m_paShowMimeType); + m_pListView->confColumns[1].setData(I18N_NOOP("Size"),"Size",TDEIO::UDS_SIZE,m_paShowSize); + m_pListView->confColumns[2].setData(I18N_NOOP("Modified"),"Date",TDEIO::UDS_MODIFICATION_TIME,m_paShowTime); + m_pListView->confColumns[3].setData(I18N_NOOP("Accessed"),"AccessDate",TDEIO::UDS_ACCESS_TIME,m_paShowAccessTime); + m_pListView->confColumns[4].setData(I18N_NOOP("Created"),"CreationDate",TDEIO::UDS_CREATION_TIME,m_paShowCreateTime); + m_pListView->confColumns[5].setData(I18N_NOOP("Permissions"),"Access",TDEIO::UDS_ACCESS,m_paShowPermissions); + m_pListView->confColumns[6].setData(I18N_NOOP("Owner"),"Owner",TDEIO::UDS_USER,m_paShowOwner); + m_pListView->confColumns[7].setData(I18N_NOOP("Group"),"Group",TDEIO::UDS_GROUP,m_paShowGroup); + m_pListView->confColumns[8].setData(I18N_NOOP("Link"),"Link",TDEIO::UDS_LINK_DEST,m_paShowLinkDest); + m_pListView->confColumns[9].setData(I18N_NOOP("URL"),"URL",TDEIO::UDS_URL,m_paShowURL); + // Note: File Type is in fact the mimetype comment. We use UDS_FILE_TYPE but that's not what we show in fact :/ + m_pListView->confColumns[10].setData(I18N_NOOP("File Type"),"Type",TDEIO::UDS_FILE_TYPE,m_paShowType); + + + connect( m_pListView, TQT_SIGNAL( selectionChanged() ), + m_extension, TQT_SLOT( updateActions() ) ); + connect( m_pListView, TQT_SIGNAL( selectionChanged() ), + this, TQT_SLOT( slotSelectionChanged() ) ); + + connect( m_pListView, TQT_SIGNAL( currentChanged(TQListViewItem*) ), + m_extension, TQT_SLOT( updateActions() ) ); + connect(m_pListView->header(),TQT_SIGNAL(indexChange(int,int,int)),this,TQT_SLOT(headerDragged(int,int,int))); + connect(m_pListView->header(),TQT_SIGNAL(clicked(int)),this,TQT_SLOT(slotHeaderClicked(int))); + connect(m_pListView->header(),TQT_SIGNAL(sizeChange(int,int,int)),TQT_SLOT(slotHeaderSizeChanged())); + + // signals from konqdirpart (for BC reasons) + connect( this, TQT_SIGNAL( findOpened( KonqDirPart * ) ), TQT_SLOT( slotKFindOpened() ) ); + connect( this, TQT_SIGNAL( findClosed( KonqDirPart * ) ), TQT_SLOT( slotKFindClosed() ) ); + + loadPlugins( this, this, instance() ); +} + +KonqListView::~KonqListView() +{ + delete m_mimeTypeResolver; + delete m_pProps; +} + +void KonqListView::guiActivateEvent( KParts::GUIActivateEvent *event ) +{ + KonqDirPart::guiActivateEvent(event ); + //ReadOnlyPart::guiActivateEvent(event ); + ((ListViewBrowserExtension*)m_extension)->updateActions(); +} + +bool KonqListView::doOpenURL( const KURL &url ) +{ + KURL u( url ); + const TQString prettyURL = url.pathOrURL(); + emit setWindowCaption( prettyURL ); + return m_pListView->openURL( url ); +} + +bool KonqListView::doCloseURL() +{ + m_pListView->stop(); + m_mimeTypeResolver->m_lstPendingMimeIconItems.clear(); + return true; +} + +void KonqListView::listingComplete() +{ + m_mimeTypeResolver->start( /*10*/ 0 ); +} + +void KonqListView::determineIcon( KonqBaseListViewItem * item ) +{ + //int oldSerial = item->pixmap(0)->serialNumber(); + + (void) item->item()->determineMimeType(); + + //TQPixmap newIcon = item->item()->pixmap( m_parent->iconSize(), + // item->state() ); + //if ( oldSerial != newIcon.serialNumber() ) + // item->setPixmap( 0, newIcon ); + + if (item->item()->isMimeTypeKnown()) { + item->mimetypeFound(); + } + + // We also have columns to update, not only the icon + item->updateContents(); +} + +void KonqListView::saveState( TQDataStream &stream ) +{ + //kdDebug(1202) << k_funcinfo << endl; + KonqDirPart::saveState( stream ); + m_pListView->saveState( stream ); +} + +void KonqListView::restoreState( TQDataStream &stream ) +{ + //kdDebug(1202) << k_funcinfo << endl; + KonqDirPart::restoreState( stream ); + m_pListView->restoreState( stream ); +} + +void KonqListView::disableIcons( const KURL::List &lst ) +{ + m_pListView->disableIcons( lst ); +} + +void KonqListView::slotSelect() +{ + bool ok; + TQString pattern = KInputDialog::getText( TQString::null, + i18n( "Select files:" ), "*", &ok, m_pListView ); + if ( !ok ) + return; + + TQRegExp re( pattern, true, true ); + + m_pListView->blockSignals( true ); + + for (KonqBaseListViewWidget::iterator it = m_pListView->begin(); it != m_pListView->end(); it++ ) + { + if ((m_pListView->automaticSelection()) && (it->isSelected())) { + it->setSelected(FALSE); + //the following line is to prevent that more than one item were selected + //and now get deselected and automaticSelection() was true, this shouldn't happen + //but who knows, aleXXX + m_pListView->deactivateAutomaticSelection(); + } + if ( it->isVisible() ) { + if ( re.exactMatch( it->text(0) ) ) { + it->setSelected(TRUE); + } + } + else { + it->setSelected(FALSE); + } + } + m_pListView->blockSignals( false ); + m_pListView->deactivateAutomaticSelection(); + emit m_pListView->selectionChanged(); + m_pListView->viewport()->update(); +} + +void KonqListView::slotUnselect() +{ + bool ok; + TQString pattern = KInputDialog::getText( TQString::null, + i18n( "Unselect files:" ), "*", &ok, m_pListView ); + if ( !ok ) + return; + + TQRegExp re( pattern, TRUE, TRUE ); + + m_pListView->blockSignals(TRUE); + + for (KonqBaseListViewWidget::iterator it = m_pListView->begin(); it != m_pListView->end(); it++ ) { + if ( it->isVisible() ) { + if ( re.exactMatch( it->text(0) ) ) { + it->setSelected(FALSE); + } + } + else { + it->setSelected(FALSE); + } + } + + m_pListView->blockSignals(FALSE); + m_pListView->deactivateAutomaticSelection(); + emit m_pListView->selectionChanged(); + m_pListView->viewport()->update(); +} + +void KonqListView::slotSelectAll() +{ + m_pListView->selectAll(TRUE); + m_pListView->deactivateAutomaticSelection(); + emit m_pListView->selectionChanged(); +} + +void KonqListView::slotUnselectAll() +{ + m_pListView->selectAll(FALSE); + m_pListView->deactivateAutomaticSelection(); + emit m_pListView->selectionChanged(); +} + + +void KonqListView::slotInvertSelection() +{ + if ((m_pListView->automaticSelection()) + && (m_pListView->currentItem()!=0) + && (m_pListView->currentItem()->isSelected())) + m_pListView->currentItem()->setSelected(FALSE); + + m_pListView->invertSelection(); + m_pListView->deactivateAutomaticSelection(); + emit m_pListView->selectionChanged(); + m_pListView->viewport()->update(); +} + +void KonqListView::newIconSize( int size ) +{ + KonqDirPart::newIconSize( size ); + m_pListView->updateListContents(); +} + +void KonqListView::slotShowDot() +{ + m_pProps->setShowingDotFiles( m_paShowDot->isChecked() ); + m_pListView->m_dirLister->setShowingDotFiles( m_pProps->isShowingDotFiles() ); + m_pListView->m_dirLister->emitChanges(); +} + +void KonqListView::slotCaseInsensitive() +{ + m_pProps->setCaseInsensitiveSort( m_paCaseInsensitive->isChecked() ); + m_pListView->sort(); +} + +void KonqListView::slotColumnToggled() +{ + kdDebug(1202) << "::slotColumnToggled" << endl; + for (uint i=0; iNumberOfAtoms; i++) + { + m_pListView->confColumns[i].displayThisOne=!m_pListView->confColumns[i].toggleThisOne + || (m_pListView->confColumns[i].toggleThisOne->isChecked()&&m_pListView->confColumns[i].toggleThisOne->isEnabled()); + //this column has been enabled, the columns after it slide one column back + if ((m_pListView->confColumns[i].displayThisOne) && (m_pListView->confColumns[i].displayInColumn==-1)) + { + int maxColumn(0); + for (uint j=0; jNumberOfAtoms; j++) + if ((m_pListView->confColumns[j].displayInColumn>maxColumn) && (m_pListView->confColumns[j].displayThisOne)) + maxColumn=m_pListView->confColumns[j].displayInColumn; + m_pListView->confColumns[i].displayInColumn=maxColumn+1; + } + //this column has been disabled, the columns after it slide one column + if ((!m_pListView->confColumns[i].displayThisOne) && (m_pListView->confColumns[i].displayInColumn!=-1)) + { + for (uint j=0; jNumberOfAtoms; j++) + if (m_pListView->confColumns[j].displayInColumn>m_pListView->confColumns[i].displayInColumn) + m_pListView->confColumns[j].displayInColumn--; + m_pListView->confColumns[i].displayInColumn=-1; + } + } + + //create the new list contents + m_pListView->createColumns(); + m_pListView->updateListContents(); + + //save the config + TQStringList lstColumns; + int currentColumn(m_pListView->m_filenameColumn+1); + for (int i=0; i<(int)m_pListView->NumberOfAtoms; i++) + { + kdDebug(1202)<<"checking: -"<confColumns[i].name<<"-"<confColumns[i].displayThisOne) && (currentColumn==m_pListView->confColumns[i].displayInColumn)) + { + lstColumns.append(m_pListView->confColumns[i].name); + kdDebug(1202)<<" adding"<url().protocol() ); + config.readConfig(); + config.setColumns( lstColumns ); + config.writeConfig(); + + // Update column sizes + slotHeaderSizeChanged(); +} + +void KonqListView::slotHeaderClicked(int sec) +{ + kdDebug(1202)<<"section: "<NumberOfAtoms; i++) + if (m_pListView->confColumns[i].displayInColumn==sec) clickedColumn=i; + kdDebug(1202)<<"atom index "<confColumns[clickedColumn].desktopFileName; + + if (nameOfSortColumn!=m_pListView->sortedByColumn) + { + m_pListView->sortedByColumn=nameOfSortColumn; + m_pListView->setAscending(TRUE); + } + else + m_pListView->setAscending(!m_pListView->ascending()); + + KonqListViewSettings config( m_pListView->url().protocol() ); + config.readConfig(); + config.setSortBy( nameOfSortColumn ); + config.setSortOrder( m_pListView->ascending() ); + config.writeConfig(); +} + +void KonqListView::headerDragged(int sec, int from, int to) +{ + kdDebug(1202)<<"section: "<currentItem()==0) + return 0L; + return static_cast(m_pListView->currentItem())->item(); +} + +void KonqListView::slotSaveAfterHeaderDrag() +{ + TQStringList lstColumns; + + for ( int i=0; i < m_pListView->columns(); i++ ) + { + int section = m_pListView->header()->mapToSection( i ); + + // look for section + for ( uint j=0; j < m_pListView->NumberOfAtoms; j++ ) + { + if ( m_pListView->confColumns[j].displayInColumn == section ) + { + lstColumns.append( m_pListView->confColumns[j].name ); + break; + } + } + } + KonqListViewSettings config( m_pListView->url().protocol() ); + config.readConfig(); + config.setColumns( lstColumns ); + config.writeConfig(); + + // Update column sizes + slotHeaderSizeChanged(); +} + +void KonqListView::slotSaveColumnWidths() +{ + TQValueList lstColumnWidths; + + for ( int i=0; i < m_pListView->columns(); i++ ) + { + int section = m_pListView->header()->mapToSection( i ); + + // look for section + for ( uint j=0; j < m_pListView->NumberOfAtoms; j++ ) + { + // Save size only if the column is found + if ( m_pListView->confColumns[j].displayInColumn == section ) + { + m_pListView->confColumns[j].width = m_pListView->columnWidth(section); + lstColumnWidths.append( m_pListView->confColumns[j].width ); + break; + } + } + } + KonqListViewSettings config( m_pListView->url().protocol() ); + config.readConfig(); + config.setColumnWidths( lstColumnWidths ); + + // size of current filename column + config.setFileNameColumnWidth( m_pListView->columnWidth(0) ); + config.writeConfig(); +} + +void KonqListView::slotHeaderSizeChanged() +{ + if ( !m_headerTimer ) + { + m_headerTimer = new TQTimer( this ); + connect( m_headerTimer, TQT_SIGNAL( timeout() ), this, TQT_SLOT( slotSaveColumnWidths() ) ); + } + else + m_headerTimer->stop(); + + m_headerTimer->start( 250, true ); +} + +void KonqListView::slotKFindOpened() +{ + if ( m_pListView->m_dirLister ) + m_pListView->m_dirLister->setAutoUpdate( false ); +} + +void KonqListView::slotKFindClosed() +{ + if ( m_pListView->m_dirLister ) + m_pListView->m_dirLister->setAutoUpdate( true ); +} + +void KonqListView::setupActions() +{ + m_paShowTime=new TDEToggleAction(i18n("Show &Modification Time"), 0,this, TQT_SLOT(slotColumnToggled()), actionCollection(), "show_time" ); + m_paShowTime->setCheckedState(i18n("Hide &Modification Time")); + m_paShowType=new TDEToggleAction(i18n("Show &File Type"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_type" ); + m_paShowType->setCheckedState(i18n("Hide &File Type")); + m_paShowMimeType=new TDEToggleAction(i18n("Show MimeType"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_mimetype" ); + m_paShowMimeType->setCheckedState(i18n("Hide MimeType")); + m_paShowAccessTime=new TDEToggleAction(i18n("Show &Access Time"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_access_time" ); + m_paShowAccessTime->setCheckedState(i18n("Hide &Access Time")); + m_paShowCreateTime=new TDEToggleAction(i18n("Show &Creation Time"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_creation_time" ); + m_paShowCreateTime->setCheckedState(i18n("Hide &Creation Time")); + m_paShowLinkDest=new TDEToggleAction(i18n("Show &Link Destination"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_link_dest" ); + m_paShowLinkDest->setCheckedState(i18n("Hide &Link Destination")); + m_paShowSize=new TDEToggleAction(i18n("Show Filesize"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_size" ); + m_paShowSize->setCheckedState(i18n("Hide Filesize")); + m_paShowOwner=new TDEToggleAction(i18n("Show Owner"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_owner" ); + m_paShowOwner->setCheckedState(i18n("Hide Owner")); + m_paShowGroup=new TDEToggleAction(i18n("Show Group"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_group" ); + m_paShowGroup->setCheckedState(i18n("Hide Group")); + m_paShowPermissions=new TDEToggleAction(i18n("Show Permissions"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_permissions" ); + m_paShowPermissions->setCheckedState(i18n("Hide Permissions")); + m_paShowURL=new TDEToggleAction(i18n("Show URL"), 0, this, TQT_SLOT(slotColumnToggled()),actionCollection(), "show_url" ); + + m_paSelect = new TDEAction( i18n( "Se&lect..." ), CTRL+Key_Plus, this, TQT_SLOT( slotSelect() ), actionCollection(), "select" ); + m_paUnselect = new TDEAction( i18n( "Unselect..." ), CTRL+Key_Minus, this, TQT_SLOT( slotUnselect() ), actionCollection(), "unselect" ); + m_paSelectAll = KStdAction::selectAll( this, TQT_SLOT( slotSelectAll() ), actionCollection(), "selectall" ); + m_paUnselectAll = new TDEAction( i18n( "Unselect All" ), CTRL+Key_U, this, TQT_SLOT( slotUnselectAll() ), actionCollection(), "unselectall" ); + m_paInvertSelection = new TDEAction( i18n( "&Invert Selection" ), CTRL+Key_Asterisk, this, TQT_SLOT( slotInvertSelection() ), actionCollection(), "invertselection" ); + + // These 2 actions are 'fake' actions. They are defined so that the keyboard shortcuts + // can be set from the 'Configure Shortcuts..." dialog. + // The real actions are performed in the TDEListViewLineEdit::keyPressEvent() in tdeui + m_paRenameMoveNext = new TDEAction(i18n( "&Rename and move to next item" ), Key_Tab, + NULL, NULL, actionCollection(), "renameMoveNext" ); + m_paRenameMoveNext->setWhatsThis(i18n("Pressing this button completes the current rename operation," + "moves to the next item and starts a new rename operation.")); + m_paRenameMoveNext->setToolTip( i18n("Complete rename operation and move the next item")); + m_paRenameMoveNext->setEnabled(false); + m_paRenameMovePrev = new TDEAction( i18n( "&Rename and move to previous item" ), SHIFT+Key_BackTab, + NULL, NULL, actionCollection(), "renameMovePrev" ); + m_paRenameMovePrev->setWhatsThis(i18n("Pressing this button completes the current rename operation," + "moves to the previous item and starts a new rename operation.")); + m_paRenameMovePrev->setToolTip( i18n("Complete rename operation and move the previous item")); + m_paRenameMovePrev->setEnabled(false); + + m_paShowDot = new TDEToggleAction( i18n( "Show &Hidden Files" ), 0, this, TQT_SLOT( slotShowDot() ), actionCollection(), "show_dot" ); +// m_paShowDot->setCheckedState(i18n("Hide &Hidden Files")); + m_paCaseInsensitive = new TDEToggleAction(i18n("Case Insensitive Sort"), 0, this, TQT_SLOT(slotCaseInsensitive()),actionCollection(), "sort_caseinsensitive" ); + + newIconSize( TDEIcon::SizeSmall /* default size */ ); +} + +void KonqListView::slotSelectionChanged() +{ + bool itemSelected = selectedFileItems().count()>0; + m_paUnselect->setEnabled( itemSelected ); + m_paUnselectAll->setEnabled( itemSelected ); +// m_paInvertSelection->setEnabled( itemSelected ); +} + +#include "konq_listview.moc" + + diff --git a/konqueror/listview/konq_listviewitems.cc b/konqueror/listview/konq_listviewitems.cc deleted file mode 100644 index 45ff99c1c..000000000 --- a/konqueror/listview/konq_listviewitems.cc +++ /dev/null @@ -1,459 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 1998, 1999 Torben Weis - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "konq_listview.h" -#include -#include -#include -#include -#include -#include -#include -#include - -static TQString retrieveExtraEntry( KFileItem* fileitem, int numExtra ) -{ - /// ######## SLOOOOW - TDEIO::UDSEntry::ConstIterator it = fileitem->entry().begin(); - const TDEIO::UDSEntry::ConstIterator end = fileitem->entry().end(); - int n = 0; - for( ; it != end; ++it ) - { - if ((*it).m_uds == TDEIO::UDS_EXTRA) - { - ++n; - if ( n == numExtra ) - { - return (*it).m_str; - } - } - } - return TQString::null; -} - - -/************************************************************** - * - * KonqListViewItem - * - **************************************************************/ -KonqListViewItem::KonqListViewItem( KonqBaseListViewWidget *_listViewWidget, - KonqListViewItem * _parent, KFileItem* _fileitem ) - : KonqBaseListViewItem( _listViewWidget, _parent, _fileitem ), - m_pixmaps( listView()->columns() ) -{ - updateContents(); -} - -KonqListViewItem::KonqListViewItem( KonqBaseListViewWidget *_listViewWidget, KFileItem* _fileitem ) - : KonqBaseListViewItem( _listViewWidget, _fileitem ), - m_pixmaps( listView()->columns() ) -{ - updateContents(); -} - -KonqListViewItem::~KonqListViewItem() -{ - for ( TQValueVector::iterator - it = m_pixmaps.begin(), itEnd = m_pixmaps.end(); - it != itEnd; ++it ) - delete *it; -} - -void KonqListViewItem::updateContents() -{ - // Set the pixmap - setDisabled( m_bDisabled ); - - // Set the text of each column - setText( 0, m_fileitem->text() ); - - // The order is: .dir (0), dir (1), .file (2), file (3) - sortChar = S_ISDIR( m_fileitem->mode() ) ? 1 : 3; - if ( m_fileitem->text()[0] == '.' ) - --sortChar; - - //now we have the first column, so let's do the rest - - int numExtra = 1; - for ( unsigned int i=0; iNumberOfAtoms; i++ ) - { - ColumnInfo *tmpColumn=&m_pListViewWidget->columnConfigInfo()[i]; - if (tmpColumn->displayThisOne) - { - switch (tmpColumn->udsId) - { - case TDEIO::UDS_USER: - setText(tmpColumn->displayInColumn,m_fileitem->user()); - break; - case TDEIO::UDS_GROUP: - setText(tmpColumn->displayInColumn,m_fileitem->group()); - break; - case TDEIO::UDS_FILE_TYPE: - if (m_fileitem->isMimeTypeKnown()) { - setText(tmpColumn->displayInColumn,m_fileitem->mimeComment()); - } - break; - case TDEIO::UDS_MIME_TYPE: - if (m_fileitem->isMimeTypeKnown()) { - setText(tmpColumn->displayInColumn,m_fileitem->mimetype()); - } - break; - case TDEIO::UDS_URL: - setText(tmpColumn->displayInColumn,m_fileitem->url().prettyURL()); - break; - case TDEIO::UDS_LINK_DEST: - setText(tmpColumn->displayInColumn,m_fileitem->linkDest()); - break; - case TDEIO::UDS_SIZE: - if ( m_pListViewWidget->m_pSettings->fileSizeInBytes() ) - setText(tmpColumn->displayInColumn,TDEGlobal::locale()->formatNumber( m_fileitem->size(),0)+" "); - else - setText(tmpColumn->displayInColumn,TDEIO::convertSize(m_fileitem->size())+" "); - break; - case TDEIO::UDS_ACCESS: - setText(tmpColumn->displayInColumn,m_fileitem->permissionsString()); - break; - case TDEIO::UDS_MODIFICATION_TIME: - case TDEIO::UDS_ACCESS_TIME: - case TDEIO::UDS_CREATION_TIME: - { - TQDateTime dt; - time_t _time = m_fileitem->time( tmpColumn->udsId ); - if ( _time != 0 ) - { - dt.setTime_t( _time ); - setText(tmpColumn->displayInColumn, TDEGlobal::locale()->formatDateTime(dt)); - } - else - { - setText(tmpColumn->displayInColumn, TQString::null); - } - } - break; - case TDEIO::UDS_EXTRA: - { - const TQString entryStr = retrieveExtraEntry( m_fileitem, numExtra ); - if ( tmpColumn->type == TQVariant::DateTime ) - { - TQDateTime dt = TQT_TQDATETIME_OBJECT(TQDateTime::fromString( entryStr, Qt::ISODate )); - setText(tmpColumn->displayInColumn, - TDEGlobal::locale()->formatDateTime(dt)); - } - else // if ( tmpColumn->type == TQVariant::String ) - setText(tmpColumn->displayInColumn, entryStr); - ++numExtra; - break; - } - default: - break; - }; - }; - }; -} - -void KonqListViewItem::setDisabled( bool disabled ) -{ - KonqBaseListViewItem::setDisabled( disabled ); - int iconSize = m_pListViewWidget->iconSize(); - iconSize = iconSize ? iconSize : TDEGlobal::iconLoader()->currentSize( TDEIcon::Small ); // Default = small - setPixmap( 0, m_fileitem->pixmap( iconSize, state() ) ); -} - -void KonqListViewItem::setActive( bool active ) -{ - if ( m_bActive == active ) - return; - - //#### Optimize away repaint if possible, like the iconview does? - KonqBaseListViewItem::setActive( active ); - int iconSize = m_pListViewWidget->iconSize(); - iconSize = iconSize ? iconSize : TDEGlobal::iconLoader()->currentSize( TDEIcon::Small ); // Default = small - setPixmap( 0, m_fileitem->pixmap( iconSize, state() ) ); -} - -void KonqListViewItem::setPixmap( int column, const TQPixmap& pm ) -{ - if ( column < 0 ) - return; - - const TQPixmap *current = pixmap( column ); - - if ( ( pm.isNull() && !current ) || - ( current && pm.serialNumber() == current->serialNumber() ) ) - return; - - int oldWidth = current ? current->width() : 0; - int oldHeight = current ? current->height() : 0; - - if ( (int)m_pixmaps.size() <= column ) - m_pixmaps.resize( column+1 ); - - delete current; - m_pixmaps[column] = pm.isNull() ? 0 : new TQPixmap( pm ); - - int newWidth = pm.isNull() ? 0 : pm.width(); - int newHeight = pm.isNull() ? 0 : pm.height(); - - // If the height or width have changed then we're going to have to repaint - // this whole thing. Fortunately since most of the calls are coming from - // setActive() this is the uncommon case. - - if ( oldWidth != newWidth || oldHeight != newHeight ) - { - setup(); - widthChanged( column ); - invalidateHeight(); - return; - } - - // If we're just replacing the icon with another one its size -- i.e. a - // "highlighted" icon, don't bother repainting the whole widget. - - TQListView *lv = m_pListViewWidget; - - int decorationWidth = lv->treeStepSize() * ( depth() + ( lv->rootIsDecorated() ? 1 : 0 ) ); - int x = lv->header()->sectionPos( column ) + decorationWidth + lv->itemMargin(); - int y = lv->itemPos( this ); - int w = newWidth; - int h = height(); - lv->repaintContents( x, y, w, h ); -} - -const TQPixmap* KonqListViewItem::pixmap( int column ) const -{ - bool ok; - if ((int)m_pixmaps.count() <= column) - return 0; - - TQPixmap *pm = m_pixmaps.at( column, &ok ); - if( !ok ) - return 0; - return pm; -} - -int KonqBaseListViewItem::compare( TQListViewItem* item, int col, bool ascending ) const -{ - KonqListViewItem* k = static_cast( item ); - if ( sortChar != k->sortChar ) - // Dirs are always first, even when sorting in descending order - return !ascending ? k->sortChar - sortChar : sortChar - k->sortChar; - - int numExtra = 0; - for ( unsigned int i=0; iNumberOfAtoms; i++ ) - { - ColumnInfo *cInfo = &m_pListViewWidget->columnConfigInfo()[i]; - if ( cInfo->udsId == TDEIO::UDS_EXTRA ) - ++numExtra; - if ( col == cInfo->displayInColumn ) - { - switch ( cInfo->udsId ) - { - case TDEIO::UDS_MODIFICATION_TIME: - case TDEIO::UDS_ACCESS_TIME: - case TDEIO::UDS_CREATION_TIME: - { - time_t t1 = m_fileitem->time( cInfo->udsId ); - time_t t2 = k->m_fileitem->time( cInfo->udsId ); - return ( t1 > t2 ) ? 1 : ( t1 < t2 ) ? -1 : 0; - } - case TDEIO::UDS_SIZE: - { - TDEIO::filesize_t s1 = m_fileitem->size(); - TDEIO::filesize_t s2 = k->m_fileitem->size(); - return ( s1 > s2 ) ? 1 : ( s1 < s2 ) ? -1 : 0; - } - case TDEIO::UDS_EXTRA: - { - if ( cInfo->type & TQVariant::DateTime ) { - const TQString entryStr1 = retrieveExtraEntry( m_fileitem, numExtra ); - TQDateTime dt1 = TQT_TQDATETIME_OBJECT(TQDateTime::fromString( entryStr1, Qt::ISODate )); - const TQString entryStr2 = retrieveExtraEntry( k->m_fileitem, numExtra ); - TQDateTime dt2 = TQT_TQDATETIME_OBJECT(TQDateTime::fromString( entryStr2, Qt::ISODate )); - return ( dt1 > dt2 ) ? 1 : ( dt1 < dt2 ) ? -1 : 0; - } - } - default: - break; - } - break; - } - } - if ( m_pListViewWidget->caseInsensitiveSort() ) - return text( col ).lower().localeAwareCompare( k->text( col ).lower() ); - else { - return m_pListViewWidget->m_pSettings->caseSensitiveCompare( text( col ), k->text( col ) ); - } -} - -void KonqListViewItem::paintCell( TQPainter *_painter, const TQColorGroup & _cg, int _column, int _width, int _alignment ) -{ - TQColorGroup cg( _cg ); - - if ( _column == 0 ) - { - _painter->setFont( m_pListViewWidget->itemFont() ); - } - - cg.setColor( TQColorGroup::Text, m_pListViewWidget->itemColor() ); - - TDEListView *lv = static_cast< TDEListView* >( listView() ); - const TQPixmap *pm = TQT_TQPIXMAP_CONST(lv->viewport()->paletteBackgroundPixmap()); - if ( _column == 0 && isSelected() && !lv->allColumnsShowFocus() ) - { - int newWidth = width( lv->fontMetrics(), lv, _column ); - if ( newWidth > _width ) - newWidth = _width; - if ( pm && !pm->isNull() ) - { - cg.setBrush( TQColorGroup::Base, TQBrush( backgroundColor(_column), *pm ) ); - TQPoint o = _painter->brushOrigin(); - _painter->setBrushOrigin( o.x() - lv->contentsX(), o.y() - lv->contentsY() ); - const TQColorGroup::ColorRole crole = - TQPalette::backgroundRoleFromMode( lv->viewport()->backgroundMode() ); - _painter->fillRect( newWidth, 0, _width - newWidth, height(), cg.brush( crole ) ); - _painter->setBrushOrigin( o ); - } - else - { - _painter->fillRect( newWidth, 0, _width - newWidth, height(), backgroundColor(_column) ); - } - - _width = newWidth; - } - - TDEListViewItem::paintCell( _painter, cg, _column, _width, _alignment ); -} - -void KonqListViewItem::paintFocus( TQPainter * _painter, const TQColorGroup & cg, const TQRect & _r ) -{ - TQRect r( _r ); - TQListView *lv = static_cast< TQListView * >( listView() ); - r.setWidth( width( lv->fontMetrics(), lv, 0 ) ); - if ( r.right() > lv->header()->sectionRect( 0 ).right() ) - r.setRight( lv->header()->sectionRect( 0 ).right() ); - TQListViewItem::paintFocus( _painter, cg, r ); -} - -const char* KonqBaseListViewItem::makeAccessString( const mode_t mode) -{ - static char buffer[ 12 ]; - - char uxbit,gxbit,oxbit; - - if ( (mode & (S_IXUSR|S_ISUID)) == (S_IXUSR|S_ISUID) ) - uxbit = 's'; - else if ( (mode & (S_IXUSR|S_ISUID)) == S_ISUID ) - uxbit = 'S'; - else if ( (mode & (S_IXUSR|S_ISUID)) == S_IXUSR ) - uxbit = 'x'; - else - uxbit = '-'; - - if ( (mode & (S_IXGRP|S_ISGID)) == (S_IXGRP|S_ISGID) ) - gxbit = 's'; - else if ( (mode & (S_IXGRP|S_ISGID)) == S_ISGID ) - gxbit = 'S'; - else if ( (mode & (S_IXGRP|S_ISGID)) == S_IXGRP ) - gxbit = 'x'; - else - gxbit = '-'; - - if ( (mode & (S_IXOTH|S_ISVTX)) == (S_IXOTH|S_ISVTX) ) - oxbit = 't'; - else if ( (mode & (S_IXOTH|S_ISVTX)) == S_ISVTX ) - oxbit = 'T'; - else if ( (mode & (S_IXOTH|S_ISVTX)) == S_IXOTH ) - oxbit = 'x'; - else - oxbit = '-'; - - buffer[0] = ((( mode & S_IRUSR ) == S_IRUSR ) ? 'r' : '-' ); - buffer[1] = ((( mode & S_IWUSR ) == S_IWUSR ) ? 'w' : '-' ); - buffer[2] = uxbit; - buffer[3] = ((( mode & S_IRGRP ) == S_IRGRP ) ? 'r' : '-' ); - buffer[4] = ((( mode & S_IWGRP ) == S_IWGRP ) ? 'w' : '-' ); - buffer[5] = gxbit; - buffer[6] = ((( mode & S_IROTH ) == S_IROTH ) ? 'r' : '-' ); - buffer[7] = ((( mode & S_IWOTH ) == S_IWOTH ) ? 'w' : '-' ); - buffer[8] = oxbit; - buffer[9] = 0; - - return buffer; -} - -KonqBaseListViewItem::KonqBaseListViewItem(KonqBaseListViewWidget *_listViewWidget, KFileItem* _fileitem) -:TDEListViewItem(_listViewWidget) -,sortChar(0) -,m_bDisabled(false) -,m_bActive(false) -,m_fileitem(_fileitem) -,m_fileitemURL(_fileitem->url()) -,m_pListViewWidget(_listViewWidget) -{} - -KonqBaseListViewItem::KonqBaseListViewItem(KonqBaseListViewWidget *_listViewWidget, KonqBaseListViewItem *_parent, KFileItem* _fileitem) -:TDEListViewItem(_parent) -,sortChar(0) -,m_bDisabled(false) -,m_bActive(false) -,m_fileitem(_fileitem) -,m_fileitemURL(_fileitem->url()) -,m_pListViewWidget(_listViewWidget) -{} - -KonqBaseListViewItem::~KonqBaseListViewItem() -{ - if (m_pListViewWidget->m_activeItem == this) - m_pListViewWidget->m_activeItem = 0; - if (m_pListViewWidget->m_dragOverItem == this) - m_pListViewWidget->m_dragOverItem = 0; - - if (m_pListViewWidget->m_selected) - m_pListViewWidget->m_selected->removeRef(this); -} - -TQRect KonqBaseListViewItem::rect() const -{ - TQRect r = m_pListViewWidget->itemRect(this); - return TQRect( m_pListViewWidget->viewportToContents( r.topLeft() ), TQSize( r.width(), r.height() ) ); -} - -void KonqBaseListViewItem::mimetypeFound() -{ - // Update icon - setDisabled( m_bDisabled ); - uint done = 0; - KonqBaseListViewWidget * lv = m_pListViewWidget; - for (unsigned int i=0; iNumberOfAtoms && done < 2; i++) - { - ColumnInfo *tmpColumn=&lv->columnConfigInfo()[i]; - if (lv->columnConfigInfo()[i].udsId==TDEIO::UDS_FILE_TYPE && tmpColumn->displayThisOne) - { - setText(tmpColumn->displayInColumn, m_fileitem->mimeComment()); - done++; - } - if (lv->columnConfigInfo()[i].udsId==TDEIO::UDS_MIME_TYPE && tmpColumn->displayThisOne) - { - setText(tmpColumn->displayInColumn, m_fileitem->mimetype()); - done++; - } - } -} - diff --git a/konqueror/listview/konq_listviewitems.cpp b/konqueror/listview/konq_listviewitems.cpp new file mode 100644 index 000000000..45ff99c1c --- /dev/null +++ b/konqueror/listview/konq_listviewitems.cpp @@ -0,0 +1,459 @@ +/* This file is part of the KDE project + Copyright (C) 1998, 1999 Torben Weis + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "konq_listview.h" +#include +#include +#include +#include +#include +#include +#include +#include + +static TQString retrieveExtraEntry( KFileItem* fileitem, int numExtra ) +{ + /// ######## SLOOOOW + TDEIO::UDSEntry::ConstIterator it = fileitem->entry().begin(); + const TDEIO::UDSEntry::ConstIterator end = fileitem->entry().end(); + int n = 0; + for( ; it != end; ++it ) + { + if ((*it).m_uds == TDEIO::UDS_EXTRA) + { + ++n; + if ( n == numExtra ) + { + return (*it).m_str; + } + } + } + return TQString::null; +} + + +/************************************************************** + * + * KonqListViewItem + * + **************************************************************/ +KonqListViewItem::KonqListViewItem( KonqBaseListViewWidget *_listViewWidget, + KonqListViewItem * _parent, KFileItem* _fileitem ) + : KonqBaseListViewItem( _listViewWidget, _parent, _fileitem ), + m_pixmaps( listView()->columns() ) +{ + updateContents(); +} + +KonqListViewItem::KonqListViewItem( KonqBaseListViewWidget *_listViewWidget, KFileItem* _fileitem ) + : KonqBaseListViewItem( _listViewWidget, _fileitem ), + m_pixmaps( listView()->columns() ) +{ + updateContents(); +} + +KonqListViewItem::~KonqListViewItem() +{ + for ( TQValueVector::iterator + it = m_pixmaps.begin(), itEnd = m_pixmaps.end(); + it != itEnd; ++it ) + delete *it; +} + +void KonqListViewItem::updateContents() +{ + // Set the pixmap + setDisabled( m_bDisabled ); + + // Set the text of each column + setText( 0, m_fileitem->text() ); + + // The order is: .dir (0), dir (1), .file (2), file (3) + sortChar = S_ISDIR( m_fileitem->mode() ) ? 1 : 3; + if ( m_fileitem->text()[0] == '.' ) + --sortChar; + + //now we have the first column, so let's do the rest + + int numExtra = 1; + for ( unsigned int i=0; iNumberOfAtoms; i++ ) + { + ColumnInfo *tmpColumn=&m_pListViewWidget->columnConfigInfo()[i]; + if (tmpColumn->displayThisOne) + { + switch (tmpColumn->udsId) + { + case TDEIO::UDS_USER: + setText(tmpColumn->displayInColumn,m_fileitem->user()); + break; + case TDEIO::UDS_GROUP: + setText(tmpColumn->displayInColumn,m_fileitem->group()); + break; + case TDEIO::UDS_FILE_TYPE: + if (m_fileitem->isMimeTypeKnown()) { + setText(tmpColumn->displayInColumn,m_fileitem->mimeComment()); + } + break; + case TDEIO::UDS_MIME_TYPE: + if (m_fileitem->isMimeTypeKnown()) { + setText(tmpColumn->displayInColumn,m_fileitem->mimetype()); + } + break; + case TDEIO::UDS_URL: + setText(tmpColumn->displayInColumn,m_fileitem->url().prettyURL()); + break; + case TDEIO::UDS_LINK_DEST: + setText(tmpColumn->displayInColumn,m_fileitem->linkDest()); + break; + case TDEIO::UDS_SIZE: + if ( m_pListViewWidget->m_pSettings->fileSizeInBytes() ) + setText(tmpColumn->displayInColumn,TDEGlobal::locale()->formatNumber( m_fileitem->size(),0)+" "); + else + setText(tmpColumn->displayInColumn,TDEIO::convertSize(m_fileitem->size())+" "); + break; + case TDEIO::UDS_ACCESS: + setText(tmpColumn->displayInColumn,m_fileitem->permissionsString()); + break; + case TDEIO::UDS_MODIFICATION_TIME: + case TDEIO::UDS_ACCESS_TIME: + case TDEIO::UDS_CREATION_TIME: + { + TQDateTime dt; + time_t _time = m_fileitem->time( tmpColumn->udsId ); + if ( _time != 0 ) + { + dt.setTime_t( _time ); + setText(tmpColumn->displayInColumn, TDEGlobal::locale()->formatDateTime(dt)); + } + else + { + setText(tmpColumn->displayInColumn, TQString::null); + } + } + break; + case TDEIO::UDS_EXTRA: + { + const TQString entryStr = retrieveExtraEntry( m_fileitem, numExtra ); + if ( tmpColumn->type == TQVariant::DateTime ) + { + TQDateTime dt = TQT_TQDATETIME_OBJECT(TQDateTime::fromString( entryStr, Qt::ISODate )); + setText(tmpColumn->displayInColumn, + TDEGlobal::locale()->formatDateTime(dt)); + } + else // if ( tmpColumn->type == TQVariant::String ) + setText(tmpColumn->displayInColumn, entryStr); + ++numExtra; + break; + } + default: + break; + }; + }; + }; +} + +void KonqListViewItem::setDisabled( bool disabled ) +{ + KonqBaseListViewItem::setDisabled( disabled ); + int iconSize = m_pListViewWidget->iconSize(); + iconSize = iconSize ? iconSize : TDEGlobal::iconLoader()->currentSize( TDEIcon::Small ); // Default = small + setPixmap( 0, m_fileitem->pixmap( iconSize, state() ) ); +} + +void KonqListViewItem::setActive( bool active ) +{ + if ( m_bActive == active ) + return; + + //#### Optimize away repaint if possible, like the iconview does? + KonqBaseListViewItem::setActive( active ); + int iconSize = m_pListViewWidget->iconSize(); + iconSize = iconSize ? iconSize : TDEGlobal::iconLoader()->currentSize( TDEIcon::Small ); // Default = small + setPixmap( 0, m_fileitem->pixmap( iconSize, state() ) ); +} + +void KonqListViewItem::setPixmap( int column, const TQPixmap& pm ) +{ + if ( column < 0 ) + return; + + const TQPixmap *current = pixmap( column ); + + if ( ( pm.isNull() && !current ) || + ( current && pm.serialNumber() == current->serialNumber() ) ) + return; + + int oldWidth = current ? current->width() : 0; + int oldHeight = current ? current->height() : 0; + + if ( (int)m_pixmaps.size() <= column ) + m_pixmaps.resize( column+1 ); + + delete current; + m_pixmaps[column] = pm.isNull() ? 0 : new TQPixmap( pm ); + + int newWidth = pm.isNull() ? 0 : pm.width(); + int newHeight = pm.isNull() ? 0 : pm.height(); + + // If the height or width have changed then we're going to have to repaint + // this whole thing. Fortunately since most of the calls are coming from + // setActive() this is the uncommon case. + + if ( oldWidth != newWidth || oldHeight != newHeight ) + { + setup(); + widthChanged( column ); + invalidateHeight(); + return; + } + + // If we're just replacing the icon with another one its size -- i.e. a + // "highlighted" icon, don't bother repainting the whole widget. + + TQListView *lv = m_pListViewWidget; + + int decorationWidth = lv->treeStepSize() * ( depth() + ( lv->rootIsDecorated() ? 1 : 0 ) ); + int x = lv->header()->sectionPos( column ) + decorationWidth + lv->itemMargin(); + int y = lv->itemPos( this ); + int w = newWidth; + int h = height(); + lv->repaintContents( x, y, w, h ); +} + +const TQPixmap* KonqListViewItem::pixmap( int column ) const +{ + bool ok; + if ((int)m_pixmaps.count() <= column) + return 0; + + TQPixmap *pm = m_pixmaps.at( column, &ok ); + if( !ok ) + return 0; + return pm; +} + +int KonqBaseListViewItem::compare( TQListViewItem* item, int col, bool ascending ) const +{ + KonqListViewItem* k = static_cast( item ); + if ( sortChar != k->sortChar ) + // Dirs are always first, even when sorting in descending order + return !ascending ? k->sortChar - sortChar : sortChar - k->sortChar; + + int numExtra = 0; + for ( unsigned int i=0; iNumberOfAtoms; i++ ) + { + ColumnInfo *cInfo = &m_pListViewWidget->columnConfigInfo()[i]; + if ( cInfo->udsId == TDEIO::UDS_EXTRA ) + ++numExtra; + if ( col == cInfo->displayInColumn ) + { + switch ( cInfo->udsId ) + { + case TDEIO::UDS_MODIFICATION_TIME: + case TDEIO::UDS_ACCESS_TIME: + case TDEIO::UDS_CREATION_TIME: + { + time_t t1 = m_fileitem->time( cInfo->udsId ); + time_t t2 = k->m_fileitem->time( cInfo->udsId ); + return ( t1 > t2 ) ? 1 : ( t1 < t2 ) ? -1 : 0; + } + case TDEIO::UDS_SIZE: + { + TDEIO::filesize_t s1 = m_fileitem->size(); + TDEIO::filesize_t s2 = k->m_fileitem->size(); + return ( s1 > s2 ) ? 1 : ( s1 < s2 ) ? -1 : 0; + } + case TDEIO::UDS_EXTRA: + { + if ( cInfo->type & TQVariant::DateTime ) { + const TQString entryStr1 = retrieveExtraEntry( m_fileitem, numExtra ); + TQDateTime dt1 = TQT_TQDATETIME_OBJECT(TQDateTime::fromString( entryStr1, Qt::ISODate )); + const TQString entryStr2 = retrieveExtraEntry( k->m_fileitem, numExtra ); + TQDateTime dt2 = TQT_TQDATETIME_OBJECT(TQDateTime::fromString( entryStr2, Qt::ISODate )); + return ( dt1 > dt2 ) ? 1 : ( dt1 < dt2 ) ? -1 : 0; + } + } + default: + break; + } + break; + } + } + if ( m_pListViewWidget->caseInsensitiveSort() ) + return text( col ).lower().localeAwareCompare( k->text( col ).lower() ); + else { + return m_pListViewWidget->m_pSettings->caseSensitiveCompare( text( col ), k->text( col ) ); + } +} + +void KonqListViewItem::paintCell( TQPainter *_painter, const TQColorGroup & _cg, int _column, int _width, int _alignment ) +{ + TQColorGroup cg( _cg ); + + if ( _column == 0 ) + { + _painter->setFont( m_pListViewWidget->itemFont() ); + } + + cg.setColor( TQColorGroup::Text, m_pListViewWidget->itemColor() ); + + TDEListView *lv = static_cast< TDEListView* >( listView() ); + const TQPixmap *pm = TQT_TQPIXMAP_CONST(lv->viewport()->paletteBackgroundPixmap()); + if ( _column == 0 && isSelected() && !lv->allColumnsShowFocus() ) + { + int newWidth = width( lv->fontMetrics(), lv, _column ); + if ( newWidth > _width ) + newWidth = _width; + if ( pm && !pm->isNull() ) + { + cg.setBrush( TQColorGroup::Base, TQBrush( backgroundColor(_column), *pm ) ); + TQPoint o = _painter->brushOrigin(); + _painter->setBrushOrigin( o.x() - lv->contentsX(), o.y() - lv->contentsY() ); + const TQColorGroup::ColorRole crole = + TQPalette::backgroundRoleFromMode( lv->viewport()->backgroundMode() ); + _painter->fillRect( newWidth, 0, _width - newWidth, height(), cg.brush( crole ) ); + _painter->setBrushOrigin( o ); + } + else + { + _painter->fillRect( newWidth, 0, _width - newWidth, height(), backgroundColor(_column) ); + } + + _width = newWidth; + } + + TDEListViewItem::paintCell( _painter, cg, _column, _width, _alignment ); +} + +void KonqListViewItem::paintFocus( TQPainter * _painter, const TQColorGroup & cg, const TQRect & _r ) +{ + TQRect r( _r ); + TQListView *lv = static_cast< TQListView * >( listView() ); + r.setWidth( width( lv->fontMetrics(), lv, 0 ) ); + if ( r.right() > lv->header()->sectionRect( 0 ).right() ) + r.setRight( lv->header()->sectionRect( 0 ).right() ); + TQListViewItem::paintFocus( _painter, cg, r ); +} + +const char* KonqBaseListViewItem::makeAccessString( const mode_t mode) +{ + static char buffer[ 12 ]; + + char uxbit,gxbit,oxbit; + + if ( (mode & (S_IXUSR|S_ISUID)) == (S_IXUSR|S_ISUID) ) + uxbit = 's'; + else if ( (mode & (S_IXUSR|S_ISUID)) == S_ISUID ) + uxbit = 'S'; + else if ( (mode & (S_IXUSR|S_ISUID)) == S_IXUSR ) + uxbit = 'x'; + else + uxbit = '-'; + + if ( (mode & (S_IXGRP|S_ISGID)) == (S_IXGRP|S_ISGID) ) + gxbit = 's'; + else if ( (mode & (S_IXGRP|S_ISGID)) == S_ISGID ) + gxbit = 'S'; + else if ( (mode & (S_IXGRP|S_ISGID)) == S_IXGRP ) + gxbit = 'x'; + else + gxbit = '-'; + + if ( (mode & (S_IXOTH|S_ISVTX)) == (S_IXOTH|S_ISVTX) ) + oxbit = 't'; + else if ( (mode & (S_IXOTH|S_ISVTX)) == S_ISVTX ) + oxbit = 'T'; + else if ( (mode & (S_IXOTH|S_ISVTX)) == S_IXOTH ) + oxbit = 'x'; + else + oxbit = '-'; + + buffer[0] = ((( mode & S_IRUSR ) == S_IRUSR ) ? 'r' : '-' ); + buffer[1] = ((( mode & S_IWUSR ) == S_IWUSR ) ? 'w' : '-' ); + buffer[2] = uxbit; + buffer[3] = ((( mode & S_IRGRP ) == S_IRGRP ) ? 'r' : '-' ); + buffer[4] = ((( mode & S_IWGRP ) == S_IWGRP ) ? 'w' : '-' ); + buffer[5] = gxbit; + buffer[6] = ((( mode & S_IROTH ) == S_IROTH ) ? 'r' : '-' ); + buffer[7] = ((( mode & S_IWOTH ) == S_IWOTH ) ? 'w' : '-' ); + buffer[8] = oxbit; + buffer[9] = 0; + + return buffer; +} + +KonqBaseListViewItem::KonqBaseListViewItem(KonqBaseListViewWidget *_listViewWidget, KFileItem* _fileitem) +:TDEListViewItem(_listViewWidget) +,sortChar(0) +,m_bDisabled(false) +,m_bActive(false) +,m_fileitem(_fileitem) +,m_fileitemURL(_fileitem->url()) +,m_pListViewWidget(_listViewWidget) +{} + +KonqBaseListViewItem::KonqBaseListViewItem(KonqBaseListViewWidget *_listViewWidget, KonqBaseListViewItem *_parent, KFileItem* _fileitem) +:TDEListViewItem(_parent) +,sortChar(0) +,m_bDisabled(false) +,m_bActive(false) +,m_fileitem(_fileitem) +,m_fileitemURL(_fileitem->url()) +,m_pListViewWidget(_listViewWidget) +{} + +KonqBaseListViewItem::~KonqBaseListViewItem() +{ + if (m_pListViewWidget->m_activeItem == this) + m_pListViewWidget->m_activeItem = 0; + if (m_pListViewWidget->m_dragOverItem == this) + m_pListViewWidget->m_dragOverItem = 0; + + if (m_pListViewWidget->m_selected) + m_pListViewWidget->m_selected->removeRef(this); +} + +TQRect KonqBaseListViewItem::rect() const +{ + TQRect r = m_pListViewWidget->itemRect(this); + return TQRect( m_pListViewWidget->viewportToContents( r.topLeft() ), TQSize( r.width(), r.height() ) ); +} + +void KonqBaseListViewItem::mimetypeFound() +{ + // Update icon + setDisabled( m_bDisabled ); + uint done = 0; + KonqBaseListViewWidget * lv = m_pListViewWidget; + for (unsigned int i=0; iNumberOfAtoms && done < 2; i++) + { + ColumnInfo *tmpColumn=&lv->columnConfigInfo()[i]; + if (lv->columnConfigInfo()[i].udsId==TDEIO::UDS_FILE_TYPE && tmpColumn->displayThisOne) + { + setText(tmpColumn->displayInColumn, m_fileitem->mimeComment()); + done++; + } + if (lv->columnConfigInfo()[i].udsId==TDEIO::UDS_MIME_TYPE && tmpColumn->displayThisOne) + { + setText(tmpColumn->displayInColumn, m_fileitem->mimetype()); + done++; + } + } +} + diff --git a/konqueror/listview/konq_listviewwidget.cc b/konqueror/listview/konq_listviewwidget.cc deleted file mode 100644 index 4c1198325..000000000 --- a/konqueror/listview/konq_listviewwidget.cc +++ /dev/null @@ -1,1592 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 1998, 1999 Torben Weis - 2001, 2002, 2004 Michael Brade - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "konq_listview.h" -#include "konq_listviewsettings.h" -#include "konq_listviewwidget.h" -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -ColumnInfo::ColumnInfo() - :displayInColumn(-1) - ,name() - ,desktopFileName() - ,udsId(0) - ,type(TQVariant::Invalid) - ,displayThisOne(false) - ,toggleThisOne(0) -{} - - -void ColumnInfo::setData(const TQString& n, const TQString& desktopName, int kioUds, - TDEToggleAction* someAction, int theWidth) -{ - displayInColumn=-1; - name=n; - desktopFileName=desktopName; - udsId=kioUds; - type=TQVariant::Invalid; - displayThisOne=false; - toggleThisOne=someAction; - width=theWidth; -} - -void ColumnInfo::setData(const TQString& n, const TQString& desktopName, int kioUds, - TQVariant::Type t, TDEToggleAction* someAction, int theWidth) -{ - displayInColumn=-1; - name=n; - desktopFileName=desktopName; - udsId=kioUds; - type=t; - displayThisOne=false; - toggleThisOne=someAction; - width=theWidth; -} - - -KonqBaseListViewWidget::KonqBaseListViewWidget( KonqListView *parent, TQWidget *parentWidget) - : TDEListView(parentWidget) - ,sortedByColumn(0) - ,m_pBrowserView(parent) - ,m_dirLister(new KDirLister( true /*m_showIcons==false*/)) - ,m_dragOverItem(0) - ,m_activeItem(0) - ,m_selected(0) - ,m_scrollTimer(0) - ,m_rubber(0) - ,m_showIcons(true) - ,m_bCaseInsensitive(true) - ,m_bUpdateContentsPosAfterListing(false) - ,m_bAscending(true) - ,m_itemFound(false) - ,m_restored(false) - ,m_filenameColumn(0) - ,m_itemToGoTo("") - ,m_backgroundTimer(0) - ,m_fileTip(new KonqFileTip(this)) -{ - kdDebug(1202) << "+KonqBaseListViewWidget" << endl; - - m_dirLister->setMainWindow(topLevelWidget()); - - m_bTopLevelComplete = true; - - //Adjust TDEListView behaviour - setMultiSelection(true); - setSelectionModeExt( FileManager ); - setDragEnabled(true); - setItemsMovable(false); - setUseSmallExecuteArea(true); - - initConfig(); -#if 0 - connect( this, TQT_SIGNAL(rightButtonPressed(TQListViewItem*,const TQPoint&,int)), - this, TQT_SLOT(slotRightButtonPressed(TQListViewItem*,const TQPoint&,int))); -#endif - connect( this, TQT_SIGNAL(returnPressed( TQListViewItem * )), - this, TQT_SLOT(slotReturnPressed( TQListViewItem * )) ); - connect( this, TQT_SIGNAL(mouseButtonClicked( int, TQListViewItem *, const TQPoint&, int )), - this, TQT_SLOT(slotMouseButtonClicked2( int, TQListViewItem *, const TQPoint&, int )) ); - connect( this, TQT_SIGNAL(executed( TQListViewItem * )), - this, TQT_SLOT(slotExecuted( TQListViewItem * )) ); - connect( this, TQT_SIGNAL(currentChanged( TQListViewItem * )), - this, TQT_SLOT(slotCurrentChanged( TQListViewItem * )) ); - connect( this, TQT_SIGNAL(itemRenamed( TQListViewItem *, const TQString &, int )), - this, TQT_SLOT(slotItemRenamed( TQListViewItem *, const TQString &, int )) ); - connect( this, TQT_SIGNAL(contextMenuRequested( TQListViewItem *, const TQPoint&, int )), - this, TQT_SLOT(slotPopupMenu( TQListViewItem *, const TQPoint&, int )) ); - connect( this, TQT_SIGNAL(renameNext( TQListViewItem *, int )), - this, TQT_SLOT(slotRenameNextItem( TQListViewItem*, int)) ); - connect( this, TQT_SIGNAL(renamePrev( TQListViewItem *, int )), - this, TQT_SLOT(slotRenamePrevItem( TQListViewItem*, int)) ); - connect( this, TQT_SIGNAL(selectionChanged()), this, TQT_SLOT(slotSelectionChanged()) ); - - connect( horizontalScrollBar(), TQT_SIGNAL(valueChanged( int )), - this, TQT_SIGNAL(viewportAdjusted()) ); - connect( verticalScrollBar(), TQT_SIGNAL(valueChanged( int )), - this, TQT_SIGNAL(viewportAdjusted()) ); - - // Connect the directory lister - connect( m_dirLister, TQT_SIGNAL(started( const KURL & )), - this, TQT_SLOT(slotStarted()) ); - connect( m_dirLister, TQT_SIGNAL(completed()), this, TQT_SLOT(slotCompleted()) ); - connect( m_dirLister, TQT_SIGNAL(canceled()), this, TQT_SLOT(slotCanceled()) ); - connect( m_dirLister, TQT_SIGNAL(clear()), this, TQT_SLOT(slotClear()) ); - connect( m_dirLister, TQT_SIGNAL(newItems( const KFileItemList & ) ), - this, TQT_SLOT(slotNewItems( const KFileItemList & )) ); - connect( m_dirLister, TQT_SIGNAL(deleteItem( KFileItem * )), - this, TQT_SLOT(slotDeleteItem( KFileItem * )) ); - connect( m_dirLister, TQT_SIGNAL(refreshItems( const KFileItemList & )), - this, TQT_SLOT( slotRefreshItems( const KFileItemList & )) ); - connect( m_dirLister, TQT_SIGNAL(redirection( const KURL & )), - this, TQT_SLOT(slotRedirection( const KURL & )) ); - connect( m_dirLister, TQT_SIGNAL(itemsFilteredByMime( const KFileItemList & )), - m_pBrowserView, TQT_SIGNAL(itemsFilteredByMime( const KFileItemList & )) ); - - connect( m_dirLister, TQT_SIGNAL(infoMessage( const TQString& )), - m_pBrowserView->extension(), TQT_SIGNAL(infoMessage( const TQString& )) ); - connect( m_dirLister, TQT_SIGNAL(percent( int )), - m_pBrowserView->extension(), TQT_SIGNAL(loadingProgress( int )) ); - connect( m_dirLister, TQT_SIGNAL(speed( int )), - m_pBrowserView->extension(), TQT_SIGNAL(speedProgress( int )) ); - - connect( header(), TQT_SIGNAL(sizeChange( int, int, int )), TQT_SLOT(slotUpdateBackground()) ); - - viewport()->setMouseTracking( true ); - viewport()->setFocusPolicy( TQ_WheelFocus ); - setFocusPolicy( TQ_WheelFocus ); - setAcceptDrops( true ); - - //looks better with the statusbar - setFrameStyle( TQFrame::StyledPanel | TQFrame::Sunken ); - setShowSortIndicator( true ); -} - -KonqBaseListViewWidget::~KonqBaseListViewWidget() -{ - kdDebug(1202) << "-KonqBaseListViewWidget" << endl; - - delete m_selected; m_selected = 0; - - // TODO: this is a hack, better fix the connections of m_dirLister if possible! - m_dirLister->disconnect( this ); - delete m_dirLister; - - delete m_fileTip; -} - -void KonqBaseListViewWidget::readProtocolConfig( const KURL & url ) -{ - const TQString protocol = url.protocol(); - KonqListViewSettings config( protocol ); - config.readConfig(); - sortedByColumn = config.sortBy(); - m_bAscending = config.sortOrder(); - - m_filenameColumnWidth = config.fileNameColumnWidth(); - - TQStringList lstColumns = config.columns(); - TQValueList lstColumnWidths = config.columnWidths(); - if (lstColumns.isEmpty()) - { - // Default column selection - lstColumns.append( "Size" ); - lstColumns.append( "File Type" ); - lstColumns.append( "Modified" ); - lstColumns.append( "Permissions" ); - lstColumns.append( "Owner" ); - lstColumns.append( "Group" ); - lstColumns.append( "Link" ); - } - - // Default number of columns - NumberOfAtoms = 11; - int extraIndex = NumberOfAtoms; - - // Check for any extra data - KProtocolInfo::ExtraFieldList extraFields = KProtocolInfo::extraFields(url); - NumberOfAtoms += extraFields.count(); - confColumns.resize( NumberOfAtoms ); - - KProtocolInfo::ExtraFieldList::Iterator extraFieldsIt = extraFields.begin(); - for ( int num = 1; extraFieldsIt != extraFields.end(); ++extraFieldsIt, ++num ) - { - const TQString column = (*extraFieldsIt).name; - if ( lstColumns.find(column) == lstColumns.end() ) - lstColumns << column; - const TQString type = (*extraFieldsIt).type; // ## TODO use when sorting - TQVariant::Type t = TQVariant::Invalid; - if ( type.lower() == TQString(TQSTRING_OBJECT_NAME_STRING).lower() ) - t = TQVariant::String; - else if ( type.lower() == TQString(TQDATETIME_OBJECT_NAME_STRING).lower() ) - t = TQVariant::DateTime; - else - kdWarning() << "Unsupported ExtraType '" << type << "'" << endl; - confColumns[extraIndex++].setData( column, TQString("Extra%1").arg(num), TDEIO::UDS_EXTRA, t, 0); - } - - //disable everything - for ( unsigned int i = 0; i < NumberOfAtoms; i++ ) - { - confColumns[i].displayThisOne = false; - confColumns[i].displayInColumn = -1; - if ( confColumns[i].toggleThisOne ) - { - confColumns[i].toggleThisOne->setChecked( false ); - confColumns[i].toggleThisOne->setEnabled( true ); - } - } - int currentColumn = m_filenameColumn + 1; - //check all columns in lstColumns - for ( unsigned int i = 0; i < lstColumns.count(); i++ ) - { - //search the column in confColumns - for ( unsigned int j = 0; j < NumberOfAtoms; j++ ) - { - if ( confColumns[j].name == *lstColumns.at(i) ) - { - confColumns[j].displayThisOne = true; - confColumns[j].displayInColumn = currentColumn; - if ( confColumns[j].toggleThisOne ) - confColumns[j].toggleThisOne->setChecked( true ); - currentColumn++; - - if ( i < lstColumnWidths.count() ) - confColumns[j].width = *lstColumnWidths.at(i); - else - { - // Default Column widths - ColumnInfo *tmpColumn = &confColumns[j]; - TQString str; - - if ( tmpColumn->udsId == TDEIO::UDS_SIZE ) - str = TDEGlobal::locale()->formatNumber( 888888888, 0 ) + " "; - else if ( tmpColumn->udsId == TDEIO::UDS_ACCESS ) - str = "--Permissions--"; - else if ( tmpColumn->udsId == TDEIO::UDS_USER ) - str = "a_long_username"; - else if ( tmpColumn->udsId == TDEIO::UDS_GROUP ) - str = "a_groupname"; - else if ( tmpColumn->udsId == TDEIO::UDS_LINK_DEST ) - str = "a_quite_long_filename_for_link_dest"; - else if ( tmpColumn->udsId == TDEIO::UDS_FILE_TYPE ) - str = "a_long_comment_for_mimetype"; - else if ( tmpColumn->udsId == TDEIO::UDS_MIME_TYPE ) - str = "_a_long_/_mimetype_"; - else if ( tmpColumn->udsId == TDEIO::UDS_URL ) - str = "a_long_lonq_long_very_long_url"; - else if ( (tmpColumn->udsId & TDEIO::UDS_TIME) - || (tmpColumn->udsId == TDEIO::UDS_EXTRA && - (tmpColumn->type & TQVariant::DateTime)) ) - { - TQDateTime dt( TQDate( 2000, 10, 10 ), TQTime( 20, 20, 20 ) ); - str = TDEGlobal::locale()->formatDateTime( dt ) + "--"; - } - else - str = "it_is_the_default_width"; - - confColumns[j].width = fontMetrics().width(str); - } - break; - } - } - } - //check what the protocol provides - TQStringList listingList = KProtocolInfo::listing( url ); - kdDebug(1202) << k_funcinfo << "protocol: " << protocol << endl; - - // Even if this is not given by the protocol, we can determine it. - // Please don't remove this ;-). It makes it possible to show the file type - // using the mimetype comment, which for most users is a nicer alternative - // than the raw mimetype name. - listingList.append( "MimeType" ); - for ( unsigned int i = 0; i < NumberOfAtoms; i++ ) - { - if ( confColumns[i].udsId == TDEIO::UDS_URL || - confColumns[i].udsId == TDEIO::UDS_MIME_TYPE || - !confColumns[i].displayThisOne ) - { - continue; - } - - TQStringList::Iterator listIt = listingList.find( confColumns[i].desktopFileName ); - if ( listIt == listingList.end() ) // not found -> hide - { - //move all columns behind one to the front - for ( unsigned int l = 0; l < NumberOfAtoms; l++ ) - if ( confColumns[l].displayInColumn > confColumns[i].displayInColumn ) - confColumns[l].displayInColumn--; - - //disable this column - confColumns[i].displayThisOne = false; - if ( confColumns[i].toggleThisOne ) - { - confColumns[i].toggleThisOne->setEnabled( false ); - confColumns[i].toggleThisOne->setChecked( false ); - } - } - } -} - -void KonqBaseListViewWidget::createColumns() -{ - //this column is always required, so add it - if ( columns() < 1 ) - addColumn( i18n("Name"), m_filenameColumnWidth ); - setSorting( 0, true ); - - //remove all columns that will be re-added - for ( int i=columns()-1; i>m_filenameColumn; i--) - removeColumn(i); - - //now add the checked columns - int currentColumn = m_filenameColumn + 1; - for ( int i = 0; i < (int)NumberOfAtoms; i++ ) - { - if ( confColumns[i].displayThisOne && (confColumns[i].displayInColumn == currentColumn) ) - { - addColumn( i18n(confColumns[i].name.utf8()), confColumns[i].width ); - if ( sortedByColumn == confColumns[i].desktopFileName ) - setSorting( currentColumn, m_bAscending ); - if ( confColumns[i].udsId == TDEIO::UDS_SIZE ) - setColumnAlignment( currentColumn, AlignRight ); - i = -1; - currentColumn++; - } - } - if ( sortedByColumn == "FileName" ) - setSorting( 0, m_bAscending ); -} - -void KonqBaseListViewWidget::stop() -{ - m_dirLister->stop(); -} - -const KURL & KonqBaseListViewWidget::url() -{ - return m_url; -} - -void KonqBaseListViewWidget::initConfig() -{ - m_pSettings = KonqFMSettings::settings(); - - TQFont stdFont( m_pSettings->standardFont() ); - setFont( stdFont ); - //TODO: create config GUI - TQFont itemFont( m_pSettings->standardFont() ); - itemFont.setUnderline( m_pSettings->underlineLink() ); - setItemFont( itemFont ); - setItemColor( m_pSettings->normalTextColor() ); - - bool on = m_pSettings->showFileTips() && TQToolTip::isGloballyEnabled(); - m_fileTip->setOptions( on, m_pSettings->showPreviewsInFileTips(), m_pSettings->numFileTips() ); - - updateListContents(); -} - -void KonqBaseListViewWidget::contentsMousePressEvent( TQMouseEvent *e ) { - if ( m_rubber ) { - TQRect r( m_rubber->normalize() ); - delete m_rubber; - m_rubber = 0; - repaintContents( r, FALSE ); - } - - delete m_selected; - m_selected = new TQPtrList; - - TQPoint vp = contentsToViewport( e->pos() ); - KonqBaseListViewItem* item = isExecuteArea( vp ) ? - static_cast( itemAt( vp ) ) : 0L; - - if ( item ) { - TDEListView::contentsMousePressEvent( e ); - } - else { - if ( e->button() == Qt::LeftButton ) { - m_rubber = new TQRect( e->x(), e->y(), 0, 0 ); - clearSelection(); - emit selectionChanged(); - m_fileTip->setItem( 0 ); - } - if ( e->button() != Qt::RightButton ) { - TQListView::contentsMousePressEvent( e ); - } - } - - // Store list of selected items at mouse-press time. - // This is used when autoscrolling (why?) - // and during dnd (the target item is temporarily selected) - selectedItems( m_selected ); -} - -void KonqBaseListViewWidget::contentsMouseReleaseEvent( TQMouseEvent *e ) { - if ( m_rubber ) { - resetKeyboardSelectionOperation(); - TQRect r( m_rubber->normalize() ); - delete m_rubber; - m_rubber = 0; - repaintContents( r, FALSE ); - } - - if ( m_scrollTimer ) { - disconnect( m_scrollTimer, TQT_SIGNAL( timeout() ), this, TQT_SLOT( slotAutoScroll() ) ); - m_scrollTimer->stop(); - delete m_scrollTimer; - m_scrollTimer = 0; - } - - delete m_selected; m_selected = 0; - TDEListView::contentsMouseReleaseEvent( e ); -} - -void KonqBaseListViewWidget::contentsMouseMoveEvent( TQMouseEvent *e ) -{ - if ( m_rubber ) - { - slotAutoScroll(); - return; - } - - TQPoint vp = contentsToViewport( e->pos() ); - KonqBaseListViewItem* item = isExecuteArea( vp ) ? - static_cast( itemAt( vp ) ) : 0; - - if ( item != m_activeItem ) - { - if ( m_activeItem != 0 ) - m_activeItem->setActive( false ); - - m_activeItem = item; - - if ( item ) - { - item->setActive( true ); - emit m_pBrowserView->setStatusBarText( item->item()->getStatusBarInfo() ); - m_pBrowserView->emitMouseOver( item->item() ); - - vp.setY( itemRect( item ).y() ); - TQRect rect( viewportToContents( vp ), TQSize(20, item->height()) ); - m_fileTip->setItem( item->item(), rect, item->pixmap( 0 ) ); - m_fileTip->setPreview( TDEGlobalSettings::showFilePreview( item->item()->url() ) ); - setShowToolTips( !m_pSettings->showFileTips() ); - } - else - { - reportItemCounts(); - m_pBrowserView->emitMouseOver( 0 ); - - m_fileTip->setItem( 0 ); - setShowToolTips( true ); - } - } - - TDEListView::contentsMouseMoveEvent( e ); -} - -void KonqBaseListViewWidget::contentsWheelEvent( TQWheelEvent *e ) -{ - // when scrolling with mousewheel, stop possible pending filetip - m_fileTip->setItem( 0 ); - - if ( m_activeItem != 0 ) - { - m_activeItem->setActive( false ); - m_activeItem = 0; - } - - reportItemCounts(); - m_pBrowserView->emitMouseOver( 0 ); - TDEListView::contentsWheelEvent( e ); -} - -void KonqBaseListViewWidget::contentsMouseDoubleClickEvent(TQMouseEvent *e) -{ - if (m_rubber) { - TQRect r(m_rubber->normalize()); - delete m_rubber; - m_rubber = NULL; - repaintContents(r, false); - } - - TQPoint vp = contentsToViewport(e->pos()); - KonqBaseListViewItem* item = isExecuteArea(vp) ? - static_cast(itemAt(vp)) : NULL; - - if (item) { - TDEListView::contentsMouseDoubleClickEvent(e); - } - else { - KParts::URLArgs args; - args.trustedSource = true; - KURL upURL = m_dirLister->url().upURL(); - if (!upURL.isEmpty()) { - m_pBrowserView->extension()->openURLRequest(upURL, args); - } - } -} - -void KonqBaseListViewWidget::leaveEvent( TQEvent *e ) -{ - if ( m_activeItem != 0 ) - { - m_activeItem->setActive( false ); - m_activeItem = 0; - } - - reportItemCounts(); - m_pBrowserView->emitMouseOver( 0 ); - - m_fileTip->setItem( 0 ); - - TDEListView::leaveEvent( e ); -} - -void KonqBaseListViewWidget::drawRubber( TQPainter *p ) -{ - if ( !m_rubber ) - return; - - p->setRasterOp( NotROP ); - p->setPen( TQPen( color0, 1 ) ); - p->setBrush( NoBrush ); - - TQPoint pt( m_rubber->x(), m_rubber->y() ); - pt = contentsToViewport( pt ); - style().tqdrawPrimitive( TQStyle::PE_RubberBand, p, - TQRect( pt.x(), pt.y(), m_rubber->width(), m_rubber->height() ), - colorGroup(), TQStyle::Style_Default, colorGroup().base() ); -} - -void KonqBaseListViewWidget::slotAutoScroll() -{ - if ( !m_rubber ) - return; - - // this code assumes that all items have the same height - - const TQPoint pos = viewport()->mapFromGlobal( TQCursor::pos() ); - const TQPoint vc = viewportToContents( pos ); - TQListViewItem *at = itemAt( vc ); - - if ( vc == m_rubber->bottomRight() ) - return; - - TQRect oldRubber = *m_rubber; - - const int oldTop = m_rubber->normalize().top(); - const int oldBottom = m_rubber->normalize().bottom(); - - - m_rubber->setBottomRight( vc ); - - TQListViewItem *cur = itemAt( TQPoint(0,0) ); - - bool block = signalsBlocked(); - blockSignals( true ); - - TQRect rr; - TQRect nr = m_rubber->normalize(); - bool changed = FALSE; - - if ( cur ) - { - TQRect rect; - if ( allColumnsShowFocus() ) - rect = itemRect( cur ); - else { - rect = itemRect( cur ); - rect.setWidth( executeArea( cur ) ); - } - - - rect = TQRect( viewportToContents( rect.topLeft() ), - viewportToContents( rect.bottomRight() ) ); - - if ( !allColumnsShowFocus() ) - { - rect.setLeft( header()->sectionPos( 0 ) ); - rect.setWidth( rect.width() ); - } - else - { - rect.setLeft( 0 ); - rect.setWidth( header()->headerWidth() ); - } - - TQRect r = rect; - TQListViewItem *tmp = cur; - - while ( cur && rect.top() <= oldBottom ) - { - if ( rect.intersects( nr ) ) - { - if ( !cur->isSelected() && cur->isSelectable() ) - { - setSelected( cur, true ); - setActiveMultiSelectItem( at ); - changed = TRUE; - rr = rr.unite( itemRect( cur ) ); - } - } - else - { - if ( cur->isSelected() ) - { - changed = TRUE; - rr = rr.unite( itemRect( cur ) ); - } - - if ( !m_selected || !m_selected->contains( (KonqBaseListViewItem*)cur ) ) - { - setSelected( cur, false ); - setActiveMultiSelectItem( at ); - } - } - - - cur = cur->itemBelow(); - if (cur && !allColumnsShowFocus()) - rect.setWidth( executeArea( cur ) ); - rect.moveBy( 0, rect.height() ); - } - - rect = r; - rect.moveBy( 0, -rect.height() ); - cur = tmp->itemAbove(); - - while ( cur && rect.bottom() >= oldTop ) - { - if ( rect.intersects( nr ) ) - { - if ( !cur->isSelected() && cur->isSelectable() ) - { - setSelected( cur, true ); - setActiveMultiSelectItem( at ); - changed = TRUE; - rr = rr.unite( itemRect( cur ) ); - } - } - else - { - if ( cur->isSelected() ) - { - changed = TRUE; - rr = rr.unite( itemRect( cur ) ); - } - - if ( !m_selected || !m_selected->contains( (KonqBaseListViewItem*)cur ) ) - { - setSelected( cur, false ); - setActiveMultiSelectItem( at ); - } - } - - - cur = cur->itemAbove(); - if (cur && !allColumnsShowFocus()) - rect.setWidth( executeArea( cur ) ); - rect.moveBy( 0, -rect.height() ); - } - } - - blockSignals( block ); - emit selectionChanged(); - - TQRect allRect = oldRubber.normalize(); - if ( changed ) - { - allRect |= rr.normalize(); - } - allRect |= m_rubber->normalize(); - TQPoint point = contentsToViewport( allRect.topLeft() ); - allRect = TQRect( point.x(), point.y(), allRect.width(), allRect.height() ); - allRect &= viewport()->rect(); - allRect.addCoords( -2, -2, 2, 2 ); - - TQPixmap backrubber( viewport()->rect().size() ); - backrubber.fill( viewport(), viewport()->rect().topLeft() ); - - TQPainter p( &backrubber ); - p.save(); - drawContentsOffset( &p, - contentsX(), - contentsY(), - contentsX() + allRect.left(), contentsY() + allRect.top(), - allRect.width(), allRect.height() ); - p.restore(); - drawRubber( &p ); - p.end(); - bitBlt( viewport(), allRect.topLeft(), &backrubber, allRect ); - - const int scroll_margin = 40; - ensureVisible( vc.x(), vc.y(), scroll_margin, scroll_margin ); - - if ( !TQRect( scroll_margin, scroll_margin, - viewport()->width() - 2*scroll_margin, - viewport()->height() - 2*scroll_margin ).contains( pos ) ) - { - if ( !m_scrollTimer ) - { - m_scrollTimer = new TQTimer( this ); - - connect( m_scrollTimer, TQT_SIGNAL( timeout() ), - this, TQT_SLOT( slotAutoScroll() ) ); - m_scrollTimer->start( 100, false ); - } - } - else if ( m_scrollTimer ) - { - disconnect( m_scrollTimer, TQT_SIGNAL( timeout() ), - this, TQT_SLOT( slotAutoScroll() ) ); - m_scrollTimer->stop(); - delete m_scrollTimer; - m_scrollTimer = 0; - } -} - -void KonqBaseListViewWidget::viewportPaintEvent( TQPaintEvent *e ) -{ - - TDEListView::viewportPaintEvent( e ); - - TQPainter p( viewport() ); - drawRubber( &p ); - p.end(); -} - -void KonqBaseListViewWidget::viewportResizeEvent(TQResizeEvent * e) -{ - TDEListView::viewportResizeEvent(e); - emit viewportAdjusted(); -} - -void KonqBaseListViewWidget::viewportDragMoveEvent( TQDragMoveEvent *_ev ) -{ - KonqBaseListViewItem *item = - isExecuteArea( _ev->pos() ) ? (KonqBaseListViewItem*)itemAt( _ev->pos() ) : 0L; - - // Unselect previous drag-over-item - if ( m_dragOverItem && m_dragOverItem != item ) - if ( !m_selected || !m_selected->contains( m_dragOverItem ) ) - setSelected( m_dragOverItem, false ); - - if ( !item ) - { - _ev->acceptAction(); - m_dragOverItem = 0L; - return; - } - - if ( item->item()->acceptsDrops() ) - { - _ev->acceptAction(); - if ( m_dragOverItem != item ) - { - setSelected( item, true ); - m_dragOverItem = item; - } - } - else - { - _ev->ignore(); - m_dragOverItem = 0L; - } -} - -void KonqBaseListViewWidget::viewportDragEnterEvent( TQDragEnterEvent *_ev ) -{ - m_dragOverItem = 0L; - - // By default we accept any format - _ev->acceptAction(); -} - -void KonqBaseListViewWidget::viewportDragLeaveEvent( TQDragLeaveEvent * ) -{ - if ( m_dragOverItem != 0L ) - setSelected( m_dragOverItem, false ); - m_dragOverItem = 0L; -} - -void KonqBaseListViewWidget::viewportDropEvent( TQDropEvent *ev ) -{ - if ( m_dirLister->url().isEmpty() ) - return; - kdDebug() << "KonqBaseListViewWidget::viewportDropEvent" << endl; - if ( m_dragOverItem != 0L ) - setSelected( m_dragOverItem, false ); - m_dragOverItem = 0L; - - ev->accept(); - - // We dropped on an item only if we dropped on the Name column. - KonqBaseListViewItem *item = - isExecuteArea( ev->pos() ) ? (KonqBaseListViewItem*)itemAt( ev->pos() ) : 0; - - KFileItem * destItem = (item) ? item->item() : m_dirLister->rootItem(); - KURL u = destItem ? destItem->url() : url(); - if ( u.isEmpty() ) - return; - KonqOperations::doDrop( destItem /*may be 0L*/, u, ev, this ); -} - -void KonqBaseListViewWidget::startDrag() -{ - m_fileTip->setItem( 0 ); - KURL::List urls = selectedUrls( false ); - - TQListViewItem * m_pressedItem = currentItem(); - - TQPixmap pixmap2; - bool pixmap0Invalid = !m_pressedItem->pixmap(0) || m_pressedItem->pixmap(0)->isNull(); - - // Multiple URLs ? - if (( urls.count() > 1 ) || (pixmap0Invalid)) - { - int iconSize = m_pBrowserView->m_pProps->iconSize(); - iconSize = iconSize ? iconSize : TDEGlobal::iconLoader()->currentSize( TDEIcon::Small ); // Default = small - pixmap2 = DesktopIcon( "application-vnd.tde.tdemultiple", iconSize ); - if ( pixmap2.isNull() ) - kdWarning(1202) << "Could not find multiple pixmap" << endl; - } - - //KURLDrag *d = new KURLDrag( urls, viewport() ); - KonqDrag *drag= new KonqDrag( urls, selectedUrls(true), false, viewport() ); - if ( !pixmap2.isNull() ) - drag->setPixmap( pixmap2 ); - else if ( !pixmap0Invalid ) - drag->setPixmap( *m_pressedItem->pixmap( 0 ) ); - - drag->drag(); -} - -void KonqBaseListViewWidget::slotItemRenamed( TQListViewItem *item, const TQString &name, int col ) -{ - Q_ASSERT( col == 0 ); - Q_ASSERT( item != 0 ); - - // The correct behavior is to show the old name until the rename has successfully - // completed. Unfortunately, TDEListView forces us to allow the text to be changed - // before we try the rename, so set it back to the pre-rename state. - KonqBaseListViewItem *renamedItem = static_cast(item); - renamedItem->updateContents(); - - // Don't do anything if the user renamed to a blank name. - if( !name.isEmpty() ) - { - // Actually attempt the rename. If it succeeds, KDirLister will update the name. - KonqOperations::rename( this, renamedItem->item()->url(), TDEIO::encodeFileName( name ) ); - } - - // When the TDEListViewLineEdit loses focus, focus tends to go to the location bar... - setFocus(); -} - -void KonqBaseListViewWidget::slotRenameNextItem(TQListViewItem *item, int) -{ - TQListViewItem *nextItem = item->itemBelow(); - if (!nextItem) - { - nextItem=this->firstChild(); - if (!nextItem) - return; - } - - deactivateAutomaticSelection(); - setCurrentItem(nextItem); - ListViewBrowserExtension *lvbe = dynamic_cast(m_pBrowserView->m_extension); - if (lvbe) - lvbe->rename(); -} - -void KonqBaseListViewWidget::slotRenamePrevItem(TQListViewItem *item, int) -{ - TQListViewItem *prevItem = item->itemAbove(); - if (!prevItem) - { - prevItem=this->lastItem(); - if (!prevItem) - return; - } - - deactivateAutomaticSelection(); - setCurrentItem(prevItem); - ListViewBrowserExtension *lvbe = dynamic_cast(m_pBrowserView->m_extension); - if (lvbe) - lvbe->rename(); -} - -void KonqBaseListViewWidget::reportItemCounts() -{ - KFileItemList lst = selectedFileItems(); - if ( !lst.isEmpty() ) - m_pBrowserView->emitCounts( lst ); - else - { - lst = visibleFileItems(); - m_pBrowserView->emitCounts( lst ); - } -} - -void KonqBaseListViewWidget::slotSelectionChanged() -{ - reportItemCounts(); - - KFileItemList lst = selectedFileItems(); - emit m_pBrowserView->m_extension->selectionInfo( lst ); -} - -void KonqBaseListViewWidget::slotMouseButtonClicked2( int _button, - TQListViewItem *_item, const TQPoint& pos, int ) -{ - if ( _button == Qt::MidButton ) - { - if ( _item && isExecuteArea( viewport()->mapFromGlobal(pos) ) ) - m_pBrowserView->mmbClicked( static_cast(_item)->item() ); - else // MMB on background - m_pBrowserView->mmbClicked( 0 ); - } -} - -void KonqBaseListViewWidget::slotExecuted( TQListViewItem *item ) -{ - if ( !item ) - return; - m_fileTip->setItem( 0 ); - // isExecuteArea() checks whether the mouse pointer is - // over an area where an action should be triggered - // (i.e. the Name column, including pixmap and "+") - if ( isExecuteArea( viewport()->mapFromGlobal( TQCursor::pos() ) ) ) - slotReturnPressed( item ); -} - -void KonqBaseListViewWidget::selectedItems( TQPtrList *_list ) -{ - iterator it = begin(); - for ( ; it != end(); it++ ) - if ( it->isVisible() && it->isSelected() ) - _list->append( &*it ); -} - -KFileItemList KonqBaseListViewWidget::visibleFileItems() -{ - KFileItemList list; - KonqBaseListViewItem *item = static_cast(firstChild()); - while ( item ) - { - list.append( item->item() ); - item = static_cast(item->itemBelow()); - } - return list; -} - -KFileItemList KonqBaseListViewWidget::selectedFileItems() -{ - KFileItemList list; - iterator it = begin(); - for ( ; it != end(); it++ ) - if ( it->isVisible() && it->isSelected() ) - list.append( it->item() ); - return list; -} - -KURL::List KonqBaseListViewWidget::selectedUrls( bool mostLocal ) -{ - bool dummy; - KURL::List list; - iterator it = begin(); - for ( ; it != end(); it++ ) - if ( it->isVisible() && it->isSelected() ) - list.append( mostLocal ? it->item()->mostLocalURL( dummy ) : it->item()->url() ); - return list; -} - -KonqPropsView * KonqBaseListViewWidget::props() const -{ - return m_pBrowserView->m_pProps; -} - -void KonqBaseListViewWidget::slotReturnPressed( TQListViewItem *_item ) -{ - if ( !_item ) - return; - KFileItem *fileItem = static_cast(_item)->item(); - if ( !fileItem ) - return; - - KURL url = fileItem->url(); - url.cleanPath(); - bool isIntoTrash = url.isLocalFile() && url.path(1).startsWith(TDEGlobalSettings::trashPath()); - if ( !isIntoTrash || (isIntoTrash && fileItem->isDir()) ) - { - m_pBrowserView->lmbClicked( fileItem ); - - if (_item->pixmap(0) != 0) - { - // Rect of the TQListViewItem's pixmap area. - TQRect rect = _item->listView()->itemRect(_item); - - // calculate nesting depth - int nestingDepth = 0; - for (TQListViewItem *currentItem = _item->parent(); - currentItem != 0; - currentItem = currentItem->parent()) - nestingDepth++; - - // no parent no indent - if (_item->parent() == 0) - nestingDepth = 0; - - // Root decoration means additional indent - if (_item->listView()->rootIsDecorated()) - nestingDepth++; - - // set recalculated rect - rect.setLeft(_item->listView()->itemMargin() + _item->listView()->treeStepSize() * nestingDepth); - rect.setWidth(_item->pixmap(0)->width()); - - // gather pixmap - TQPixmap *pix = new TQPixmap(*(_item->pixmap(0))); - - // call the icon effect if enabled - if (TDEGlobalSettings::showKonqIconActivationEffect() == true) { - TDEIconEffect::visualActivate(viewport(), rect, pix); - } - - // clean up - delete(pix); - } - } - else - KMessageBox::information( 0, i18n("You must take the file out of the trash before being able to use it.") ); -} - -void KonqBaseListViewWidget::slotPopupMenu( TQListViewItem *i, const TQPoint &point, int c ) -{ - kdDebug(1202) << "KonqBaseListViewWidget::slotPopupMenu" << endl; - popupMenu( point, ( i != 0 && c == -1 ) ); // i != 0 && c == -1 when activated by keyboard -} - -void KonqBaseListViewWidget::popupMenu( const TQPoint& _global, bool alwaysForSelectedFiles ) -{ - m_fileTip->setItem( 0 ); - - KFileItemList lstItems; - KParts::BrowserExtension::PopupFlags popupFlags = KParts::BrowserExtension::DefaultPopupItems; - - // Only consider a right-click on the name column as something - // related to the selection. On all the other columns, we want - // a popup for the current dir instead. - if ( alwaysForSelectedFiles || isExecuteArea( viewport()->mapFromGlobal( _global ) ) ) - { - TQPtrList items; - selectedItems( &items ); - for ( KonqBaseListViewItem *item = items.first(); item; item = items.next() ) - lstItems.append( item->item() ); - } - - KFileItem *rootItem = 0L; - bool deleteRootItem = false; - if ( lstItems.count() == 0 ) // emit popup for background - { - clearSelection(); - - if ( m_dirLister->url().isEmpty() ) - return; - rootItem = m_dirLister->rootItem(); - if ( !rootItem ) - { - if ( url().isEmpty() ) - return; - // Maybe we want to do a stat to get full info about the root item - // (when we use permissions). For now create a dummy one. - rootItem = new KFileItem( S_IFDIR, (mode_t)-1, url() ); - deleteRootItem = true; - } - - lstItems.append( rootItem ); - popupFlags = KParts::BrowserExtension::ShowNavigationItems | KParts::BrowserExtension::ShowUp; - } - emit m_pBrowserView->extension()->popupMenu( 0, _global, lstItems, KParts::URLArgs(), popupFlags ); - - if ( deleteRootItem ) - delete rootItem; // we just created it -} - -void KonqBaseListViewWidget::updateListContents() -{ - for ( KonqBaseListViewWidget::iterator it = begin(); it != end(); it++ ) - it->updateContents(); -} - -bool KonqBaseListViewWidget::openURL( const KURL &url ) -{ - kdDebug(1202) << k_funcinfo << "protocol: " << url.protocol() - << " url: " << url.path() << endl; - - // The first time or new protocol? So create the columns first. - if ( columns() < 1 || url.protocol() != m_url.protocol() ) - { - readProtocolConfig( url ); - createColumns(); - } - - m_bTopLevelComplete = false; - m_itemFound = false; - - if ( m_itemToGoTo.isEmpty() && url.equals( m_url.upURL(), true ) ) - m_itemToGoTo = m_url.fileName( true ); - - // Check for new properties in the new dir - // newProps returns true the first time, and any time something might - // have changed. - bool newProps = m_pBrowserView->m_pProps->enterDir( url ); - - m_dirLister->setNameFilter( m_pBrowserView->nameFilter() ); - m_dirLister->setMimeFilter( m_pBrowserView->mimeFilter() ); - m_dirLister->setShowingDotFiles( m_pBrowserView->m_pProps->isShowingDotFiles() ); - - KParts::URLArgs args = m_pBrowserView->extension()->urlArgs(); - if ( args.reload ) - { - args.xOffset = contentsX(); - args.yOffset = contentsY(); - m_pBrowserView->extension()->setURLArgs( args ); - - if ( currentItem() && itemRect( currentItem() ).isValid() ) - m_itemToGoTo = currentItem()->text(0); - - m_pBrowserView->m_filesToSelect.clear(); - iterator it = begin(); - for( ; it != end(); it++ ) - if ( it->isSelected() ) - m_pBrowserView->m_filesToSelect += it->text(0); - } - - m_itemsToSelect = m_pBrowserView->m_filesToSelect; - if ( !m_itemsToSelect.isEmpty() && m_itemToGoTo.isEmpty() ) - m_itemToGoTo = m_itemsToSelect[0]; - - if ( columnWidthMode(0) == Maximum ) - setColumnWidth(0,50); - - m_url = url; - m_bUpdateContentsPosAfterListing = true; - - // Start the directory lister ! - m_dirLister->openURL( url, false /* new url */, args.reload ); - - // Apply properties and reflect them on the actions - // do it after starting the dir lister to avoid changing the properties - // of the old view - if ( newProps ) - { - m_pBrowserView->newIconSize( m_pBrowserView->m_pProps->iconSize() ); - m_pBrowserView->m_paShowDot->setChecked( m_pBrowserView->m_pProps->isShowingDotFiles() ); - if ( m_pBrowserView->m_paCaseInsensitive->isChecked() != m_pBrowserView->m_pProps->isCaseInsensitiveSort() ) { - m_pBrowserView->m_paCaseInsensitive->setChecked( m_pBrowserView->m_pProps->isCaseInsensitiveSort() ); - // This is in case openURL returned all items synchronously. - sort(); - } - - // It has to be "viewport()" - this is what KonqDirPart's slots act upon, - // and otherwise we get a color/pixmap in the square between the scrollbars. - m_pBrowserView->m_pProps->applyColors( viewport() ); - } - - return true; -} - -void KonqBaseListViewWidget::setComplete() -{ - kdDebug(1202) << k_funcinfo << "Update Contents Pos: " - << m_bUpdateContentsPosAfterListing << endl; - - m_bTopLevelComplete = true; - - // Alex: this flag is set when we are just finishing a voluntary listing, - // so do the go-to-item thing only under here. When we update the - // current directory automatically (e.g. after a file has been deleted), - // we don't want to go to the first item ! (David) - if ( m_bUpdateContentsPosAfterListing ) - { - m_bUpdateContentsPosAfterListing = false; - - if ( !m_itemFound ) - setCurrentItem( firstChild() ); - - if ( !m_restored && !m_pBrowserView->extension()->urlArgs().reload ) - ensureItemVisible( currentItem() ); - else - setContentsPos( m_pBrowserView->extension()->urlArgs().xOffset, - m_pBrowserView->extension()->urlArgs().yOffset ); - - emit selectionChanged(); - } - - m_itemToGoTo = ""; - m_restored = false; - - // Show totals - reportItemCounts(); - - m_pBrowserView->emitMouseOver( 0 ); - - if ( !isUpdatesEnabled() || !viewport()->isUpdatesEnabled() ) - { - viewport()->setUpdatesEnabled( true ); - setUpdatesEnabled( true ); - triggerUpdate(); - } - - // Show "cut" icons as such - m_pBrowserView->slotClipboardDataChanged(); -} - -void KonqBaseListViewWidget::slotStarted() -{ - //kdDebug(1202) << k_funcinfo << endl; - - if (!m_bTopLevelComplete) - emit m_pBrowserView->started( 0 ); -} - -void KonqBaseListViewWidget::slotCompleted() -{ - //kdDebug(1202) << k_funcinfo << endl; - - setComplete(); - if ( m_bTopLevelComplete ) - emit m_pBrowserView->completed(); - m_pBrowserView->listingComplete(); -} - -void KonqBaseListViewWidget::slotCanceled() -{ - //kdDebug(1202) << k_funcinfo << endl; - - setComplete(); - emit m_pBrowserView->canceled( TQString::null ); -} - -void KonqBaseListViewWidget::slotClear() -{ - //kdDebug(1202) << k_funcinfo << endl; - - m_activeItem = 0; - m_fileTip->setItem( 0 ); - delete m_selected; m_selected = 0; - m_pBrowserView->resetCount(); - m_pBrowserView->lstPendingMimeIconItems().clear(); - - viewport()->setUpdatesEnabled( false ); - setUpdatesEnabled( false ); - clear(); -} - -void KonqBaseListViewWidget::slotNewItems( const KFileItemList & entries ) -{ - //kdDebug(1202) << k_funcinfo << entries.count() << endl; - - for ( TQPtrListIterator kit ( entries ); kit.current(); ++kit ) - { - KonqListViewItem * tmp = new KonqListViewItem( this, *kit ); - if ( !m_itemFound && tmp->text(0) == m_itemToGoTo ) - { - setCurrentItem( tmp ); - m_itemFound = true; - } - if ( !m_itemsToSelect.isEmpty() ) { - TQStringList::Iterator tsit = m_itemsToSelect.find( (*kit)->name() ); - if ( tsit != m_itemsToSelect.end() ) { - m_itemsToSelect.remove( tsit ); - setSelected( tmp, true ); - } - } - if ( !(*kit)->isMimeTypeKnown() ) - m_pBrowserView->lstPendingMimeIconItems().append( tmp ); - } - m_pBrowserView->newItems( entries ); - - if ( !viewport()->isUpdatesEnabled() ) - { - viewport()->setUpdatesEnabled( true ); - setUpdatesEnabled( true ); - triggerUpdate(); - } - slotUpdateBackground(); -} - -void KonqBaseListViewWidget::slotDeleteItem( KFileItem * _fileitem ) -{ - // new in 3.5.5 -#ifdef TDEPARTS_BROWSEREXTENSION_HAS_ITEMS_REMOVED - KFileItemList list; - list.append( _fileitem ); - emit m_pBrowserView->extension()->itemsRemoved( list ); -#else -#error "Your tdelibs doesn't have KParts::BrowserExtension::itemsRemoved, please update it to at least 3.5.5" -#endif - - iterator it = begin(); - for( ; it != end(); ++it ) - if ( (*it).item() == _fileitem ) - { - kdDebug(1202) << k_funcinfo << "removing " << _fileitem->url().url() << " from tree!" << endl; - - m_pBrowserView->deleteItem( _fileitem ); - m_pBrowserView->lstPendingMimeIconItems().remove( &(*it) ); - - if ( m_activeItem == &(*it) ) { - m_fileTip->setItem( 0 ); - m_activeItem = 0; - } - - delete &(*it); - // HACK HACK HACK: TQListViewItem/KonqBaseListViewItem should - // take care and the source looks like it does; till the - // real bug is found, this fixes some crashes (malte) - emit selectionChanged(); - return; - } - - // This is needed for the case the root of the current view is deleted. - // I supposed slotUpdateBackground has to be called as well after an item - // was removed from a listview and was just forgotten previously (Brade). - // OK, but this code also gets activated when deleting a hidden file... (dfaure) - if ( !viewport()->isUpdatesEnabled() ) - { - viewport()->setUpdatesEnabled( true ); - setUpdatesEnabled( true ); - triggerUpdate(); - } - slotUpdateBackground(); -} - -void KonqBaseListViewWidget::slotRefreshItems( const KFileItemList & entries ) -{ - //kdDebug(1202) << k_funcinfo << endl; - - TQPtrListIterator kit ( entries ); - for ( ; kit.current(); ++kit ) - { - iterator it = begin(); - for ( ; it != end(); ++it ) - if ( (*it).item() == kit.current() ) - { - it->updateContents(); - break; - } - } - - m_pBrowserView->refreshItems(entries); // Pass refresh command to KonqDirPart too - reportItemCounts(); -} - -void KonqBaseListViewWidget::slotRedirection( const KURL & url ) -{ - kdDebug(1202) << k_funcinfo << url << endl; - - if ( (columns() < 1) || (url.protocol() != m_url.protocol()) ) - { - readProtocolConfig( url ); - createColumns(); - } - const TQString prettyURL = url.pathOrURL(); - emit m_pBrowserView->extension()->setLocationBarURL( prettyURL ); - emit m_pBrowserView->setWindowCaption( prettyURL ); - m_pBrowserView->m_url = url; - m_url = url; -} - -KonqBaseListViewWidget::iterator& KonqBaseListViewWidget::iterator::operator++() -{ - if ( !m_p ) return *this; - KonqBaseListViewItem *i = (KonqBaseListViewItem *)m_p->firstChild(); - if ( i ) - { - m_p = i; - return *this; - } - i = (KonqBaseListViewItem *)m_p->nextSibling(); - if ( i ) - { - m_p = i; - return *this; - } - m_p = (KonqBaseListViewItem *)m_p->parent(); - - while ( m_p ) - { - if ( m_p->nextSibling() ) - break; - m_p = (KonqBaseListViewItem *)m_p->parent(); - } - - if ( m_p ) - m_p = (KonqBaseListViewItem *)m_p->nextSibling(); - - return *this; -} - -KonqBaseListViewWidget::iterator KonqBaseListViewWidget::iterator::operator++(int) -{ - KonqBaseListViewWidget::iterator it = *this; - if ( !m_p ) return it; - KonqBaseListViewItem *i = (KonqBaseListViewItem *)m_p->firstChild(); - if ( i ) - { - m_p = i; - return it; - } - i = (KonqBaseListViewItem *)m_p->nextSibling(); - if ( i ) - { - m_p = i; - return it; - } - m_p = (KonqBaseListViewItem *)m_p->parent(); - - while ( m_p ) - { - if ( m_p->nextSibling() ) - break; - m_p = (KonqBaseListViewItem *)m_p->parent(); - } - - if ( m_p ) - m_p = (KonqBaseListViewItem *)m_p->nextSibling(); - return it; -} - -void KonqBaseListViewWidget::paintEmptyArea( TQPainter *p, const TQRect &r ) -{ - const TQPixmap *pm = TQT_TQPIXMAP_CONST(viewport()->paletteBackgroundPixmap()); - - if (!pm || pm->isNull()) - p->fillRect(r, viewport()->backgroundColor()); - else - { - TQRect devRect = p->xForm( r ); - int ax = (devRect.x() + contentsX()); - int ay = (devRect.y() + contentsY()); - /* kdDebug() << "KonqBaseListViewWidget::paintEmptyArea " - << r.x() << "," << r.y() << " " << r.width() << "x" << r.height() - << " drawing pixmap with offset " << ax << "," << ay - << endl;*/ - p->drawTiledPixmap(r, *pm, TQPoint(ax, ay)); - } -} - -void KonqBaseListViewWidget::disableIcons( const KURL::List & lst ) -{ - iterator kit = begin(); - for( ; kit != end(); ++kit ) - { - bool bFound = false; - // Wow. This is ugly. Matching two lists together.... - // Some sorting to optimise this would be a good idea ? - for (KURL::List::ConstIterator it = lst.begin(); !bFound && it != lst.end(); ++it) - { - if ( (*kit).item()->url() == *it ) // *it is encoded already - { - bFound = true; - // maybe remove "it" from lst here ? - } - } - (*kit).setDisabled( bFound ); - } -} - -void KonqBaseListViewWidget::saveState( TQDataStream & ds ) -{ - TQString str; - if ( currentItem() ) - str = static_cast(currentItem())->item()->url().fileName(true); - ds << str << m_url; -} - -void KonqBaseListViewWidget::restoreState( TQDataStream & ds ) -{ - m_restored = true; - - TQString str; - KURL url; - ds >> str >> url; - if ( !str.isEmpty() ) - m_itemToGoTo = str; - - if ( columns() < 1 || url.protocol() != m_url.protocol() ) - { - readProtocolConfig( url ); - createColumns(); - } - m_url = url; - - m_bTopLevelComplete = false; - m_itemFound = false; -} - -void KonqBaseListViewWidget::slotUpdateBackground() -{ - if ( viewport()->paletteBackgroundPixmap() && !viewport()->paletteBackgroundPixmap()->isNull() ) - { - if ( !m_backgroundTimer ) - { - m_backgroundTimer = new TQTimer( this ); - connect( m_backgroundTimer, TQT_SIGNAL( timeout() ), viewport(), TQT_SLOT( update() ) ); - } - else - m_backgroundTimer->stop(); - - m_backgroundTimer->start( 50, true ); - } -} - -bool KonqBaseListViewWidget::caseInsensitiveSort() const -{ - return m_pBrowserView->m_pProps->isCaseInsensitiveSort(); -} - -// based on isExecuteArea from tdelistview.cpp -int KonqBaseListViewWidget::executeArea( TQListViewItem *_item ) -{ - if ( !_item ) - return 0; - - int width = treeStepSize() * ( _item->depth() + ( rootIsDecorated() ? 1 : 0 ) ); - width += itemMargin(); - int ca = AlignHorizontal_Mask & columnAlignment( 0 ); - if ( ca == AlignLeft || ca == AlignAuto ) - { - width += _item->width( fontMetrics(), this, 0 ); - if ( width > columnWidth( 0 ) ) - width = columnWidth( 0 ); - } - return width; -} - -#include "konq_listviewwidget.moc" diff --git a/konqueror/listview/konq_listviewwidget.cpp b/konqueror/listview/konq_listviewwidget.cpp new file mode 100644 index 000000000..4c1198325 --- /dev/null +++ b/konqueror/listview/konq_listviewwidget.cpp @@ -0,0 +1,1592 @@ +/* This file is part of the KDE project + Copyright (C) 1998, 1999 Torben Weis + 2001, 2002, 2004 Michael Brade + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "konq_listview.h" +#include "konq_listviewsettings.h" +#include "konq_listviewwidget.h" +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +ColumnInfo::ColumnInfo() + :displayInColumn(-1) + ,name() + ,desktopFileName() + ,udsId(0) + ,type(TQVariant::Invalid) + ,displayThisOne(false) + ,toggleThisOne(0) +{} + + +void ColumnInfo::setData(const TQString& n, const TQString& desktopName, int kioUds, + TDEToggleAction* someAction, int theWidth) +{ + displayInColumn=-1; + name=n; + desktopFileName=desktopName; + udsId=kioUds; + type=TQVariant::Invalid; + displayThisOne=false; + toggleThisOne=someAction; + width=theWidth; +} + +void ColumnInfo::setData(const TQString& n, const TQString& desktopName, int kioUds, + TQVariant::Type t, TDEToggleAction* someAction, int theWidth) +{ + displayInColumn=-1; + name=n; + desktopFileName=desktopName; + udsId=kioUds; + type=t; + displayThisOne=false; + toggleThisOne=someAction; + width=theWidth; +} + + +KonqBaseListViewWidget::KonqBaseListViewWidget( KonqListView *parent, TQWidget *parentWidget) + : TDEListView(parentWidget) + ,sortedByColumn(0) + ,m_pBrowserView(parent) + ,m_dirLister(new KDirLister( true /*m_showIcons==false*/)) + ,m_dragOverItem(0) + ,m_activeItem(0) + ,m_selected(0) + ,m_scrollTimer(0) + ,m_rubber(0) + ,m_showIcons(true) + ,m_bCaseInsensitive(true) + ,m_bUpdateContentsPosAfterListing(false) + ,m_bAscending(true) + ,m_itemFound(false) + ,m_restored(false) + ,m_filenameColumn(0) + ,m_itemToGoTo("") + ,m_backgroundTimer(0) + ,m_fileTip(new KonqFileTip(this)) +{ + kdDebug(1202) << "+KonqBaseListViewWidget" << endl; + + m_dirLister->setMainWindow(topLevelWidget()); + + m_bTopLevelComplete = true; + + //Adjust TDEListView behaviour + setMultiSelection(true); + setSelectionModeExt( FileManager ); + setDragEnabled(true); + setItemsMovable(false); + setUseSmallExecuteArea(true); + + initConfig(); +#if 0 + connect( this, TQT_SIGNAL(rightButtonPressed(TQListViewItem*,const TQPoint&,int)), + this, TQT_SLOT(slotRightButtonPressed(TQListViewItem*,const TQPoint&,int))); +#endif + connect( this, TQT_SIGNAL(returnPressed( TQListViewItem * )), + this, TQT_SLOT(slotReturnPressed( TQListViewItem * )) ); + connect( this, TQT_SIGNAL(mouseButtonClicked( int, TQListViewItem *, const TQPoint&, int )), + this, TQT_SLOT(slotMouseButtonClicked2( int, TQListViewItem *, const TQPoint&, int )) ); + connect( this, TQT_SIGNAL(executed( TQListViewItem * )), + this, TQT_SLOT(slotExecuted( TQListViewItem * )) ); + connect( this, TQT_SIGNAL(currentChanged( TQListViewItem * )), + this, TQT_SLOT(slotCurrentChanged( TQListViewItem * )) ); + connect( this, TQT_SIGNAL(itemRenamed( TQListViewItem *, const TQString &, int )), + this, TQT_SLOT(slotItemRenamed( TQListViewItem *, const TQString &, int )) ); + connect( this, TQT_SIGNAL(contextMenuRequested( TQListViewItem *, const TQPoint&, int )), + this, TQT_SLOT(slotPopupMenu( TQListViewItem *, const TQPoint&, int )) ); + connect( this, TQT_SIGNAL(renameNext( TQListViewItem *, int )), + this, TQT_SLOT(slotRenameNextItem( TQListViewItem*, int)) ); + connect( this, TQT_SIGNAL(renamePrev( TQListViewItem *, int )), + this, TQT_SLOT(slotRenamePrevItem( TQListViewItem*, int)) ); + connect( this, TQT_SIGNAL(selectionChanged()), this, TQT_SLOT(slotSelectionChanged()) ); + + connect( horizontalScrollBar(), TQT_SIGNAL(valueChanged( int )), + this, TQT_SIGNAL(viewportAdjusted()) ); + connect( verticalScrollBar(), TQT_SIGNAL(valueChanged( int )), + this, TQT_SIGNAL(viewportAdjusted()) ); + + // Connect the directory lister + connect( m_dirLister, TQT_SIGNAL(started( const KURL & )), + this, TQT_SLOT(slotStarted()) ); + connect( m_dirLister, TQT_SIGNAL(completed()), this, TQT_SLOT(slotCompleted()) ); + connect( m_dirLister, TQT_SIGNAL(canceled()), this, TQT_SLOT(slotCanceled()) ); + connect( m_dirLister, TQT_SIGNAL(clear()), this, TQT_SLOT(slotClear()) ); + connect( m_dirLister, TQT_SIGNAL(newItems( const KFileItemList & ) ), + this, TQT_SLOT(slotNewItems( const KFileItemList & )) ); + connect( m_dirLister, TQT_SIGNAL(deleteItem( KFileItem * )), + this, TQT_SLOT(slotDeleteItem( KFileItem * )) ); + connect( m_dirLister, TQT_SIGNAL(refreshItems( const KFileItemList & )), + this, TQT_SLOT( slotRefreshItems( const KFileItemList & )) ); + connect( m_dirLister, TQT_SIGNAL(redirection( const KURL & )), + this, TQT_SLOT(slotRedirection( const KURL & )) ); + connect( m_dirLister, TQT_SIGNAL(itemsFilteredByMime( const KFileItemList & )), + m_pBrowserView, TQT_SIGNAL(itemsFilteredByMime( const KFileItemList & )) ); + + connect( m_dirLister, TQT_SIGNAL(infoMessage( const TQString& )), + m_pBrowserView->extension(), TQT_SIGNAL(infoMessage( const TQString& )) ); + connect( m_dirLister, TQT_SIGNAL(percent( int )), + m_pBrowserView->extension(), TQT_SIGNAL(loadingProgress( int )) ); + connect( m_dirLister, TQT_SIGNAL(speed( int )), + m_pBrowserView->extension(), TQT_SIGNAL(speedProgress( int )) ); + + connect( header(), TQT_SIGNAL(sizeChange( int, int, int )), TQT_SLOT(slotUpdateBackground()) ); + + viewport()->setMouseTracking( true ); + viewport()->setFocusPolicy( TQ_WheelFocus ); + setFocusPolicy( TQ_WheelFocus ); + setAcceptDrops( true ); + + //looks better with the statusbar + setFrameStyle( TQFrame::StyledPanel | TQFrame::Sunken ); + setShowSortIndicator( true ); +} + +KonqBaseListViewWidget::~KonqBaseListViewWidget() +{ + kdDebug(1202) << "-KonqBaseListViewWidget" << endl; + + delete m_selected; m_selected = 0; + + // TODO: this is a hack, better fix the connections of m_dirLister if possible! + m_dirLister->disconnect( this ); + delete m_dirLister; + + delete m_fileTip; +} + +void KonqBaseListViewWidget::readProtocolConfig( const KURL & url ) +{ + const TQString protocol = url.protocol(); + KonqListViewSettings config( protocol ); + config.readConfig(); + sortedByColumn = config.sortBy(); + m_bAscending = config.sortOrder(); + + m_filenameColumnWidth = config.fileNameColumnWidth(); + + TQStringList lstColumns = config.columns(); + TQValueList lstColumnWidths = config.columnWidths(); + if (lstColumns.isEmpty()) + { + // Default column selection + lstColumns.append( "Size" ); + lstColumns.append( "File Type" ); + lstColumns.append( "Modified" ); + lstColumns.append( "Permissions" ); + lstColumns.append( "Owner" ); + lstColumns.append( "Group" ); + lstColumns.append( "Link" ); + } + + // Default number of columns + NumberOfAtoms = 11; + int extraIndex = NumberOfAtoms; + + // Check for any extra data + KProtocolInfo::ExtraFieldList extraFields = KProtocolInfo::extraFields(url); + NumberOfAtoms += extraFields.count(); + confColumns.resize( NumberOfAtoms ); + + KProtocolInfo::ExtraFieldList::Iterator extraFieldsIt = extraFields.begin(); + for ( int num = 1; extraFieldsIt != extraFields.end(); ++extraFieldsIt, ++num ) + { + const TQString column = (*extraFieldsIt).name; + if ( lstColumns.find(column) == lstColumns.end() ) + lstColumns << column; + const TQString type = (*extraFieldsIt).type; // ## TODO use when sorting + TQVariant::Type t = TQVariant::Invalid; + if ( type.lower() == TQString(TQSTRING_OBJECT_NAME_STRING).lower() ) + t = TQVariant::String; + else if ( type.lower() == TQString(TQDATETIME_OBJECT_NAME_STRING).lower() ) + t = TQVariant::DateTime; + else + kdWarning() << "Unsupported ExtraType '" << type << "'" << endl; + confColumns[extraIndex++].setData( column, TQString("Extra%1").arg(num), TDEIO::UDS_EXTRA, t, 0); + } + + //disable everything + for ( unsigned int i = 0; i < NumberOfAtoms; i++ ) + { + confColumns[i].displayThisOne = false; + confColumns[i].displayInColumn = -1; + if ( confColumns[i].toggleThisOne ) + { + confColumns[i].toggleThisOne->setChecked( false ); + confColumns[i].toggleThisOne->setEnabled( true ); + } + } + int currentColumn = m_filenameColumn + 1; + //check all columns in lstColumns + for ( unsigned int i = 0; i < lstColumns.count(); i++ ) + { + //search the column in confColumns + for ( unsigned int j = 0; j < NumberOfAtoms; j++ ) + { + if ( confColumns[j].name == *lstColumns.at(i) ) + { + confColumns[j].displayThisOne = true; + confColumns[j].displayInColumn = currentColumn; + if ( confColumns[j].toggleThisOne ) + confColumns[j].toggleThisOne->setChecked( true ); + currentColumn++; + + if ( i < lstColumnWidths.count() ) + confColumns[j].width = *lstColumnWidths.at(i); + else + { + // Default Column widths + ColumnInfo *tmpColumn = &confColumns[j]; + TQString str; + + if ( tmpColumn->udsId == TDEIO::UDS_SIZE ) + str = TDEGlobal::locale()->formatNumber( 888888888, 0 ) + " "; + else if ( tmpColumn->udsId == TDEIO::UDS_ACCESS ) + str = "--Permissions--"; + else if ( tmpColumn->udsId == TDEIO::UDS_USER ) + str = "a_long_username"; + else if ( tmpColumn->udsId == TDEIO::UDS_GROUP ) + str = "a_groupname"; + else if ( tmpColumn->udsId == TDEIO::UDS_LINK_DEST ) + str = "a_quite_long_filename_for_link_dest"; + else if ( tmpColumn->udsId == TDEIO::UDS_FILE_TYPE ) + str = "a_long_comment_for_mimetype"; + else if ( tmpColumn->udsId == TDEIO::UDS_MIME_TYPE ) + str = "_a_long_/_mimetype_"; + else if ( tmpColumn->udsId == TDEIO::UDS_URL ) + str = "a_long_lonq_long_very_long_url"; + else if ( (tmpColumn->udsId & TDEIO::UDS_TIME) + || (tmpColumn->udsId == TDEIO::UDS_EXTRA && + (tmpColumn->type & TQVariant::DateTime)) ) + { + TQDateTime dt( TQDate( 2000, 10, 10 ), TQTime( 20, 20, 20 ) ); + str = TDEGlobal::locale()->formatDateTime( dt ) + "--"; + } + else + str = "it_is_the_default_width"; + + confColumns[j].width = fontMetrics().width(str); + } + break; + } + } + } + //check what the protocol provides + TQStringList listingList = KProtocolInfo::listing( url ); + kdDebug(1202) << k_funcinfo << "protocol: " << protocol << endl; + + // Even if this is not given by the protocol, we can determine it. + // Please don't remove this ;-). It makes it possible to show the file type + // using the mimetype comment, which for most users is a nicer alternative + // than the raw mimetype name. + listingList.append( "MimeType" ); + for ( unsigned int i = 0; i < NumberOfAtoms; i++ ) + { + if ( confColumns[i].udsId == TDEIO::UDS_URL || + confColumns[i].udsId == TDEIO::UDS_MIME_TYPE || + !confColumns[i].displayThisOne ) + { + continue; + } + + TQStringList::Iterator listIt = listingList.find( confColumns[i].desktopFileName ); + if ( listIt == listingList.end() ) // not found -> hide + { + //move all columns behind one to the front + for ( unsigned int l = 0; l < NumberOfAtoms; l++ ) + if ( confColumns[l].displayInColumn > confColumns[i].displayInColumn ) + confColumns[l].displayInColumn--; + + //disable this column + confColumns[i].displayThisOne = false; + if ( confColumns[i].toggleThisOne ) + { + confColumns[i].toggleThisOne->setEnabled( false ); + confColumns[i].toggleThisOne->setChecked( false ); + } + } + } +} + +void KonqBaseListViewWidget::createColumns() +{ + //this column is always required, so add it + if ( columns() < 1 ) + addColumn( i18n("Name"), m_filenameColumnWidth ); + setSorting( 0, true ); + + //remove all columns that will be re-added + for ( int i=columns()-1; i>m_filenameColumn; i--) + removeColumn(i); + + //now add the checked columns + int currentColumn = m_filenameColumn + 1; + for ( int i = 0; i < (int)NumberOfAtoms; i++ ) + { + if ( confColumns[i].displayThisOne && (confColumns[i].displayInColumn == currentColumn) ) + { + addColumn( i18n(confColumns[i].name.utf8()), confColumns[i].width ); + if ( sortedByColumn == confColumns[i].desktopFileName ) + setSorting( currentColumn, m_bAscending ); + if ( confColumns[i].udsId == TDEIO::UDS_SIZE ) + setColumnAlignment( currentColumn, AlignRight ); + i = -1; + currentColumn++; + } + } + if ( sortedByColumn == "FileName" ) + setSorting( 0, m_bAscending ); +} + +void KonqBaseListViewWidget::stop() +{ + m_dirLister->stop(); +} + +const KURL & KonqBaseListViewWidget::url() +{ + return m_url; +} + +void KonqBaseListViewWidget::initConfig() +{ + m_pSettings = KonqFMSettings::settings(); + + TQFont stdFont( m_pSettings->standardFont() ); + setFont( stdFont ); + //TODO: create config GUI + TQFont itemFont( m_pSettings->standardFont() ); + itemFont.setUnderline( m_pSettings->underlineLink() ); + setItemFont( itemFont ); + setItemColor( m_pSettings->normalTextColor() ); + + bool on = m_pSettings->showFileTips() && TQToolTip::isGloballyEnabled(); + m_fileTip->setOptions( on, m_pSettings->showPreviewsInFileTips(), m_pSettings->numFileTips() ); + + updateListContents(); +} + +void KonqBaseListViewWidget::contentsMousePressEvent( TQMouseEvent *e ) { + if ( m_rubber ) { + TQRect r( m_rubber->normalize() ); + delete m_rubber; + m_rubber = 0; + repaintContents( r, FALSE ); + } + + delete m_selected; + m_selected = new TQPtrList; + + TQPoint vp = contentsToViewport( e->pos() ); + KonqBaseListViewItem* item = isExecuteArea( vp ) ? + static_cast( itemAt( vp ) ) : 0L; + + if ( item ) { + TDEListView::contentsMousePressEvent( e ); + } + else { + if ( e->button() == Qt::LeftButton ) { + m_rubber = new TQRect( e->x(), e->y(), 0, 0 ); + clearSelection(); + emit selectionChanged(); + m_fileTip->setItem( 0 ); + } + if ( e->button() != Qt::RightButton ) { + TQListView::contentsMousePressEvent( e ); + } + } + + // Store list of selected items at mouse-press time. + // This is used when autoscrolling (why?) + // and during dnd (the target item is temporarily selected) + selectedItems( m_selected ); +} + +void KonqBaseListViewWidget::contentsMouseReleaseEvent( TQMouseEvent *e ) { + if ( m_rubber ) { + resetKeyboardSelectionOperation(); + TQRect r( m_rubber->normalize() ); + delete m_rubber; + m_rubber = 0; + repaintContents( r, FALSE ); + } + + if ( m_scrollTimer ) { + disconnect( m_scrollTimer, TQT_SIGNAL( timeout() ), this, TQT_SLOT( slotAutoScroll() ) ); + m_scrollTimer->stop(); + delete m_scrollTimer; + m_scrollTimer = 0; + } + + delete m_selected; m_selected = 0; + TDEListView::contentsMouseReleaseEvent( e ); +} + +void KonqBaseListViewWidget::contentsMouseMoveEvent( TQMouseEvent *e ) +{ + if ( m_rubber ) + { + slotAutoScroll(); + return; + } + + TQPoint vp = contentsToViewport( e->pos() ); + KonqBaseListViewItem* item = isExecuteArea( vp ) ? + static_cast( itemAt( vp ) ) : 0; + + if ( item != m_activeItem ) + { + if ( m_activeItem != 0 ) + m_activeItem->setActive( false ); + + m_activeItem = item; + + if ( item ) + { + item->setActive( true ); + emit m_pBrowserView->setStatusBarText( item->item()->getStatusBarInfo() ); + m_pBrowserView->emitMouseOver( item->item() ); + + vp.setY( itemRect( item ).y() ); + TQRect rect( viewportToContents( vp ), TQSize(20, item->height()) ); + m_fileTip->setItem( item->item(), rect, item->pixmap( 0 ) ); + m_fileTip->setPreview( TDEGlobalSettings::showFilePreview( item->item()->url() ) ); + setShowToolTips( !m_pSettings->showFileTips() ); + } + else + { + reportItemCounts(); + m_pBrowserView->emitMouseOver( 0 ); + + m_fileTip->setItem( 0 ); + setShowToolTips( true ); + } + } + + TDEListView::contentsMouseMoveEvent( e ); +} + +void KonqBaseListViewWidget::contentsWheelEvent( TQWheelEvent *e ) +{ + // when scrolling with mousewheel, stop possible pending filetip + m_fileTip->setItem( 0 ); + + if ( m_activeItem != 0 ) + { + m_activeItem->setActive( false ); + m_activeItem = 0; + } + + reportItemCounts(); + m_pBrowserView->emitMouseOver( 0 ); + TDEListView::contentsWheelEvent( e ); +} + +void KonqBaseListViewWidget::contentsMouseDoubleClickEvent(TQMouseEvent *e) +{ + if (m_rubber) { + TQRect r(m_rubber->normalize()); + delete m_rubber; + m_rubber = NULL; + repaintContents(r, false); + } + + TQPoint vp = contentsToViewport(e->pos()); + KonqBaseListViewItem* item = isExecuteArea(vp) ? + static_cast(itemAt(vp)) : NULL; + + if (item) { + TDEListView::contentsMouseDoubleClickEvent(e); + } + else { + KParts::URLArgs args; + args.trustedSource = true; + KURL upURL = m_dirLister->url().upURL(); + if (!upURL.isEmpty()) { + m_pBrowserView->extension()->openURLRequest(upURL, args); + } + } +} + +void KonqBaseListViewWidget::leaveEvent( TQEvent *e ) +{ + if ( m_activeItem != 0 ) + { + m_activeItem->setActive( false ); + m_activeItem = 0; + } + + reportItemCounts(); + m_pBrowserView->emitMouseOver( 0 ); + + m_fileTip->setItem( 0 ); + + TDEListView::leaveEvent( e ); +} + +void KonqBaseListViewWidget::drawRubber( TQPainter *p ) +{ + if ( !m_rubber ) + return; + + p->setRasterOp( NotROP ); + p->setPen( TQPen( color0, 1 ) ); + p->setBrush( NoBrush ); + + TQPoint pt( m_rubber->x(), m_rubber->y() ); + pt = contentsToViewport( pt ); + style().tqdrawPrimitive( TQStyle::PE_RubberBand, p, + TQRect( pt.x(), pt.y(), m_rubber->width(), m_rubber->height() ), + colorGroup(), TQStyle::Style_Default, colorGroup().base() ); +} + +void KonqBaseListViewWidget::slotAutoScroll() +{ + if ( !m_rubber ) + return; + + // this code assumes that all items have the same height + + const TQPoint pos = viewport()->mapFromGlobal( TQCursor::pos() ); + const TQPoint vc = viewportToContents( pos ); + TQListViewItem *at = itemAt( vc ); + + if ( vc == m_rubber->bottomRight() ) + return; + + TQRect oldRubber = *m_rubber; + + const int oldTop = m_rubber->normalize().top(); + const int oldBottom = m_rubber->normalize().bottom(); + + + m_rubber->setBottomRight( vc ); + + TQListViewItem *cur = itemAt( TQPoint(0,0) ); + + bool block = signalsBlocked(); + blockSignals( true ); + + TQRect rr; + TQRect nr = m_rubber->normalize(); + bool changed = FALSE; + + if ( cur ) + { + TQRect rect; + if ( allColumnsShowFocus() ) + rect = itemRect( cur ); + else { + rect = itemRect( cur ); + rect.setWidth( executeArea( cur ) ); + } + + + rect = TQRect( viewportToContents( rect.topLeft() ), + viewportToContents( rect.bottomRight() ) ); + + if ( !allColumnsShowFocus() ) + { + rect.setLeft( header()->sectionPos( 0 ) ); + rect.setWidth( rect.width() ); + } + else + { + rect.setLeft( 0 ); + rect.setWidth( header()->headerWidth() ); + } + + TQRect r = rect; + TQListViewItem *tmp = cur; + + while ( cur && rect.top() <= oldBottom ) + { + if ( rect.intersects( nr ) ) + { + if ( !cur->isSelected() && cur->isSelectable() ) + { + setSelected( cur, true ); + setActiveMultiSelectItem( at ); + changed = TRUE; + rr = rr.unite( itemRect( cur ) ); + } + } + else + { + if ( cur->isSelected() ) + { + changed = TRUE; + rr = rr.unite( itemRect( cur ) ); + } + + if ( !m_selected || !m_selected->contains( (KonqBaseListViewItem*)cur ) ) + { + setSelected( cur, false ); + setActiveMultiSelectItem( at ); + } + } + + + cur = cur->itemBelow(); + if (cur && !allColumnsShowFocus()) + rect.setWidth( executeArea( cur ) ); + rect.moveBy( 0, rect.height() ); + } + + rect = r; + rect.moveBy( 0, -rect.height() ); + cur = tmp->itemAbove(); + + while ( cur && rect.bottom() >= oldTop ) + { + if ( rect.intersects( nr ) ) + { + if ( !cur->isSelected() && cur->isSelectable() ) + { + setSelected( cur, true ); + setActiveMultiSelectItem( at ); + changed = TRUE; + rr = rr.unite( itemRect( cur ) ); + } + } + else + { + if ( cur->isSelected() ) + { + changed = TRUE; + rr = rr.unite( itemRect( cur ) ); + } + + if ( !m_selected || !m_selected->contains( (KonqBaseListViewItem*)cur ) ) + { + setSelected( cur, false ); + setActiveMultiSelectItem( at ); + } + } + + + cur = cur->itemAbove(); + if (cur && !allColumnsShowFocus()) + rect.setWidth( executeArea( cur ) ); + rect.moveBy( 0, -rect.height() ); + } + } + + blockSignals( block ); + emit selectionChanged(); + + TQRect allRect = oldRubber.normalize(); + if ( changed ) + { + allRect |= rr.normalize(); + } + allRect |= m_rubber->normalize(); + TQPoint point = contentsToViewport( allRect.topLeft() ); + allRect = TQRect( point.x(), point.y(), allRect.width(), allRect.height() ); + allRect &= viewport()->rect(); + allRect.addCoords( -2, -2, 2, 2 ); + + TQPixmap backrubber( viewport()->rect().size() ); + backrubber.fill( viewport(), viewport()->rect().topLeft() ); + + TQPainter p( &backrubber ); + p.save(); + drawContentsOffset( &p, + contentsX(), + contentsY(), + contentsX() + allRect.left(), contentsY() + allRect.top(), + allRect.width(), allRect.height() ); + p.restore(); + drawRubber( &p ); + p.end(); + bitBlt( viewport(), allRect.topLeft(), &backrubber, allRect ); + + const int scroll_margin = 40; + ensureVisible( vc.x(), vc.y(), scroll_margin, scroll_margin ); + + if ( !TQRect( scroll_margin, scroll_margin, + viewport()->width() - 2*scroll_margin, + viewport()->height() - 2*scroll_margin ).contains( pos ) ) + { + if ( !m_scrollTimer ) + { + m_scrollTimer = new TQTimer( this ); + + connect( m_scrollTimer, TQT_SIGNAL( timeout() ), + this, TQT_SLOT( slotAutoScroll() ) ); + m_scrollTimer->start( 100, false ); + } + } + else if ( m_scrollTimer ) + { + disconnect( m_scrollTimer, TQT_SIGNAL( timeout() ), + this, TQT_SLOT( slotAutoScroll() ) ); + m_scrollTimer->stop(); + delete m_scrollTimer; + m_scrollTimer = 0; + } +} + +void KonqBaseListViewWidget::viewportPaintEvent( TQPaintEvent *e ) +{ + + TDEListView::viewportPaintEvent( e ); + + TQPainter p( viewport() ); + drawRubber( &p ); + p.end(); +} + +void KonqBaseListViewWidget::viewportResizeEvent(TQResizeEvent * e) +{ + TDEListView::viewportResizeEvent(e); + emit viewportAdjusted(); +} + +void KonqBaseListViewWidget::viewportDragMoveEvent( TQDragMoveEvent *_ev ) +{ + KonqBaseListViewItem *item = + isExecuteArea( _ev->pos() ) ? (KonqBaseListViewItem*)itemAt( _ev->pos() ) : 0L; + + // Unselect previous drag-over-item + if ( m_dragOverItem && m_dragOverItem != item ) + if ( !m_selected || !m_selected->contains( m_dragOverItem ) ) + setSelected( m_dragOverItem, false ); + + if ( !item ) + { + _ev->acceptAction(); + m_dragOverItem = 0L; + return; + } + + if ( item->item()->acceptsDrops() ) + { + _ev->acceptAction(); + if ( m_dragOverItem != item ) + { + setSelected( item, true ); + m_dragOverItem = item; + } + } + else + { + _ev->ignore(); + m_dragOverItem = 0L; + } +} + +void KonqBaseListViewWidget::viewportDragEnterEvent( TQDragEnterEvent *_ev ) +{ + m_dragOverItem = 0L; + + // By default we accept any format + _ev->acceptAction(); +} + +void KonqBaseListViewWidget::viewportDragLeaveEvent( TQDragLeaveEvent * ) +{ + if ( m_dragOverItem != 0L ) + setSelected( m_dragOverItem, false ); + m_dragOverItem = 0L; +} + +void KonqBaseListViewWidget::viewportDropEvent( TQDropEvent *ev ) +{ + if ( m_dirLister->url().isEmpty() ) + return; + kdDebug() << "KonqBaseListViewWidget::viewportDropEvent" << endl; + if ( m_dragOverItem != 0L ) + setSelected( m_dragOverItem, false ); + m_dragOverItem = 0L; + + ev->accept(); + + // We dropped on an item only if we dropped on the Name column. + KonqBaseListViewItem *item = + isExecuteArea( ev->pos() ) ? (KonqBaseListViewItem*)itemAt( ev->pos() ) : 0; + + KFileItem * destItem = (item) ? item->item() : m_dirLister->rootItem(); + KURL u = destItem ? destItem->url() : url(); + if ( u.isEmpty() ) + return; + KonqOperations::doDrop( destItem /*may be 0L*/, u, ev, this ); +} + +void KonqBaseListViewWidget::startDrag() +{ + m_fileTip->setItem( 0 ); + KURL::List urls = selectedUrls( false ); + + TQListViewItem * m_pressedItem = currentItem(); + + TQPixmap pixmap2; + bool pixmap0Invalid = !m_pressedItem->pixmap(0) || m_pressedItem->pixmap(0)->isNull(); + + // Multiple URLs ? + if (( urls.count() > 1 ) || (pixmap0Invalid)) + { + int iconSize = m_pBrowserView->m_pProps->iconSize(); + iconSize = iconSize ? iconSize : TDEGlobal::iconLoader()->currentSize( TDEIcon::Small ); // Default = small + pixmap2 = DesktopIcon( "application-vnd.tde.tdemultiple", iconSize ); + if ( pixmap2.isNull() ) + kdWarning(1202) << "Could not find multiple pixmap" << endl; + } + + //KURLDrag *d = new KURLDrag( urls, viewport() ); + KonqDrag *drag= new KonqDrag( urls, selectedUrls(true), false, viewport() ); + if ( !pixmap2.isNull() ) + drag->setPixmap( pixmap2 ); + else if ( !pixmap0Invalid ) + drag->setPixmap( *m_pressedItem->pixmap( 0 ) ); + + drag->drag(); +} + +void KonqBaseListViewWidget::slotItemRenamed( TQListViewItem *item, const TQString &name, int col ) +{ + Q_ASSERT( col == 0 ); + Q_ASSERT( item != 0 ); + + // The correct behavior is to show the old name until the rename has successfully + // completed. Unfortunately, TDEListView forces us to allow the text to be changed + // before we try the rename, so set it back to the pre-rename state. + KonqBaseListViewItem *renamedItem = static_cast(item); + renamedItem->updateContents(); + + // Don't do anything if the user renamed to a blank name. + if( !name.isEmpty() ) + { + // Actually attempt the rename. If it succeeds, KDirLister will update the name. + KonqOperations::rename( this, renamedItem->item()->url(), TDEIO::encodeFileName( name ) ); + } + + // When the TDEListViewLineEdit loses focus, focus tends to go to the location bar... + setFocus(); +} + +void KonqBaseListViewWidget::slotRenameNextItem(TQListViewItem *item, int) +{ + TQListViewItem *nextItem = item->itemBelow(); + if (!nextItem) + { + nextItem=this->firstChild(); + if (!nextItem) + return; + } + + deactivateAutomaticSelection(); + setCurrentItem(nextItem); + ListViewBrowserExtension *lvbe = dynamic_cast(m_pBrowserView->m_extension); + if (lvbe) + lvbe->rename(); +} + +void KonqBaseListViewWidget::slotRenamePrevItem(TQListViewItem *item, int) +{ + TQListViewItem *prevItem = item->itemAbove(); + if (!prevItem) + { + prevItem=this->lastItem(); + if (!prevItem) + return; + } + + deactivateAutomaticSelection(); + setCurrentItem(prevItem); + ListViewBrowserExtension *lvbe = dynamic_cast(m_pBrowserView->m_extension); + if (lvbe) + lvbe->rename(); +} + +void KonqBaseListViewWidget::reportItemCounts() +{ + KFileItemList lst = selectedFileItems(); + if ( !lst.isEmpty() ) + m_pBrowserView->emitCounts( lst ); + else + { + lst = visibleFileItems(); + m_pBrowserView->emitCounts( lst ); + } +} + +void KonqBaseListViewWidget::slotSelectionChanged() +{ + reportItemCounts(); + + KFileItemList lst = selectedFileItems(); + emit m_pBrowserView->m_extension->selectionInfo( lst ); +} + +void KonqBaseListViewWidget::slotMouseButtonClicked2( int _button, + TQListViewItem *_item, const TQPoint& pos, int ) +{ + if ( _button == Qt::MidButton ) + { + if ( _item && isExecuteArea( viewport()->mapFromGlobal(pos) ) ) + m_pBrowserView->mmbClicked( static_cast(_item)->item() ); + else // MMB on background + m_pBrowserView->mmbClicked( 0 ); + } +} + +void KonqBaseListViewWidget::slotExecuted( TQListViewItem *item ) +{ + if ( !item ) + return; + m_fileTip->setItem( 0 ); + // isExecuteArea() checks whether the mouse pointer is + // over an area where an action should be triggered + // (i.e. the Name column, including pixmap and "+") + if ( isExecuteArea( viewport()->mapFromGlobal( TQCursor::pos() ) ) ) + slotReturnPressed( item ); +} + +void KonqBaseListViewWidget::selectedItems( TQPtrList *_list ) +{ + iterator it = begin(); + for ( ; it != end(); it++ ) + if ( it->isVisible() && it->isSelected() ) + _list->append( &*it ); +} + +KFileItemList KonqBaseListViewWidget::visibleFileItems() +{ + KFileItemList list; + KonqBaseListViewItem *item = static_cast(firstChild()); + while ( item ) + { + list.append( item->item() ); + item = static_cast(item->itemBelow()); + } + return list; +} + +KFileItemList KonqBaseListViewWidget::selectedFileItems() +{ + KFileItemList list; + iterator it = begin(); + for ( ; it != end(); it++ ) + if ( it->isVisible() && it->isSelected() ) + list.append( it->item() ); + return list; +} + +KURL::List KonqBaseListViewWidget::selectedUrls( bool mostLocal ) +{ + bool dummy; + KURL::List list; + iterator it = begin(); + for ( ; it != end(); it++ ) + if ( it->isVisible() && it->isSelected() ) + list.append( mostLocal ? it->item()->mostLocalURL( dummy ) : it->item()->url() ); + return list; +} + +KonqPropsView * KonqBaseListViewWidget::props() const +{ + return m_pBrowserView->m_pProps; +} + +void KonqBaseListViewWidget::slotReturnPressed( TQListViewItem *_item ) +{ + if ( !_item ) + return; + KFileItem *fileItem = static_cast(_item)->item(); + if ( !fileItem ) + return; + + KURL url = fileItem->url(); + url.cleanPath(); + bool isIntoTrash = url.isLocalFile() && url.path(1).startsWith(TDEGlobalSettings::trashPath()); + if ( !isIntoTrash || (isIntoTrash && fileItem->isDir()) ) + { + m_pBrowserView->lmbClicked( fileItem ); + + if (_item->pixmap(0) != 0) + { + // Rect of the TQListViewItem's pixmap area. + TQRect rect = _item->listView()->itemRect(_item); + + // calculate nesting depth + int nestingDepth = 0; + for (TQListViewItem *currentItem = _item->parent(); + currentItem != 0; + currentItem = currentItem->parent()) + nestingDepth++; + + // no parent no indent + if (_item->parent() == 0) + nestingDepth = 0; + + // Root decoration means additional indent + if (_item->listView()->rootIsDecorated()) + nestingDepth++; + + // set recalculated rect + rect.setLeft(_item->listView()->itemMargin() + _item->listView()->treeStepSize() * nestingDepth); + rect.setWidth(_item->pixmap(0)->width()); + + // gather pixmap + TQPixmap *pix = new TQPixmap(*(_item->pixmap(0))); + + // call the icon effect if enabled + if (TDEGlobalSettings::showKonqIconActivationEffect() == true) { + TDEIconEffect::visualActivate(viewport(), rect, pix); + } + + // clean up + delete(pix); + } + } + else + KMessageBox::information( 0, i18n("You must take the file out of the trash before being able to use it.") ); +} + +void KonqBaseListViewWidget::slotPopupMenu( TQListViewItem *i, const TQPoint &point, int c ) +{ + kdDebug(1202) << "KonqBaseListViewWidget::slotPopupMenu" << endl; + popupMenu( point, ( i != 0 && c == -1 ) ); // i != 0 && c == -1 when activated by keyboard +} + +void KonqBaseListViewWidget::popupMenu( const TQPoint& _global, bool alwaysForSelectedFiles ) +{ + m_fileTip->setItem( 0 ); + + KFileItemList lstItems; + KParts::BrowserExtension::PopupFlags popupFlags = KParts::BrowserExtension::DefaultPopupItems; + + // Only consider a right-click on the name column as something + // related to the selection. On all the other columns, we want + // a popup for the current dir instead. + if ( alwaysForSelectedFiles || isExecuteArea( viewport()->mapFromGlobal( _global ) ) ) + { + TQPtrList items; + selectedItems( &items ); + for ( KonqBaseListViewItem *item = items.first(); item; item = items.next() ) + lstItems.append( item->item() ); + } + + KFileItem *rootItem = 0L; + bool deleteRootItem = false; + if ( lstItems.count() == 0 ) // emit popup for background + { + clearSelection(); + + if ( m_dirLister->url().isEmpty() ) + return; + rootItem = m_dirLister->rootItem(); + if ( !rootItem ) + { + if ( url().isEmpty() ) + return; + // Maybe we want to do a stat to get full info about the root item + // (when we use permissions). For now create a dummy one. + rootItem = new KFileItem( S_IFDIR, (mode_t)-1, url() ); + deleteRootItem = true; + } + + lstItems.append( rootItem ); + popupFlags = KParts::BrowserExtension::ShowNavigationItems | KParts::BrowserExtension::ShowUp; + } + emit m_pBrowserView->extension()->popupMenu( 0, _global, lstItems, KParts::URLArgs(), popupFlags ); + + if ( deleteRootItem ) + delete rootItem; // we just created it +} + +void KonqBaseListViewWidget::updateListContents() +{ + for ( KonqBaseListViewWidget::iterator it = begin(); it != end(); it++ ) + it->updateContents(); +} + +bool KonqBaseListViewWidget::openURL( const KURL &url ) +{ + kdDebug(1202) << k_funcinfo << "protocol: " << url.protocol() + << " url: " << url.path() << endl; + + // The first time or new protocol? So create the columns first. + if ( columns() < 1 || url.protocol() != m_url.protocol() ) + { + readProtocolConfig( url ); + createColumns(); + } + + m_bTopLevelComplete = false; + m_itemFound = false; + + if ( m_itemToGoTo.isEmpty() && url.equals( m_url.upURL(), true ) ) + m_itemToGoTo = m_url.fileName( true ); + + // Check for new properties in the new dir + // newProps returns true the first time, and any time something might + // have changed. + bool newProps = m_pBrowserView->m_pProps->enterDir( url ); + + m_dirLister->setNameFilter( m_pBrowserView->nameFilter() ); + m_dirLister->setMimeFilter( m_pBrowserView->mimeFilter() ); + m_dirLister->setShowingDotFiles( m_pBrowserView->m_pProps->isShowingDotFiles() ); + + KParts::URLArgs args = m_pBrowserView->extension()->urlArgs(); + if ( args.reload ) + { + args.xOffset = contentsX(); + args.yOffset = contentsY(); + m_pBrowserView->extension()->setURLArgs( args ); + + if ( currentItem() && itemRect( currentItem() ).isValid() ) + m_itemToGoTo = currentItem()->text(0); + + m_pBrowserView->m_filesToSelect.clear(); + iterator it = begin(); + for( ; it != end(); it++ ) + if ( it->isSelected() ) + m_pBrowserView->m_filesToSelect += it->text(0); + } + + m_itemsToSelect = m_pBrowserView->m_filesToSelect; + if ( !m_itemsToSelect.isEmpty() && m_itemToGoTo.isEmpty() ) + m_itemToGoTo = m_itemsToSelect[0]; + + if ( columnWidthMode(0) == Maximum ) + setColumnWidth(0,50); + + m_url = url; + m_bUpdateContentsPosAfterListing = true; + + // Start the directory lister ! + m_dirLister->openURL( url, false /* new url */, args.reload ); + + // Apply properties and reflect them on the actions + // do it after starting the dir lister to avoid changing the properties + // of the old view + if ( newProps ) + { + m_pBrowserView->newIconSize( m_pBrowserView->m_pProps->iconSize() ); + m_pBrowserView->m_paShowDot->setChecked( m_pBrowserView->m_pProps->isShowingDotFiles() ); + if ( m_pBrowserView->m_paCaseInsensitive->isChecked() != m_pBrowserView->m_pProps->isCaseInsensitiveSort() ) { + m_pBrowserView->m_paCaseInsensitive->setChecked( m_pBrowserView->m_pProps->isCaseInsensitiveSort() ); + // This is in case openURL returned all items synchronously. + sort(); + } + + // It has to be "viewport()" - this is what KonqDirPart's slots act upon, + // and otherwise we get a color/pixmap in the square between the scrollbars. + m_pBrowserView->m_pProps->applyColors( viewport() ); + } + + return true; +} + +void KonqBaseListViewWidget::setComplete() +{ + kdDebug(1202) << k_funcinfo << "Update Contents Pos: " + << m_bUpdateContentsPosAfterListing << endl; + + m_bTopLevelComplete = true; + + // Alex: this flag is set when we are just finishing a voluntary listing, + // so do the go-to-item thing only under here. When we update the + // current directory automatically (e.g. after a file has been deleted), + // we don't want to go to the first item ! (David) + if ( m_bUpdateContentsPosAfterListing ) + { + m_bUpdateContentsPosAfterListing = false; + + if ( !m_itemFound ) + setCurrentItem( firstChild() ); + + if ( !m_restored && !m_pBrowserView->extension()->urlArgs().reload ) + ensureItemVisible( currentItem() ); + else + setContentsPos( m_pBrowserView->extension()->urlArgs().xOffset, + m_pBrowserView->extension()->urlArgs().yOffset ); + + emit selectionChanged(); + } + + m_itemToGoTo = ""; + m_restored = false; + + // Show totals + reportItemCounts(); + + m_pBrowserView->emitMouseOver( 0 ); + + if ( !isUpdatesEnabled() || !viewport()->isUpdatesEnabled() ) + { + viewport()->setUpdatesEnabled( true ); + setUpdatesEnabled( true ); + triggerUpdate(); + } + + // Show "cut" icons as such + m_pBrowserView->slotClipboardDataChanged(); +} + +void KonqBaseListViewWidget::slotStarted() +{ + //kdDebug(1202) << k_funcinfo << endl; + + if (!m_bTopLevelComplete) + emit m_pBrowserView->started( 0 ); +} + +void KonqBaseListViewWidget::slotCompleted() +{ + //kdDebug(1202) << k_funcinfo << endl; + + setComplete(); + if ( m_bTopLevelComplete ) + emit m_pBrowserView->completed(); + m_pBrowserView->listingComplete(); +} + +void KonqBaseListViewWidget::slotCanceled() +{ + //kdDebug(1202) << k_funcinfo << endl; + + setComplete(); + emit m_pBrowserView->canceled( TQString::null ); +} + +void KonqBaseListViewWidget::slotClear() +{ + //kdDebug(1202) << k_funcinfo << endl; + + m_activeItem = 0; + m_fileTip->setItem( 0 ); + delete m_selected; m_selected = 0; + m_pBrowserView->resetCount(); + m_pBrowserView->lstPendingMimeIconItems().clear(); + + viewport()->setUpdatesEnabled( false ); + setUpdatesEnabled( false ); + clear(); +} + +void KonqBaseListViewWidget::slotNewItems( const KFileItemList & entries ) +{ + //kdDebug(1202) << k_funcinfo << entries.count() << endl; + + for ( TQPtrListIterator kit ( entries ); kit.current(); ++kit ) + { + KonqListViewItem * tmp = new KonqListViewItem( this, *kit ); + if ( !m_itemFound && tmp->text(0) == m_itemToGoTo ) + { + setCurrentItem( tmp ); + m_itemFound = true; + } + if ( !m_itemsToSelect.isEmpty() ) { + TQStringList::Iterator tsit = m_itemsToSelect.find( (*kit)->name() ); + if ( tsit != m_itemsToSelect.end() ) { + m_itemsToSelect.remove( tsit ); + setSelected( tmp, true ); + } + } + if ( !(*kit)->isMimeTypeKnown() ) + m_pBrowserView->lstPendingMimeIconItems().append( tmp ); + } + m_pBrowserView->newItems( entries ); + + if ( !viewport()->isUpdatesEnabled() ) + { + viewport()->setUpdatesEnabled( true ); + setUpdatesEnabled( true ); + triggerUpdate(); + } + slotUpdateBackground(); +} + +void KonqBaseListViewWidget::slotDeleteItem( KFileItem * _fileitem ) +{ + // new in 3.5.5 +#ifdef TDEPARTS_BROWSEREXTENSION_HAS_ITEMS_REMOVED + KFileItemList list; + list.append( _fileitem ); + emit m_pBrowserView->extension()->itemsRemoved( list ); +#else +#error "Your tdelibs doesn't have KParts::BrowserExtension::itemsRemoved, please update it to at least 3.5.5" +#endif + + iterator it = begin(); + for( ; it != end(); ++it ) + if ( (*it).item() == _fileitem ) + { + kdDebug(1202) << k_funcinfo << "removing " << _fileitem->url().url() << " from tree!" << endl; + + m_pBrowserView->deleteItem( _fileitem ); + m_pBrowserView->lstPendingMimeIconItems().remove( &(*it) ); + + if ( m_activeItem == &(*it) ) { + m_fileTip->setItem( 0 ); + m_activeItem = 0; + } + + delete &(*it); + // HACK HACK HACK: TQListViewItem/KonqBaseListViewItem should + // take care and the source looks like it does; till the + // real bug is found, this fixes some crashes (malte) + emit selectionChanged(); + return; + } + + // This is needed for the case the root of the current view is deleted. + // I supposed slotUpdateBackground has to be called as well after an item + // was removed from a listview and was just forgotten previously (Brade). + // OK, but this code also gets activated when deleting a hidden file... (dfaure) + if ( !viewport()->isUpdatesEnabled() ) + { + viewport()->setUpdatesEnabled( true ); + setUpdatesEnabled( true ); + triggerUpdate(); + } + slotUpdateBackground(); +} + +void KonqBaseListViewWidget::slotRefreshItems( const KFileItemList & entries ) +{ + //kdDebug(1202) << k_funcinfo << endl; + + TQPtrListIterator kit ( entries ); + for ( ; kit.current(); ++kit ) + { + iterator it = begin(); + for ( ; it != end(); ++it ) + if ( (*it).item() == kit.current() ) + { + it->updateContents(); + break; + } + } + + m_pBrowserView->refreshItems(entries); // Pass refresh command to KonqDirPart too + reportItemCounts(); +} + +void KonqBaseListViewWidget::slotRedirection( const KURL & url ) +{ + kdDebug(1202) << k_funcinfo << url << endl; + + if ( (columns() < 1) || (url.protocol() != m_url.protocol()) ) + { + readProtocolConfig( url ); + createColumns(); + } + const TQString prettyURL = url.pathOrURL(); + emit m_pBrowserView->extension()->setLocationBarURL( prettyURL ); + emit m_pBrowserView->setWindowCaption( prettyURL ); + m_pBrowserView->m_url = url; + m_url = url; +} + +KonqBaseListViewWidget::iterator& KonqBaseListViewWidget::iterator::operator++() +{ + if ( !m_p ) return *this; + KonqBaseListViewItem *i = (KonqBaseListViewItem *)m_p->firstChild(); + if ( i ) + { + m_p = i; + return *this; + } + i = (KonqBaseListViewItem *)m_p->nextSibling(); + if ( i ) + { + m_p = i; + return *this; + } + m_p = (KonqBaseListViewItem *)m_p->parent(); + + while ( m_p ) + { + if ( m_p->nextSibling() ) + break; + m_p = (KonqBaseListViewItem *)m_p->parent(); + } + + if ( m_p ) + m_p = (KonqBaseListViewItem *)m_p->nextSibling(); + + return *this; +} + +KonqBaseListViewWidget::iterator KonqBaseListViewWidget::iterator::operator++(int) +{ + KonqBaseListViewWidget::iterator it = *this; + if ( !m_p ) return it; + KonqBaseListViewItem *i = (KonqBaseListViewItem *)m_p->firstChild(); + if ( i ) + { + m_p = i; + return it; + } + i = (KonqBaseListViewItem *)m_p->nextSibling(); + if ( i ) + { + m_p = i; + return it; + } + m_p = (KonqBaseListViewItem *)m_p->parent(); + + while ( m_p ) + { + if ( m_p->nextSibling() ) + break; + m_p = (KonqBaseListViewItem *)m_p->parent(); + } + + if ( m_p ) + m_p = (KonqBaseListViewItem *)m_p->nextSibling(); + return it; +} + +void KonqBaseListViewWidget::paintEmptyArea( TQPainter *p, const TQRect &r ) +{ + const TQPixmap *pm = TQT_TQPIXMAP_CONST(viewport()->paletteBackgroundPixmap()); + + if (!pm || pm->isNull()) + p->fillRect(r, viewport()->backgroundColor()); + else + { + TQRect devRect = p->xForm( r ); + int ax = (devRect.x() + contentsX()); + int ay = (devRect.y() + contentsY()); + /* kdDebug() << "KonqBaseListViewWidget::paintEmptyArea " + << r.x() << "," << r.y() << " " << r.width() << "x" << r.height() + << " drawing pixmap with offset " << ax << "," << ay + << endl;*/ + p->drawTiledPixmap(r, *pm, TQPoint(ax, ay)); + } +} + +void KonqBaseListViewWidget::disableIcons( const KURL::List & lst ) +{ + iterator kit = begin(); + for( ; kit != end(); ++kit ) + { + bool bFound = false; + // Wow. This is ugly. Matching two lists together.... + // Some sorting to optimise this would be a good idea ? + for (KURL::List::ConstIterator it = lst.begin(); !bFound && it != lst.end(); ++it) + { + if ( (*kit).item()->url() == *it ) // *it is encoded already + { + bFound = true; + // maybe remove "it" from lst here ? + } + } + (*kit).setDisabled( bFound ); + } +} + +void KonqBaseListViewWidget::saveState( TQDataStream & ds ) +{ + TQString str; + if ( currentItem() ) + str = static_cast(currentItem())->item()->url().fileName(true); + ds << str << m_url; +} + +void KonqBaseListViewWidget::restoreState( TQDataStream & ds ) +{ + m_restored = true; + + TQString str; + KURL url; + ds >> str >> url; + if ( !str.isEmpty() ) + m_itemToGoTo = str; + + if ( columns() < 1 || url.protocol() != m_url.protocol() ) + { + readProtocolConfig( url ); + createColumns(); + } + m_url = url; + + m_bTopLevelComplete = false; + m_itemFound = false; +} + +void KonqBaseListViewWidget::slotUpdateBackground() +{ + if ( viewport()->paletteBackgroundPixmap() && !viewport()->paletteBackgroundPixmap()->isNull() ) + { + if ( !m_backgroundTimer ) + { + m_backgroundTimer = new TQTimer( this ); + connect( m_backgroundTimer, TQT_SIGNAL( timeout() ), viewport(), TQT_SLOT( update() ) ); + } + else + m_backgroundTimer->stop(); + + m_backgroundTimer->start( 50, true ); + } +} + +bool KonqBaseListViewWidget::caseInsensitiveSort() const +{ + return m_pBrowserView->m_pProps->isCaseInsensitiveSort(); +} + +// based on isExecuteArea from tdelistview.cpp +int KonqBaseListViewWidget::executeArea( TQListViewItem *_item ) +{ + if ( !_item ) + return 0; + + int width = treeStepSize() * ( _item->depth() + ( rootIsDecorated() ? 1 : 0 ) ); + width += itemMargin(); + int ca = AlignHorizontal_Mask & columnAlignment( 0 ); + if ( ca == AlignLeft || ca == AlignAuto ) + { + width += _item->width( fontMetrics(), this, 0 ); + if ( width > columnWidth( 0 ) ) + width = columnWidth( 0 ); + } + return width; +} + +#include "konq_listviewwidget.moc" diff --git a/konqueror/listview/konq_textviewitem.cc b/konqueror/listview/konq_textviewitem.cc deleted file mode 100644 index 1076e10af..000000000 --- a/konqueror/listview/konq_textviewitem.cc +++ /dev/null @@ -1,258 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 1998, 1999 Torben Weis - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "konq_textviewitem.h" -#include "konq_settings.h" - -#include -#include -#include - -int KonqTextViewItem::compare( TQListViewItem *item, int col, bool ascending ) const -{ - if (col==1) - return KonqBaseListViewItem::compare(item, 0, ascending); - return KonqBaseListViewItem::compare(item, col, ascending); -} - -/*TQString KonqTextViewItem::key( int _column, bool asc) const -{ - if (_column==1) return key(0,asc); - TQString tmp = TQString::number( sortChar ); - //check if it is a time column - if (_column>1) - { - KonqTextViewWidget* lv = static_cast(listView()); - for (unsigned int i=0; iNumberOfAtoms; i++) - { - ColumnInfo *cInfo=&lv->columnConfigInfo()[i]; - if (_column==cInfo->displayInColumn) - { - if ((cInfo->udsId==TDEIO::UDS_MODIFICATION_TIME) - || (cInfo->udsId==TDEIO::UDS_ACCESS_TIME) - || (cInfo->udsId==TDEIO::UDS_CREATION_TIME)) - { - tmp += TQString::number( m_fileitem->time(cInfo->udsId) ).rightJustify( 14, '0' ); - return tmp; - } - else if (cInfo->udsId==TDEIO::UDS_SIZE) - { - tmp += TDEIO::number( m_fileitem->size() ).rightJustify( 20, '0' ); - return tmp; - } - else break; - - }; - }; - }; - tmp+=text(_column); - return tmp; -}*/ - -void KonqTextViewItem::updateContents() -{ - TQString tmp; - TDEIO::filesize_t size=m_fileitem->size(); - mode_t m=m_fileitem->mode(); - - // The order is: .dir (0), dir (1), .file (2), file (3) - sortChar = S_ISDIR( m_fileitem->mode() ) ? 1 : 3; - if ( m_fileitem->text()[0] == '.' ) - --sortChar; - - if (m_fileitem->isLink()) - { - if (S_ISDIR(m)) - { - type=KTVI_DIRLINK; - tmp="~"; - } - else if ((S_ISREG(m)) || (S_ISCHR(m)) || (S_ISBLK(m)) || (S_ISSOCK(m)) || (S_ISFIFO(m))) - { - tmp="@"; - type=KTVI_REGULARLINK; - } - else - { - tmp="!"; - type=KTVI_UNKNOWN; - size=0; - }; - } - else if (S_ISREG(m)) - { - if ((m_fileitem->permissions() & (S_IXUSR|S_IXGRP|S_IXOTH)) !=0 ) - { - tmp="*"; - type=KTVI_EXEC; - } - else - { - tmp=""; - type=KTVI_REGULAR; - }; - } - else if (S_ISDIR(m)) - { - type=KTVI_DIR; - tmp="/"; - } - else if (S_ISCHR(m)) - { - type=KTVI_CHARDEV; - tmp="-"; - } - else if (S_ISBLK(m)) - { - type=KTVI_BLOCKDEV; - tmp="+"; - } - else if (S_ISSOCK(m)) - { - type=KTVI_SOCKET; - tmp="="; - } - else if (S_ISFIFO(m)) - { - type=KTVI_FIFO; - tmp=">"; - } - else - { - tmp="!"; - type=KTVI_UNKNOWN; - size=0; - }; - setText(1,tmp); - setText(0,m_fileitem->text()); - //now we have the first two columns, so let's do the rest - KonqTextViewWidget* lv = static_cast(listView()); - - for (unsigned int i=0; iNumberOfAtoms; i++) - { - ColumnInfo *tmpColumn=&lv->confColumns[i]; - if (tmpColumn->displayThisOne) - { - switch (tmpColumn->udsId) - { - case TDEIO::UDS_USER: - setText(tmpColumn->displayInColumn,m_fileitem->user()); - break; - case TDEIO::UDS_GROUP: - setText(tmpColumn->displayInColumn,m_fileitem->group()); - break; - case TDEIO::UDS_LINK_DEST: - setText(tmpColumn->displayInColumn,m_fileitem->linkDest()); - break; - case TDEIO::UDS_FILE_TYPE: - if (m_fileitem->isMimeTypeKnown()) { - setText(tmpColumn->displayInColumn,m_fileitem->mimeComment()); - } - break; - case TDEIO::UDS_MIME_TYPE: - if (m_fileitem->isMimeTypeKnown()) { - setText(tmpColumn->displayInColumn,m_fileitem->mimetype()); - } - break; - case TDEIO::UDS_URL: - setText(tmpColumn->displayInColumn,m_fileitem->url().prettyURL()); - break; - case TDEIO::UDS_SIZE: - if ( static_cast(listView())->m_pSettings->fileSizeInBytes() ) - setText(tmpColumn->displayInColumn,TDEGlobal::locale()->formatNumber(size, 0)+" "); - else - setText(tmpColumn->displayInColumn,TDEIO::convertSize(size)+" "); - break; - case TDEIO::UDS_ACCESS: - setText(tmpColumn->displayInColumn,m_fileitem->permissionsString()); - break; - case TDEIO::UDS_MODIFICATION_TIME: - case TDEIO::UDS_ACCESS_TIME: - case TDEIO::UDS_CREATION_TIME: - for( TDEIO::UDSEntry::ConstIterator it = m_fileitem->entry().begin(); it != m_fileitem->entry().end(); it++ ) - { - if ((*it).m_uds==(unsigned int)tmpColumn->udsId) - { - TQDateTime dt; - dt.setTime_t((time_t) (*it).m_long); - setText(tmpColumn->displayInColumn,TDEGlobal::locale()->formatDateTime(dt)); - break; - }; - - }; - break; - default: - break; - }; - }; - }; -} - -void KonqTextViewItem::paintCell( TQPainter *_painter, const TQColorGroup & _cg, int _column, int _width, int _alignment ) -{ - TQColorGroup cg( _cg ); - cg.setColor(TQColorGroup::Text, static_cast(listView())->colors[type]); - // Don't do that! Keep things readable whatever the selection background color is -// cg.setColor(TQColorGroup::HighlightedText, static_cast(listView())->highlight[type]); -// cg.setColor(TQColorGroup::Highlight, Qt::darkGray); - - TDEListViewItem::paintCell( _painter, cg, _column, _width, _alignment ); -} - -/*void KonqTextViewItem::paintFocus( TQPainter *_p, const TQColorGroup &_cg, const TQRect &_r ) -{ - listView()->style().drawFocusRect( _p, _r, _cg, - isSelected() ? &_cg.highlight() : &_cg.base(), isSelected() ); - - TQPixmap pix( _r.width(), _r.height() ); - bitBlt( &pix, 0, 0, _p->device(), _r.left(), _r.top(), _r.width(), _r.height() ); - TQImage im = pix.convertToImage(); - im = KImageEffect::fade( im, 0.25, Qt::black ); - _p->drawImage( _r.topLeft(), im ); -}*/ - -void KonqTextViewItem::setup() -{ - widthChanged(); - int h(listView()->fontMetrics().height()); - if ( h % 2 > 0 ) h++; - setHeight(h); -} - -void KonqTextViewItem::mimetypeFound() -{ - // Update icon - setDisabled( m_bDisabled ); - uint done = 0; - KonqBaseListViewWidget * lv = m_pListViewWidget; - for (unsigned int i=0; iNumberOfAtoms && done < 2; i++) - { - ColumnInfo *tmpColumn=&lv->columnConfigInfo()[i]; - if (lv->columnConfigInfo()[i].udsId==TDEIO::UDS_FILE_TYPE && tmpColumn->displayThisOne) - { - setText(tmpColumn->displayInColumn, m_fileitem->mimeComment()); - done++; - } - if (lv->columnConfigInfo()[i].udsId==TDEIO::UDS_MIME_TYPE && tmpColumn->displayThisOne) - { - setText(tmpColumn->displayInColumn, m_fileitem->mimetype()); - done++; - } - } -} \ No newline at end of file diff --git a/konqueror/listview/konq_textviewitem.cpp b/konqueror/listview/konq_textviewitem.cpp new file mode 100644 index 000000000..1076e10af --- /dev/null +++ b/konqueror/listview/konq_textviewitem.cpp @@ -0,0 +1,258 @@ +/* This file is part of the KDE project + Copyright (C) 1998, 1999 Torben Weis + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "konq_textviewitem.h" +#include "konq_settings.h" + +#include +#include +#include + +int KonqTextViewItem::compare( TQListViewItem *item, int col, bool ascending ) const +{ + if (col==1) + return KonqBaseListViewItem::compare(item, 0, ascending); + return KonqBaseListViewItem::compare(item, col, ascending); +} + +/*TQString KonqTextViewItem::key( int _column, bool asc) const +{ + if (_column==1) return key(0,asc); + TQString tmp = TQString::number( sortChar ); + //check if it is a time column + if (_column>1) + { + KonqTextViewWidget* lv = static_cast(listView()); + for (unsigned int i=0; iNumberOfAtoms; i++) + { + ColumnInfo *cInfo=&lv->columnConfigInfo()[i]; + if (_column==cInfo->displayInColumn) + { + if ((cInfo->udsId==TDEIO::UDS_MODIFICATION_TIME) + || (cInfo->udsId==TDEIO::UDS_ACCESS_TIME) + || (cInfo->udsId==TDEIO::UDS_CREATION_TIME)) + { + tmp += TQString::number( m_fileitem->time(cInfo->udsId) ).rightJustify( 14, '0' ); + return tmp; + } + else if (cInfo->udsId==TDEIO::UDS_SIZE) + { + tmp += TDEIO::number( m_fileitem->size() ).rightJustify( 20, '0' ); + return tmp; + } + else break; + + }; + }; + }; + tmp+=text(_column); + return tmp; +}*/ + +void KonqTextViewItem::updateContents() +{ + TQString tmp; + TDEIO::filesize_t size=m_fileitem->size(); + mode_t m=m_fileitem->mode(); + + // The order is: .dir (0), dir (1), .file (2), file (3) + sortChar = S_ISDIR( m_fileitem->mode() ) ? 1 : 3; + if ( m_fileitem->text()[0] == '.' ) + --sortChar; + + if (m_fileitem->isLink()) + { + if (S_ISDIR(m)) + { + type=KTVI_DIRLINK; + tmp="~"; + } + else if ((S_ISREG(m)) || (S_ISCHR(m)) || (S_ISBLK(m)) || (S_ISSOCK(m)) || (S_ISFIFO(m))) + { + tmp="@"; + type=KTVI_REGULARLINK; + } + else + { + tmp="!"; + type=KTVI_UNKNOWN; + size=0; + }; + } + else if (S_ISREG(m)) + { + if ((m_fileitem->permissions() & (S_IXUSR|S_IXGRP|S_IXOTH)) !=0 ) + { + tmp="*"; + type=KTVI_EXEC; + } + else + { + tmp=""; + type=KTVI_REGULAR; + }; + } + else if (S_ISDIR(m)) + { + type=KTVI_DIR; + tmp="/"; + } + else if (S_ISCHR(m)) + { + type=KTVI_CHARDEV; + tmp="-"; + } + else if (S_ISBLK(m)) + { + type=KTVI_BLOCKDEV; + tmp="+"; + } + else if (S_ISSOCK(m)) + { + type=KTVI_SOCKET; + tmp="="; + } + else if (S_ISFIFO(m)) + { + type=KTVI_FIFO; + tmp=">"; + } + else + { + tmp="!"; + type=KTVI_UNKNOWN; + size=0; + }; + setText(1,tmp); + setText(0,m_fileitem->text()); + //now we have the first two columns, so let's do the rest + KonqTextViewWidget* lv = static_cast(listView()); + + for (unsigned int i=0; iNumberOfAtoms; i++) + { + ColumnInfo *tmpColumn=&lv->confColumns[i]; + if (tmpColumn->displayThisOne) + { + switch (tmpColumn->udsId) + { + case TDEIO::UDS_USER: + setText(tmpColumn->displayInColumn,m_fileitem->user()); + break; + case TDEIO::UDS_GROUP: + setText(tmpColumn->displayInColumn,m_fileitem->group()); + break; + case TDEIO::UDS_LINK_DEST: + setText(tmpColumn->displayInColumn,m_fileitem->linkDest()); + break; + case TDEIO::UDS_FILE_TYPE: + if (m_fileitem->isMimeTypeKnown()) { + setText(tmpColumn->displayInColumn,m_fileitem->mimeComment()); + } + break; + case TDEIO::UDS_MIME_TYPE: + if (m_fileitem->isMimeTypeKnown()) { + setText(tmpColumn->displayInColumn,m_fileitem->mimetype()); + } + break; + case TDEIO::UDS_URL: + setText(tmpColumn->displayInColumn,m_fileitem->url().prettyURL()); + break; + case TDEIO::UDS_SIZE: + if ( static_cast(listView())->m_pSettings->fileSizeInBytes() ) + setText(tmpColumn->displayInColumn,TDEGlobal::locale()->formatNumber(size, 0)+" "); + else + setText(tmpColumn->displayInColumn,TDEIO::convertSize(size)+" "); + break; + case TDEIO::UDS_ACCESS: + setText(tmpColumn->displayInColumn,m_fileitem->permissionsString()); + break; + case TDEIO::UDS_MODIFICATION_TIME: + case TDEIO::UDS_ACCESS_TIME: + case TDEIO::UDS_CREATION_TIME: + for( TDEIO::UDSEntry::ConstIterator it = m_fileitem->entry().begin(); it != m_fileitem->entry().end(); it++ ) + { + if ((*it).m_uds==(unsigned int)tmpColumn->udsId) + { + TQDateTime dt; + dt.setTime_t((time_t) (*it).m_long); + setText(tmpColumn->displayInColumn,TDEGlobal::locale()->formatDateTime(dt)); + break; + }; + + }; + break; + default: + break; + }; + }; + }; +} + +void KonqTextViewItem::paintCell( TQPainter *_painter, const TQColorGroup & _cg, int _column, int _width, int _alignment ) +{ + TQColorGroup cg( _cg ); + cg.setColor(TQColorGroup::Text, static_cast(listView())->colors[type]); + // Don't do that! Keep things readable whatever the selection background color is +// cg.setColor(TQColorGroup::HighlightedText, static_cast(listView())->highlight[type]); +// cg.setColor(TQColorGroup::Highlight, Qt::darkGray); + + TDEListViewItem::paintCell( _painter, cg, _column, _width, _alignment ); +} + +/*void KonqTextViewItem::paintFocus( TQPainter *_p, const TQColorGroup &_cg, const TQRect &_r ) +{ + listView()->style().drawFocusRect( _p, _r, _cg, + isSelected() ? &_cg.highlight() : &_cg.base(), isSelected() ); + + TQPixmap pix( _r.width(), _r.height() ); + bitBlt( &pix, 0, 0, _p->device(), _r.left(), _r.top(), _r.width(), _r.height() ); + TQImage im = pix.convertToImage(); + im = KImageEffect::fade( im, 0.25, Qt::black ); + _p->drawImage( _r.topLeft(), im ); +}*/ + +void KonqTextViewItem::setup() +{ + widthChanged(); + int h(listView()->fontMetrics().height()); + if ( h % 2 > 0 ) h++; + setHeight(h); +} + +void KonqTextViewItem::mimetypeFound() +{ + // Update icon + setDisabled( m_bDisabled ); + uint done = 0; + KonqBaseListViewWidget * lv = m_pListViewWidget; + for (unsigned int i=0; iNumberOfAtoms && done < 2; i++) + { + ColumnInfo *tmpColumn=&lv->columnConfigInfo()[i]; + if (lv->columnConfigInfo()[i].udsId==TDEIO::UDS_FILE_TYPE && tmpColumn->displayThisOne) + { + setText(tmpColumn->displayInColumn, m_fileitem->mimeComment()); + done++; + } + if (lv->columnConfigInfo()[i].udsId==TDEIO::UDS_MIME_TYPE && tmpColumn->displayThisOne) + { + setText(tmpColumn->displayInColumn, m_fileitem->mimetype()); + done++; + } + } +} \ No newline at end of file diff --git a/konqueror/listview/konq_textviewwidget.cc b/konqueror/listview/konq_textviewwidget.cc deleted file mode 100644 index ab227899a..000000000 --- a/konqueror/listview/konq_textviewwidget.cc +++ /dev/null @@ -1,224 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 1998, 1999 Torben Weis - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "konq_listview.h" -#include "konq_textviewitem.h" - -#include - -#include -#include - -#include -#include - - -KonqTextViewWidget::KonqTextViewWidget( KonqListView *parent, TQWidget *parentWidget ) -:KonqBaseListViewWidget(parent,parentWidget) -{ - kdDebug(1202) << "+KonqTextViewWidget" << endl; - m_filenameColumn=1; - - // David: This breaks dropping things towards the current directory - // using the columns != Name. - // I know, but I want to have it this way and I use it all the time. - // If I want to have free space, I disable some columns. - // If people don't like it, they can use a different view type. Alex - setAllColumnsShowFocus(TRUE); - setRootIsDecorated(false); - - colors[KTVI_REGULAR]=Qt::black; - colors[KTVI_EXEC]=TQColor(0,170,0); - colors[KTVI_REGULARLINK]=Qt::black; - colors[KTVI_DIR]=Qt::black; - colors[KTVI_DIRLINK]=Qt::black; - colors[KTVI_BADLINK]=Qt::red; - colors[KTVI_SOCKET]=Qt::magenta; - colors[KTVI_FIFO]=Qt::magenta; - colors[KTVI_UNKNOWN]=Qt::red; - colors[KTVI_CHARDEV]=Qt::blue; - colors[KTVI_BLOCKDEV]=Qt::blue; - - m_showIcons=FALSE; -} - -KonqTextViewWidget::~KonqTextViewWidget() -{} - -void KonqTextViewWidget::createColumns() -{ - if (columns()<2) - { - addColumn( i18n("Name"), m_filenameColumnWidth ); - addColumn( " ", fontMetrics().width("@") + 2 ); - setColumnAlignment( 1, AlignRight ); - //this way the column with the name has the index 0 and - //so the "jump to filename beginning with this character" works - header()->moveSection( 0, 2 ); - } - KonqBaseListViewWidget::createColumns(); -} - -void KonqTextViewWidget::slotNewItems( const KFileItemList & entries ) -{ - //kdDebug(1202) << k_funcinfo << entries.count() << endl; - - for ( TQPtrListIterator kit ( entries ); kit.current(); ++kit ) - { - KonqTextViewItem *tmp = new KonqTextViewItem( this, *kit ); - if ( !m_itemFound && tmp->text(0) == m_itemToGoTo ) - { - setCurrentItem( tmp ); - m_itemFound = true; - } - if ( !m_itemsToSelect.isEmpty() ) { - TQStringList::Iterator tsit = m_itemsToSelect.find( (*kit)->name() ); - if ( tsit != m_itemsToSelect.end() ) { - m_itemsToSelect.remove( tsit ); - setSelected( tmp, true ); - } - } - if ( !(*kit)->isMimeTypeKnown() ) - m_pBrowserView->lstPendingMimeIconItems().append( tmp ); - } - - m_pBrowserView->newItems( entries ); - - if ( !viewport()->isUpdatesEnabled() ) - { - viewport()->setUpdatesEnabled( true ); - setUpdatesEnabled( true ); - triggerUpdate(); - } - slotUpdateBackground(); -} - -void KonqTextViewWidget::setComplete() -{ - kdDebug(1202) << k_funcinfo << "Update Contents Pos: " - << m_bUpdateContentsPosAfterListing << endl; - - m_bTopLevelComplete = true; - - // Alex: this flag is set when we are just finishing a voluntary listing, - // so do the go-to-item thing only under here. When we update the - // current directory automatically (e.g. after a file has been deleted), - // we don't want to go to the first item ! (David) - if ( m_bUpdateContentsPosAfterListing ) - { - m_bUpdateContentsPosAfterListing = false; - - if ( !m_itemFound ) - setCurrentItem( firstChild() ); - - if ( !m_restored && !m_pBrowserView->extension()->urlArgs().reload ) - ensureItemVisible( currentItem() ); - else - setContentsPos( m_pBrowserView->extension()->urlArgs().xOffset, - m_pBrowserView->extension()->urlArgs().yOffset ); - - activateAutomaticSelection(); - emit selectionChanged(); - } - - m_itemToGoTo = ""; - m_restored = false; - - // Show "cut" icons as such - m_pBrowserView->slotClipboardDataChanged(); - // Show totals - slotOnViewport(); - - if ( !isUpdatesEnabled() || !viewport()->isUpdatesEnabled() ) - { - viewport()->setUpdatesEnabled( true ); - setUpdatesEnabled( true ); - triggerUpdate(); - } -} - -bool KonqTextViewWidget::isExecuteArea( const TQPoint& point ) -{ - if (!itemAt( point ) ) - return false; - int x=point.x(); - - int offset = 0; - int width = columnWidth( 0 ); - int pos = header()->mapToIndex( 0 ); - - for ( int index = 0; index < pos; index++ ) - offset += columnWidth( header()->mapToSection( index ) ); - - return ( x > offset && x < ( offset + width ) ); -} - -/*void KonqTextViewWidget::viewportDragMoveEvent( TQDragMoveEvent *_ev ) -{ - KonqBaseListViewItem *item = - isNameColumn( _ev->pos() ) ? (KonqBaseListViewItem*)itemAt( _ev->pos() ) : 0L; - - if ( !item ) - { - if ( m_dragOverItem ) - setSelected( m_dragOverItem, false ); - _ev->accept(); - return; - } - - if ( m_dragOverItem == item ) - return; // No change - - if ( m_dragOverItem != 0L ) - setSelected( m_dragOverItem, false ); - - if ( item->item()->acceptsDrops() ) - { - _ev->accept(); - setSelected( item, true ); - m_dragOverItem = item; - } - else - { - _ev->ignore(); - m_dragOverItem = 0L; - } -} - -void KonqTextViewWidget::viewportDropEvent( TQDropEvent *ev ) -{ - if ( m_dirLister->url().isEmpty() ) - return; - kdDebug() << "KonqTextViewWidget::viewportDropEvent" << endl; - if ( m_dragOverItem != 0L ) - setSelected( m_dragOverItem, false ); - m_dragOverItem = 0L; - - ev->accept(); - - // We dropped on an item only if we dropped on the Name column. - KonqBaseListViewItem *item = - isNameColumn( ev->pos() ) ? (KonqBaseListViewItem*)itemAt( ev->pos() ) : 0; - - KFileItem * destItem = (item) ? item->item() : m_dirLister->rootItem(); // may be 0 - KonqOperations::doDrop( destItem, destItem ? destItem->url() : url(), ev, this ); -}*/ - - -#include "konq_textviewwidget.moc" diff --git a/konqueror/listview/konq_textviewwidget.cpp b/konqueror/listview/konq_textviewwidget.cpp new file mode 100644 index 000000000..ab227899a --- /dev/null +++ b/konqueror/listview/konq_textviewwidget.cpp @@ -0,0 +1,224 @@ +/* This file is part of the KDE project + Copyright (C) 1998, 1999 Torben Weis + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "konq_listview.h" +#include "konq_textviewitem.h" + +#include + +#include +#include + +#include +#include + + +KonqTextViewWidget::KonqTextViewWidget( KonqListView *parent, TQWidget *parentWidget ) +:KonqBaseListViewWidget(parent,parentWidget) +{ + kdDebug(1202) << "+KonqTextViewWidget" << endl; + m_filenameColumn=1; + + // David: This breaks dropping things towards the current directory + // using the columns != Name. + // I know, but I want to have it this way and I use it all the time. + // If I want to have free space, I disable some columns. + // If people don't like it, they can use a different view type. Alex + setAllColumnsShowFocus(TRUE); + setRootIsDecorated(false); + + colors[KTVI_REGULAR]=Qt::black; + colors[KTVI_EXEC]=TQColor(0,170,0); + colors[KTVI_REGULARLINK]=Qt::black; + colors[KTVI_DIR]=Qt::black; + colors[KTVI_DIRLINK]=Qt::black; + colors[KTVI_BADLINK]=Qt::red; + colors[KTVI_SOCKET]=Qt::magenta; + colors[KTVI_FIFO]=Qt::magenta; + colors[KTVI_UNKNOWN]=Qt::red; + colors[KTVI_CHARDEV]=Qt::blue; + colors[KTVI_BLOCKDEV]=Qt::blue; + + m_showIcons=FALSE; +} + +KonqTextViewWidget::~KonqTextViewWidget() +{} + +void KonqTextViewWidget::createColumns() +{ + if (columns()<2) + { + addColumn( i18n("Name"), m_filenameColumnWidth ); + addColumn( " ", fontMetrics().width("@") + 2 ); + setColumnAlignment( 1, AlignRight ); + //this way the column with the name has the index 0 and + //so the "jump to filename beginning with this character" works + header()->moveSection( 0, 2 ); + } + KonqBaseListViewWidget::createColumns(); +} + +void KonqTextViewWidget::slotNewItems( const KFileItemList & entries ) +{ + //kdDebug(1202) << k_funcinfo << entries.count() << endl; + + for ( TQPtrListIterator kit ( entries ); kit.current(); ++kit ) + { + KonqTextViewItem *tmp = new KonqTextViewItem( this, *kit ); + if ( !m_itemFound && tmp->text(0) == m_itemToGoTo ) + { + setCurrentItem( tmp ); + m_itemFound = true; + } + if ( !m_itemsToSelect.isEmpty() ) { + TQStringList::Iterator tsit = m_itemsToSelect.find( (*kit)->name() ); + if ( tsit != m_itemsToSelect.end() ) { + m_itemsToSelect.remove( tsit ); + setSelected( tmp, true ); + } + } + if ( !(*kit)->isMimeTypeKnown() ) + m_pBrowserView->lstPendingMimeIconItems().append( tmp ); + } + + m_pBrowserView->newItems( entries ); + + if ( !viewport()->isUpdatesEnabled() ) + { + viewport()->setUpdatesEnabled( true ); + setUpdatesEnabled( true ); + triggerUpdate(); + } + slotUpdateBackground(); +} + +void KonqTextViewWidget::setComplete() +{ + kdDebug(1202) << k_funcinfo << "Update Contents Pos: " + << m_bUpdateContentsPosAfterListing << endl; + + m_bTopLevelComplete = true; + + // Alex: this flag is set when we are just finishing a voluntary listing, + // so do the go-to-item thing only under here. When we update the + // current directory automatically (e.g. after a file has been deleted), + // we don't want to go to the first item ! (David) + if ( m_bUpdateContentsPosAfterListing ) + { + m_bUpdateContentsPosAfterListing = false; + + if ( !m_itemFound ) + setCurrentItem( firstChild() ); + + if ( !m_restored && !m_pBrowserView->extension()->urlArgs().reload ) + ensureItemVisible( currentItem() ); + else + setContentsPos( m_pBrowserView->extension()->urlArgs().xOffset, + m_pBrowserView->extension()->urlArgs().yOffset ); + + activateAutomaticSelection(); + emit selectionChanged(); + } + + m_itemToGoTo = ""; + m_restored = false; + + // Show "cut" icons as such + m_pBrowserView->slotClipboardDataChanged(); + // Show totals + slotOnViewport(); + + if ( !isUpdatesEnabled() || !viewport()->isUpdatesEnabled() ) + { + viewport()->setUpdatesEnabled( true ); + setUpdatesEnabled( true ); + triggerUpdate(); + } +} + +bool KonqTextViewWidget::isExecuteArea( const TQPoint& point ) +{ + if (!itemAt( point ) ) + return false; + int x=point.x(); + + int offset = 0; + int width = columnWidth( 0 ); + int pos = header()->mapToIndex( 0 ); + + for ( int index = 0; index < pos; index++ ) + offset += columnWidth( header()->mapToSection( index ) ); + + return ( x > offset && x < ( offset + width ) ); +} + +/*void KonqTextViewWidget::viewportDragMoveEvent( TQDragMoveEvent *_ev ) +{ + KonqBaseListViewItem *item = + isNameColumn( _ev->pos() ) ? (KonqBaseListViewItem*)itemAt( _ev->pos() ) : 0L; + + if ( !item ) + { + if ( m_dragOverItem ) + setSelected( m_dragOverItem, false ); + _ev->accept(); + return; + } + + if ( m_dragOverItem == item ) + return; // No change + + if ( m_dragOverItem != 0L ) + setSelected( m_dragOverItem, false ); + + if ( item->item()->acceptsDrops() ) + { + _ev->accept(); + setSelected( item, true ); + m_dragOverItem = item; + } + else + { + _ev->ignore(); + m_dragOverItem = 0L; + } +} + +void KonqTextViewWidget::viewportDropEvent( TQDropEvent *ev ) +{ + if ( m_dirLister->url().isEmpty() ) + return; + kdDebug() << "KonqTextViewWidget::viewportDropEvent" << endl; + if ( m_dragOverItem != 0L ) + setSelected( m_dragOverItem, false ); + m_dragOverItem = 0L; + + ev->accept(); + + // We dropped on an item only if we dropped on the Name column. + KonqBaseListViewItem *item = + isNameColumn( ev->pos() ) ? (KonqBaseListViewItem*)itemAt( ev->pos() ) : 0; + + KFileItem * destItem = (item) ? item->item() : m_dirLister->rootItem(); // may be 0 + KonqOperations::doDrop( destItem, destItem ? destItem->url() : url(), ev, this ); +}*/ + + +#include "konq_textviewwidget.moc" diff --git a/konqueror/listview/konq_treeviewitem.cc b/konqueror/listview/konq_treeviewitem.cc deleted file mode 100644 index 12953c401..000000000 --- a/konqueror/listview/konq_treeviewitem.cc +++ /dev/null @@ -1,101 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 1998, 1999 Torben Weis - 2001, 2002, 2004 Michael Brade - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "konq_treeviewwidget.h" -#include "konq_listview.h" - - -KonqListViewDir::KonqListViewDir( KonqTreeViewWidget *_parent, KFileItem* _fileitem ) - : KonqListViewItem( _parent, _fileitem ) -{ - setExpandable( true ); - m_bComplete = false; -} - -KonqListViewDir::KonqListViewDir( KonqTreeViewWidget *_treeview, KonqListViewDir *_parent, KFileItem *_fileitem ) - : KonqListViewItem( _treeview, _parent, _fileitem ) -{ - setExpandable( true ); - m_bComplete = false; -} - -void KonqListViewDir::setOpen( bool _open ) -{ - open( _open, false ); -} - -void KonqListViewDir::open( bool _open, bool _reload ) -{ - if ( _open != isOpen() || _reload ) - { - KonqTreeViewWidget *treeView = static_cast(m_pListViewWidget); - - if ( _open ) - { - if ( !m_bComplete || _reload ) // complete it before opening - treeView->openSubFolder( this, _reload ); - else - { - // we need to add the items to the counts for the statusbar - KFileItemList lst; - lst.setAutoDelete( false ); - - TQListViewItem* it = firstChild(); - while ( it ) - { - lst.append( static_cast(it)->item() ); - it = it->nextSibling(); - } - - // tell the view about the new items to count - treeView->m_pBrowserView->newItems( lst ); - } - } - else - { - treeView->stopListingSubFolder( this ); - - TQListViewItem* it = firstChild(); - while ( it ) - { - // unselect the items in the closed folder - treeView->setSelected( it, false ); - // delete the item from the counts for the statusbar - KFileItem* item = static_cast(it)->item(); - treeView->m_pBrowserView->deleteItem( item ); - it = it->nextSibling(); - } - } - - TQListViewItem::setOpen( _open ); - treeView->slotOnViewport(); - } -} - -KURL KonqListViewDir::kurl() -{ - return m_fileitemURL; -} - -TQString KonqListViewDir::url( int _trailing ) -{ - return m_fileitemURL.url( _trailing ); -} - diff --git a/konqueror/listview/konq_treeviewitem.cpp b/konqueror/listview/konq_treeviewitem.cpp new file mode 100644 index 000000000..12953c401 --- /dev/null +++ b/konqueror/listview/konq_treeviewitem.cpp @@ -0,0 +1,101 @@ +/* This file is part of the KDE project + Copyright (C) 1998, 1999 Torben Weis + 2001, 2002, 2004 Michael Brade + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "konq_treeviewwidget.h" +#include "konq_listview.h" + + +KonqListViewDir::KonqListViewDir( KonqTreeViewWidget *_parent, KFileItem* _fileitem ) + : KonqListViewItem( _parent, _fileitem ) +{ + setExpandable( true ); + m_bComplete = false; +} + +KonqListViewDir::KonqListViewDir( KonqTreeViewWidget *_treeview, KonqListViewDir *_parent, KFileItem *_fileitem ) + : KonqListViewItem( _treeview, _parent, _fileitem ) +{ + setExpandable( true ); + m_bComplete = false; +} + +void KonqListViewDir::setOpen( bool _open ) +{ + open( _open, false ); +} + +void KonqListViewDir::open( bool _open, bool _reload ) +{ + if ( _open != isOpen() || _reload ) + { + KonqTreeViewWidget *treeView = static_cast(m_pListViewWidget); + + if ( _open ) + { + if ( !m_bComplete || _reload ) // complete it before opening + treeView->openSubFolder( this, _reload ); + else + { + // we need to add the items to the counts for the statusbar + KFileItemList lst; + lst.setAutoDelete( false ); + + TQListViewItem* it = firstChild(); + while ( it ) + { + lst.append( static_cast(it)->item() ); + it = it->nextSibling(); + } + + // tell the view about the new items to count + treeView->m_pBrowserView->newItems( lst ); + } + } + else + { + treeView->stopListingSubFolder( this ); + + TQListViewItem* it = firstChild(); + while ( it ) + { + // unselect the items in the closed folder + treeView->setSelected( it, false ); + // delete the item from the counts for the statusbar + KFileItem* item = static_cast(it)->item(); + treeView->m_pBrowserView->deleteItem( item ); + it = it->nextSibling(); + } + } + + TQListViewItem::setOpen( _open ); + treeView->slotOnViewport(); + } +} + +KURL KonqListViewDir::kurl() +{ + return m_fileitemURL; +} + +TQString KonqListViewDir::url( int _trailing ) +{ + return m_fileitemURL.url( _trailing ); +} + diff --git a/konqueror/listview/konq_treeviewwidget.cc b/konqueror/listview/konq_treeviewwidget.cc deleted file mode 100644 index 77adc4b61..000000000 --- a/konqueror/listview/konq_treeviewwidget.cc +++ /dev/null @@ -1,307 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 1998, 1999 Torben Weis - 2001, 2002, 2004 Michael Brade - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "konq_listview.h" -#include "konq_treeviewwidget.h" - -#include -#include - -template class TQDict; - - -KonqTreeViewWidget::KonqTreeViewWidget( KonqListView *parent, TQWidget *parentWidget) - : KonqBaseListViewWidget( parent, parentWidget ) -{ - kdDebug(1202) << "+KonqTreeViewWidget" << endl; - - setRootIsDecorated( true ); - setTreeStepSize( 20 ); - - connect( m_dirLister, TQT_SIGNAL( completed( const KURL & ) ), - this, TQT_SLOT( slotCompleted( const KURL & ) ) ); - connect( m_dirLister, TQT_SIGNAL( clear( const KURL & ) ), - this, TQT_SLOT( slotClear( const KURL & ) ) ); - connect( m_dirLister, TQT_SIGNAL( redirection( const KURL &, const KURL & ) ), - this, TQT_SLOT( slotRedirection( const KURL &, const KURL & ) ) ); -} - -KonqTreeViewWidget::~KonqTreeViewWidget() -{ - kdDebug(1202) << "-KonqTreeViewWidget" << endl; - - // Remove all items - clear(); - // Clear dict - m_dictSubDirs.clear(); -} - -bool KonqTreeViewWidget::openURL( const KURL &url ) -{ - //kdDebug(1202) << k_funcinfo << url.prettyURL() << endl; - - if ( m_pBrowserView->extension()->urlArgs().reload ) - { - TQDictIterator it( m_dictSubDirs ); - for (; it.current(); ++it ) - if ( it.current()->isOpen() ) - m_urlsToReload.append( it.current()->url( -1 ) ); - - // Someone could press reload while the listing is still in progess - // -> move the items that are not opened yet to m_urlsToReload. - // We don't need to check for doubled items since remove() removes - // all occurrences. - m_urlsToReload += m_urlsToOpen; - m_urlsToOpen.clear(); - } - - return KonqBaseListViewWidget::openURL( url ); -} - -void KonqTreeViewWidget::saveState( TQDataStream &stream ) -{ - TQStringList openDirList; - - TQDictIterator it( m_dictSubDirs ); - for (; it.current(); ++it ) - { - if ( it.current()->isOpen() ) - openDirList.append( it.current()->url( -1 ) ); - } - - stream << openDirList; - KonqBaseListViewWidget::saveState( stream ); -} - -void KonqTreeViewWidget::restoreState( TQDataStream &stream ) -{ - stream >> m_urlsToOpen; - KonqBaseListViewWidget::restoreState( stream ); -} - -void KonqTreeViewWidget::slotCompleted() -{ - // This is necessary because after reloading it could happen that a - // previously opened subdirectory was deleted and this would still - // be queued for opening. - m_urlsToReload.clear(); - m_urlsToOpen.clear(); - - KonqBaseListViewWidget::slotCompleted(); -} - -void KonqTreeViewWidget::slotCompleted( const KURL & _url ) -{ - // do nothing if the view itself is finished - if ( m_url.equals( _url, true ) ) - return; - - KonqListViewDir *dir = m_dictSubDirs[ _url.url(-1) ]; - if ( dir ) - dir->setComplete( true ); - else - kdWarning() << "KonqTreeViewWidget::slotCompleted : dir " << _url.url(-1) << " not found in dict!" << endl; - - if ( !viewport()->isUpdatesEnabled() ) - { - viewport()->setUpdatesEnabled( true ); - setUpdatesEnabled( true ); - triggerUpdate(); - } -} - -void KonqTreeViewWidget::slotClear() -{ - kdDebug(1202) << k_funcinfo << endl; - - m_dictSubDirs.clear(); - KonqBaseListViewWidget::slotClear(); -} - -void KonqTreeViewWidget::slotClear( const KURL & _url ) -{ - // normally this means we have to delete only the contents of directory _url - // but we are allowed to delete the subdirs as well since the opening of - // subdirs happens level per level. If a subdir is deleted with delete, all - // its children will be deleted by Qt immediately! - - kdDebug(1202) << k_funcinfo << _url << endl; - - KonqListViewDir *item = m_dictSubDirs[_url.url(-1)]; - if ( item ) - { - // search all subdirs of _url (item) - TQDictIterator it( m_dictSubDirs ); - while ( it.current() ) - { - if ( !_url.equals( it.currentKey(), true ) - && _url.isParentOf( it.currentKey() ) ) - { - m_urlsToOpen.remove( it.currentKey() ); - m_urlsToReload.remove( it.currentKey() ); - m_dictSubDirs.remove( it.currentKey() ); // do last, it changes it.currentKey()!! - } - else - ++it; - } - - // Remark: This code works only if we have exactly one tree which is the - // case for Konqy's treeview. It will break if m_dictSubDirs contains two - // subdirectories where only one of them will have its items deleted by - // the following code. - - // delete all child items, their fileitems are no longer valid - TQListViewItem *child; - while ( (child = item->firstChild()) ) - delete child; - - // only if we really deleted something update the statusbar - reportItemCounts(); - } -} - -void KonqTreeViewWidget::slotRedirection( const KURL &oldUrl, const KURL &newUrl ) -{ - kdDebug(1202) << k_funcinfo << oldUrl.url() << " -> " << newUrl.url() << endl; - - KonqListViewDir *dir = m_dictSubDirs.take( oldUrl.url(-1) ); - Q_ASSERT( dir ); - m_dictSubDirs.insert( newUrl.url(-1), dir ); - // TODO: do we need to rename the fileitem in dir as well? -} - -void KonqTreeViewWidget::slotNewItems( const KFileItemList &entries ) -{ - if (!entries.count()) - return; - // Find parent item - it's the same for all the items - TQPtrListIterator kit( entries ); - KURL dir( (*kit)->url().upURL() ); - - KonqListViewDir *parentDir = 0L; - if ( !m_url.equals( dir, true ) ) // ignore trailing slash - parentDir = m_dictSubDirs[ dir.url(-1) ]; - - if ( !parentDir ) // hack for zeroconf://domain/type/service listed in zeroconf:/type/ dir - { - dir.setHost( TQString::null ); - parentDir = m_dictSubDirs[ dir.url(-1) ]; - } - - for ( ; kit.current(); ++kit ) - { - KonqListViewDir *dirItem = 0; - KonqListViewItem *fileItem = 0; - - if ( parentDir ) // adding under a directory item - { - if ( (*kit)->isDir() ) - { - dirItem = new KonqListViewDir( this, parentDir, *kit ); - m_dictSubDirs.insert( (*kit)->url().url(-1), dirItem ); - } - else - fileItem = new KonqListViewItem( this, parentDir, *kit ); - } - else // adding on the toplevel - { - if ( (*kit)->isDir() ) - { - dirItem = new KonqListViewDir( this, *kit ); - m_dictSubDirs.insert( (*kit)->url().url(-1), dirItem ); - } - else - fileItem = new KonqListViewItem( this, *kit ); - } - - if ( !m_itemFound ) - { - if ( fileItem && fileItem->text(0) == m_itemToGoTo ) - { - setCurrentItem( fileItem ); - m_itemFound = true; - } - else if ( dirItem && dirItem->text(0) == m_itemToGoTo ) - { - setCurrentItem( dirItem ); - m_itemFound = true; - } - } - - if ( !m_itemsToSelect.isEmpty() ) { - TQStringList::Iterator tsit = m_itemsToSelect.find( (*kit)->name() ); - if ( tsit != m_itemsToSelect.end() ) { - m_itemsToSelect.remove( tsit ); - setSelected( fileItem ? fileItem : dirItem, true ); - } - } - - if ( fileItem && !(*kit)->isMimeTypeKnown() ) - m_pBrowserView->lstPendingMimeIconItems().append( fileItem ); - - if ( dirItem ) - { - TQString u = (*kit)->url().url( 0 ); - if ( m_urlsToOpen.remove( u ) ) - dirItem->open( true, false ); - else if ( m_urlsToReload.remove( u ) ) - dirItem->open( true, true ); - } - } - - if ( !viewport()->isUpdatesEnabled() ) - { - viewport()->setUpdatesEnabled( true ); - setUpdatesEnabled( true ); - triggerUpdate(); - } - - // counts for the statusbar - m_pBrowserView->newItems( entries ); - slotUpdateBackground(); -} - -void KonqTreeViewWidget::slotDeleteItem( KFileItem *_fileItem ) -{ - TQString url = _fileItem->url().url(-1); - - // Check if this item is in m_dictSubDirs, and if yes, then remove it - slotClear( _fileItem->url() ); - - m_dictSubDirs.remove( url ); - m_urlsToOpen.remove( url ); - m_urlsToReload.remove( url ); - - KonqBaseListViewWidget::slotDeleteItem( _fileItem ); -} - -void KonqTreeViewWidget::openSubFolder( KonqListViewDir* _dir, bool _reload ) -{ - m_dirLister->openURL( _dir->kurl(), true /* keep existing data */, _reload ); - slotUpdateBackground(); -} - -void KonqTreeViewWidget::stopListingSubFolder( KonqListViewDir* _dir ) -{ - m_dirLister->stop( _dir->kurl() ); - slotUpdateBackground(); -} - -#include "konq_treeviewwidget.moc" diff --git a/konqueror/listview/konq_treeviewwidget.cpp b/konqueror/listview/konq_treeviewwidget.cpp new file mode 100644 index 000000000..77adc4b61 --- /dev/null +++ b/konqueror/listview/konq_treeviewwidget.cpp @@ -0,0 +1,307 @@ +/* This file is part of the KDE project + Copyright (C) 1998, 1999 Torben Weis + 2001, 2002, 2004 Michael Brade + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "konq_listview.h" +#include "konq_treeviewwidget.h" + +#include +#include + +template class TQDict; + + +KonqTreeViewWidget::KonqTreeViewWidget( KonqListView *parent, TQWidget *parentWidget) + : KonqBaseListViewWidget( parent, parentWidget ) +{ + kdDebug(1202) << "+KonqTreeViewWidget" << endl; + + setRootIsDecorated( true ); + setTreeStepSize( 20 ); + + connect( m_dirLister, TQT_SIGNAL( completed( const KURL & ) ), + this, TQT_SLOT( slotCompleted( const KURL & ) ) ); + connect( m_dirLister, TQT_SIGNAL( clear( const KURL & ) ), + this, TQT_SLOT( slotClear( const KURL & ) ) ); + connect( m_dirLister, TQT_SIGNAL( redirection( const KURL &, const KURL & ) ), + this, TQT_SLOT( slotRedirection( const KURL &, const KURL & ) ) ); +} + +KonqTreeViewWidget::~KonqTreeViewWidget() +{ + kdDebug(1202) << "-KonqTreeViewWidget" << endl; + + // Remove all items + clear(); + // Clear dict + m_dictSubDirs.clear(); +} + +bool KonqTreeViewWidget::openURL( const KURL &url ) +{ + //kdDebug(1202) << k_funcinfo << url.prettyURL() << endl; + + if ( m_pBrowserView->extension()->urlArgs().reload ) + { + TQDictIterator it( m_dictSubDirs ); + for (; it.current(); ++it ) + if ( it.current()->isOpen() ) + m_urlsToReload.append( it.current()->url( -1 ) ); + + // Someone could press reload while the listing is still in progess + // -> move the items that are not opened yet to m_urlsToReload. + // We don't need to check for doubled items since remove() removes + // all occurrences. + m_urlsToReload += m_urlsToOpen; + m_urlsToOpen.clear(); + } + + return KonqBaseListViewWidget::openURL( url ); +} + +void KonqTreeViewWidget::saveState( TQDataStream &stream ) +{ + TQStringList openDirList; + + TQDictIterator it( m_dictSubDirs ); + for (; it.current(); ++it ) + { + if ( it.current()->isOpen() ) + openDirList.append( it.current()->url( -1 ) ); + } + + stream << openDirList; + KonqBaseListViewWidget::saveState( stream ); +} + +void KonqTreeViewWidget::restoreState( TQDataStream &stream ) +{ + stream >> m_urlsToOpen; + KonqBaseListViewWidget::restoreState( stream ); +} + +void KonqTreeViewWidget::slotCompleted() +{ + // This is necessary because after reloading it could happen that a + // previously opened subdirectory was deleted and this would still + // be queued for opening. + m_urlsToReload.clear(); + m_urlsToOpen.clear(); + + KonqBaseListViewWidget::slotCompleted(); +} + +void KonqTreeViewWidget::slotCompleted( const KURL & _url ) +{ + // do nothing if the view itself is finished + if ( m_url.equals( _url, true ) ) + return; + + KonqListViewDir *dir = m_dictSubDirs[ _url.url(-1) ]; + if ( dir ) + dir->setComplete( true ); + else + kdWarning() << "KonqTreeViewWidget::slotCompleted : dir " << _url.url(-1) << " not found in dict!" << endl; + + if ( !viewport()->isUpdatesEnabled() ) + { + viewport()->setUpdatesEnabled( true ); + setUpdatesEnabled( true ); + triggerUpdate(); + } +} + +void KonqTreeViewWidget::slotClear() +{ + kdDebug(1202) << k_funcinfo << endl; + + m_dictSubDirs.clear(); + KonqBaseListViewWidget::slotClear(); +} + +void KonqTreeViewWidget::slotClear( const KURL & _url ) +{ + // normally this means we have to delete only the contents of directory _url + // but we are allowed to delete the subdirs as well since the opening of + // subdirs happens level per level. If a subdir is deleted with delete, all + // its children will be deleted by Qt immediately! + + kdDebug(1202) << k_funcinfo << _url << endl; + + KonqListViewDir *item = m_dictSubDirs[_url.url(-1)]; + if ( item ) + { + // search all subdirs of _url (item) + TQDictIterator it( m_dictSubDirs ); + while ( it.current() ) + { + if ( !_url.equals( it.currentKey(), true ) + && _url.isParentOf( it.currentKey() ) ) + { + m_urlsToOpen.remove( it.currentKey() ); + m_urlsToReload.remove( it.currentKey() ); + m_dictSubDirs.remove( it.currentKey() ); // do last, it changes it.currentKey()!! + } + else + ++it; + } + + // Remark: This code works only if we have exactly one tree which is the + // case for Konqy's treeview. It will break if m_dictSubDirs contains two + // subdirectories where only one of them will have its items deleted by + // the following code. + + // delete all child items, their fileitems are no longer valid + TQListViewItem *child; + while ( (child = item->firstChild()) ) + delete child; + + // only if we really deleted something update the statusbar + reportItemCounts(); + } +} + +void KonqTreeViewWidget::slotRedirection( const KURL &oldUrl, const KURL &newUrl ) +{ + kdDebug(1202) << k_funcinfo << oldUrl.url() << " -> " << newUrl.url() << endl; + + KonqListViewDir *dir = m_dictSubDirs.take( oldUrl.url(-1) ); + Q_ASSERT( dir ); + m_dictSubDirs.insert( newUrl.url(-1), dir ); + // TODO: do we need to rename the fileitem in dir as well? +} + +void KonqTreeViewWidget::slotNewItems( const KFileItemList &entries ) +{ + if (!entries.count()) + return; + // Find parent item - it's the same for all the items + TQPtrListIterator kit( entries ); + KURL dir( (*kit)->url().upURL() ); + + KonqListViewDir *parentDir = 0L; + if ( !m_url.equals( dir, true ) ) // ignore trailing slash + parentDir = m_dictSubDirs[ dir.url(-1) ]; + + if ( !parentDir ) // hack for zeroconf://domain/type/service listed in zeroconf:/type/ dir + { + dir.setHost( TQString::null ); + parentDir = m_dictSubDirs[ dir.url(-1) ]; + } + + for ( ; kit.current(); ++kit ) + { + KonqListViewDir *dirItem = 0; + KonqListViewItem *fileItem = 0; + + if ( parentDir ) // adding under a directory item + { + if ( (*kit)->isDir() ) + { + dirItem = new KonqListViewDir( this, parentDir, *kit ); + m_dictSubDirs.insert( (*kit)->url().url(-1), dirItem ); + } + else + fileItem = new KonqListViewItem( this, parentDir, *kit ); + } + else // adding on the toplevel + { + if ( (*kit)->isDir() ) + { + dirItem = new KonqListViewDir( this, *kit ); + m_dictSubDirs.insert( (*kit)->url().url(-1), dirItem ); + } + else + fileItem = new KonqListViewItem( this, *kit ); + } + + if ( !m_itemFound ) + { + if ( fileItem && fileItem->text(0) == m_itemToGoTo ) + { + setCurrentItem( fileItem ); + m_itemFound = true; + } + else if ( dirItem && dirItem->text(0) == m_itemToGoTo ) + { + setCurrentItem( dirItem ); + m_itemFound = true; + } + } + + if ( !m_itemsToSelect.isEmpty() ) { + TQStringList::Iterator tsit = m_itemsToSelect.find( (*kit)->name() ); + if ( tsit != m_itemsToSelect.end() ) { + m_itemsToSelect.remove( tsit ); + setSelected( fileItem ? fileItem : dirItem, true ); + } + } + + if ( fileItem && !(*kit)->isMimeTypeKnown() ) + m_pBrowserView->lstPendingMimeIconItems().append( fileItem ); + + if ( dirItem ) + { + TQString u = (*kit)->url().url( 0 ); + if ( m_urlsToOpen.remove( u ) ) + dirItem->open( true, false ); + else if ( m_urlsToReload.remove( u ) ) + dirItem->open( true, true ); + } + } + + if ( !viewport()->isUpdatesEnabled() ) + { + viewport()->setUpdatesEnabled( true ); + setUpdatesEnabled( true ); + triggerUpdate(); + } + + // counts for the statusbar + m_pBrowserView->newItems( entries ); + slotUpdateBackground(); +} + +void KonqTreeViewWidget::slotDeleteItem( KFileItem *_fileItem ) +{ + TQString url = _fileItem->url().url(-1); + + // Check if this item is in m_dictSubDirs, and if yes, then remove it + slotClear( _fileItem->url() ); + + m_dictSubDirs.remove( url ); + m_urlsToOpen.remove( url ); + m_urlsToReload.remove( url ); + + KonqBaseListViewWidget::slotDeleteItem( _fileItem ); +} + +void KonqTreeViewWidget::openSubFolder( KonqListViewDir* _dir, bool _reload ) +{ + m_dirLister->openURL( _dir->kurl(), true /* keep existing data */, _reload ); + slotUpdateBackground(); +} + +void KonqTreeViewWidget::stopListingSubFolder( KonqListViewDir* _dir ) +{ + m_dirLister->stop( _dir->kurl() ); + slotUpdateBackground(); +} + +#include "konq_treeviewwidget.moc" diff --git a/konqueror/preloader/CMakeLists.txt b/konqueror/preloader/CMakeLists.txt index 90e72194b..f5610a0ae 100644 --- a/konqueror/preloader/CMakeLists.txt +++ b/konqueror/preloader/CMakeLists.txt @@ -42,7 +42,7 @@ tde_create_translated_desktop( set( target kded_konqy_preloader ) set( ${target}_SRCS - preloader.cc preloader.skel + preloader.cpp preloader.skel ) tde_add_kpart( ${target} AUTOMOC diff --git a/konqueror/preloader/Makefile.am b/konqueror/preloader/Makefile.am index ff2440b0d..9c446faa8 100644 --- a/konqueror/preloader/Makefile.am +++ b/konqueror/preloader/Makefile.am @@ -3,7 +3,7 @@ AM_CPPFLAGS = -DTQT_NO_CAST_ASCII kde_module_LTLIBRARIES = kded_konqy_preloader.la INCLUDES= -I.. $(all_includes) -kded_konqy_preloader_la_SOURCES = preloader.cc preloader.skel +kded_konqy_preloader_la_SOURCES = preloader.cpp preloader.skel kded_konqy_preloader_la_LDFLAGS = $(all_libraries) -module -avoid-version kded_konqy_preloader_la_LIBADD = ../libkonqueror_intern.la $(LIB_TDESYCOCA) $(LIB_TDECORE) diff --git a/konqueror/preloader/configure.in.in b/konqueror/preloader/configure.in.in index 315b23c97..a581917cb 100644 --- a/konqueror/preloader/configure.in.in +++ b/konqueror/preloader/configure.in.in @@ -1,5 +1,5 @@ dnl check whether mallinfo() is available and which fields to use to find out memory usage -dnl it's used in konq_mainwindow.cc +dnl it's used in konq_mainwindow.cpp dnl warning, ugly code ahead dnl some implementations have mallinfo() in stdlib.h, others in malloc.h dnl fields showing memory usage should be hblkhd, uordblks and usmblks, diff --git a/konqueror/preloader/preloader.cc b/konqueror/preloader/preloader.cc deleted file mode 100644 index 5d87a8b07..000000000 --- a/konqueror/preloader/preloader.cc +++ /dev/null @@ -1,151 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2002 Lubos Lunak - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "preloader.h" -#include "konq_settingsxt.h" - -#include -#include -#include -#include -#include - -KonqyPreloader::KonqyPreloader( const TQCString& obj ) - : KDEDModule( obj ) - { - reconfigure(); - connect( kapp->dcopClient(), TQT_SIGNAL( applicationRemoved( const TQCString& )), - TQT_SLOT( appRemoved( const TQCString& ))); - connect( &check_always_preloaded_timer, TQT_SIGNAL( timeout()), - TQT_SLOT( checkAlwaysPreloaded())); - } - -KonqyPreloader::~KonqyPreloader() - { - updateCount(); - } - -bool KonqyPreloader::registerPreloadedKonqy( TQCString id, int screen ) - { - if( instances.count() >= (uint)KonqSettings::maxPreloadCount() ) - return false; - instances.append( KonqyData( id, screen )); - return true; - } - -TQCString KonqyPreloader::getPreloadedKonqy( int screen ) - { - if( instances.count() == 0 ) - return ""; - for( InstancesList::Iterator it = instances.begin(); - it != instances.end(); - ++it ) - { - if( (*it).screen == screen ) - { - TQCString ret = (*it).id; - instances.remove( it ); - check_always_preloaded_timer.start( 5000, true ); - return ret; - } - } - return ""; - } - -void KonqyPreloader::unregisterPreloadedKonqy( TQCString id_P ) - { - for( InstancesList::Iterator it = instances.begin(); - it != instances.end(); - ++it ) - if( (*it).id == id_P ) - { - instances.remove( it ); - return; - } - } - -void KonqyPreloader::appRemoved( const TQCString& id ) - { - unregisterPreloadedKonqy( id ); - } - -void KonqyPreloader::reconfigure() - { - KonqSettings::self()->readConfig(); - updateCount(); - // Ignore "PreloadOnStartup" here, it's used by the .desktop file - // in the autostart folder, which will do 'konqueror --preload' in autostart - // phase 2. This will also cause activation of this kded module. - } - -void KonqyPreloader::updateCount() - { - while( instances.count() > (uint)KonqSettings::maxPreloadCount() ) - { - KonqyData konqy = instances.first(); - instances.pop_front(); - DCOPRef ref( konqy.id, "KonquerorIface" ); - ref.send( "terminatePreloaded" ); - } - if( KonqSettings::alwaysHavePreloaded() && - KonqSettings::maxPreloadCount() > 0 && - instances.count() == 0 ) - { - if( !check_always_preloaded_timer.isActive()) - { - if( kapp->tdeinitExec( TQString::fromLatin1( "konqueror" ), - TQStringList() << TQString::fromLatin1( "--preload" ), NULL, NULL, "0" ) == 0 ) - { - kdDebug( 1202 ) << "Preloading Konqueror instance" << endl; - check_always_preloaded_timer.start( 5000, true ); - } - // else do nothing, the launching failed - } - } - } - -// have 5s interval between attempts to preload a new konqy -// in order not to start many of them at the same time -void KonqyPreloader::checkAlwaysPreloaded() - { - // TODO here should be detection whether the system is too busy, - // and delaying preloading another konqy in such case - // but I have no idea how to do it - updateCount(); - } - -void KonqyPreloader::unloadAllPreloaded() - { - while( instances.count() > 0 ) - { - KonqyData konqy = instances.first(); - instances.pop_front(); - DCOPRef ref( konqy.id, "KonquerorIface" ); - ref.send( "terminatePreloaded" ); - } - // ignore 'always_have_preloaded' here - } - -extern "C" -KDE_EXPORT KDEDModule *create_konqy_preloader( const TQCString& obj ) - { - return new KonqyPreloader( obj ); - } - -#include "preloader.moc" diff --git a/konqueror/preloader/preloader.cpp b/konqueror/preloader/preloader.cpp new file mode 100644 index 000000000..5d87a8b07 --- /dev/null +++ b/konqueror/preloader/preloader.cpp @@ -0,0 +1,151 @@ +/* This file is part of the KDE project + Copyright (C) 2002 Lubos Lunak + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "preloader.h" +#include "konq_settingsxt.h" + +#include +#include +#include +#include +#include + +KonqyPreloader::KonqyPreloader( const TQCString& obj ) + : KDEDModule( obj ) + { + reconfigure(); + connect( kapp->dcopClient(), TQT_SIGNAL( applicationRemoved( const TQCString& )), + TQT_SLOT( appRemoved( const TQCString& ))); + connect( &check_always_preloaded_timer, TQT_SIGNAL( timeout()), + TQT_SLOT( checkAlwaysPreloaded())); + } + +KonqyPreloader::~KonqyPreloader() + { + updateCount(); + } + +bool KonqyPreloader::registerPreloadedKonqy( TQCString id, int screen ) + { + if( instances.count() >= (uint)KonqSettings::maxPreloadCount() ) + return false; + instances.append( KonqyData( id, screen )); + return true; + } + +TQCString KonqyPreloader::getPreloadedKonqy( int screen ) + { + if( instances.count() == 0 ) + return ""; + for( InstancesList::Iterator it = instances.begin(); + it != instances.end(); + ++it ) + { + if( (*it).screen == screen ) + { + TQCString ret = (*it).id; + instances.remove( it ); + check_always_preloaded_timer.start( 5000, true ); + return ret; + } + } + return ""; + } + +void KonqyPreloader::unregisterPreloadedKonqy( TQCString id_P ) + { + for( InstancesList::Iterator it = instances.begin(); + it != instances.end(); + ++it ) + if( (*it).id == id_P ) + { + instances.remove( it ); + return; + } + } + +void KonqyPreloader::appRemoved( const TQCString& id ) + { + unregisterPreloadedKonqy( id ); + } + +void KonqyPreloader::reconfigure() + { + KonqSettings::self()->readConfig(); + updateCount(); + // Ignore "PreloadOnStartup" here, it's used by the .desktop file + // in the autostart folder, which will do 'konqueror --preload' in autostart + // phase 2. This will also cause activation of this kded module. + } + +void KonqyPreloader::updateCount() + { + while( instances.count() > (uint)KonqSettings::maxPreloadCount() ) + { + KonqyData konqy = instances.first(); + instances.pop_front(); + DCOPRef ref( konqy.id, "KonquerorIface" ); + ref.send( "terminatePreloaded" ); + } + if( KonqSettings::alwaysHavePreloaded() && + KonqSettings::maxPreloadCount() > 0 && + instances.count() == 0 ) + { + if( !check_always_preloaded_timer.isActive()) + { + if( kapp->tdeinitExec( TQString::fromLatin1( "konqueror" ), + TQStringList() << TQString::fromLatin1( "--preload" ), NULL, NULL, "0" ) == 0 ) + { + kdDebug( 1202 ) << "Preloading Konqueror instance" << endl; + check_always_preloaded_timer.start( 5000, true ); + } + // else do nothing, the launching failed + } + } + } + +// have 5s interval between attempts to preload a new konqy +// in order not to start many of them at the same time +void KonqyPreloader::checkAlwaysPreloaded() + { + // TODO here should be detection whether the system is too busy, + // and delaying preloading another konqy in such case + // but I have no idea how to do it + updateCount(); + } + +void KonqyPreloader::unloadAllPreloaded() + { + while( instances.count() > 0 ) + { + KonqyData konqy = instances.first(); + instances.pop_front(); + DCOPRef ref( konqy.id, "KonquerorIface" ); + ref.send( "terminatePreloaded" ); + } + // ignore 'always_have_preloaded' here + } + +extern "C" +KDE_EXPORT KDEDModule *create_konqy_preloader( const TQCString& obj ) + { + return new KonqyPreloader( obj ); + } + +#include "preloader.moc" -- cgit v1.2.1