/***************************************************************************
 *   Copyright (C) 2005 by Nicolas Ternisien                               *
 *   nicolas.ternisien@gmail.com                                           *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) 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.             *
 ***************************************************************************/


//TQt includes
#include <tqdragobject.h>

#include <tqpixmap.h>
#include <tqpainter.h>
#include <tqpaintdevicemetrics.h>
#include <tqwhatsthis.h>
#include <tqtooltip.h>

#include <tqlistview.h>


//KDE includes
#include <tdemessagebox.h>

#include <twin.h>
#include <kprinter.h>
#include <tdeglobal.h>
#include <tdelocale.h>

#include <kiconloader.h>

#include <kservice.h>

#include <tdemenubar.h>
#include <kstatusbar.h>
#include <kkeydialog.h>

#include <tdefiledialog.h>

#include <tdeaccel.h>

#include <tdeconfig.h>

//For compatibility with old versions of KDE

#include <dcopclient.h>

#include <kurl.h>
#include <kurldrag.h>
#include <kurlrequesterdlg.h>
#include <tdetoolbarbutton.h>
#include <kedittoolbar.h>
#include <kdebug.h>
#include <kiconloader.h>

#include <tdestdaccel.h>
#include <tdeaction.h>
#include <kstdaction.h>

//Project includes
#include "ksystemlog.h"

#include "ksystemlogConfig.h"

#include "options.h"

#include "loggerDialog.h"

#include "logListItem.h"
#include "logLevel.h"
#include "logFile.h"

#include "readerFactory.h"

KSystemLog::KSystemLog() :
	TDEMainWindow(0, "ksystemlog"),
	printer(NULL),
	detailDialog(NULL),
	loadingDialog(NULL),
	tabs(NULL)
	{

	//Accept Drag and Drop
	setAcceptDrops(true);
	
	//Initialize the Status Bar
	setupStatusBar();
		
	//Initialize the find manager
	findManager=new FindManager(this, "find_manager");

	//Setup existing log levels
	Globals::setupLogLevels();
	
	//Setup existing log modes
	Globals::setupLogModes();
	
	//Setup the Actions
	setupActions();

	//Create the GUI from XML configuration
	createGUI();

	//Setup the main tab bar
	setupTabBar();
		
	//TabBar widget becomes the central place of the TDEMainWindow
	setCentralWidget(tabs);

	//Setup the Progress Bar Dialog
	setupProgressDialog();
	
	//Apply the saved mainwindow settings, if any, and ask the mainwindow
	//to automatically save settings if changed: window size, toolbar
	//position, icon size, etc.
	setAutoSaveSettings();
	
	//TODO Try to find an improvement of this _big_ hack
	//Set its default size, the first time KSystemLog is loaded
	if (!initialGeometrySet())
		resize(790,590);
	
	//Show before reading the config because users can think that KSystemLog 
	//have not been launched if it takes too long time to start.
	show();
	
	// Apply the create the main window and ask the mainwindow to
	// automatically save settings if changed: window size, toolbar
	// position, icon size, etc.  Also to add actions for the statusbar
	// toolbar, and keybindings if necessary.
	setupGUI();

	//Read the configuration and display each tab saved
	readConfig();
	
}

void KSystemLog::setupTabBar() {
	tabs=new KTabWidget(this, "tabs");
	
	connect(tabs, TQ_SIGNAL(currentChanged(TQWidget*)), this, TQ_SLOT(currentTabChanged(TQWidget*)));
	
	TQPushButton* tabNewTabButton=new TQPushButton(SmallIcon("tab_new"), "", tabs);	
	connect(tabNewTabButton, TQ_SIGNAL(clicked()), this, TQ_SLOT(newTab()));
	
	TQToolTip::add(tabNewTabButton, i18n("Create a new tab"));
	TQWhatsThis::add(tabNewTabButton, i18n("Creates a new tab which can display another log."));
	
	TQPushButton* tabCloseTabButton=new TQPushButton(SmallIcon("tab_remove"), "", tabs);
	connect(tabCloseTabButton, TQ_SIGNAL(clicked()), this, TQ_SLOT(closeTab()));
	
	TQToolTip::add(tabCloseTabButton, i18n("Close the current tab"));
	TQWhatsThis::add(tabCloseTabButton, i18n("Closes the current tab."));
	
	tabs->setCornerWidget(tabNewTabButton, TQt::TopLeft);
	tabs->setCornerWidget(tabCloseTabButton, TQt::TopRight);
	
}

KSystemLog::~KSystemLog() {
	//Save config here until a better solution is found
	saveConfig();
	
	if (detailDialog!=NULL)
		delete detailDialog;

	if (loadingDialog!=NULL)
		delete loadingDialog;
		
	if (slotLogAction!=NULL)
		delete slotLogAction;
	
}



LogManager* KSystemLog::activeLogManager() {
	if (tabs==NULL) {
		kdDebug() << "Call to tabs widget which is not initialized" << endl;
		return(NULL);
	}
		
	View* currentView=static_cast<View*> (tabs->currentPage());
	
	TQPtrListIterator<LogManager> it(logManagers);
	
	LogManager* manager=it.current();
	while(manager!=NULL) {
		
		if (manager->getView()==currentView) {
			return(manager);
		}
		
		++it;
		manager=it.current();
	}
	
	
	//Normally it's an impossible case (I hope... ;-)
	kdDebug() << "No active log manager found" << endl;
	return(NULL);
}


void KSystemLog::currentTabChanged(TQWidget* /*widget*/) {
	kdDebug() << "Tab has changed" << endl;
	
	LogManager* currentManager=activeLogManager();
	
	//If the tab changed, we suppose that the selection changes too
	slotSelectionChanged();
	
	//Update the status bar
	updateStatusBar();
	
	//Update the Group By menu
	updateGroupBy();
	
	//Management of Resume and Pause actions
	if (currentManager->isParsingPaused()) {
		pauseParsingAction->setEnabled(false);
		resumeParsingAction->setEnabled(true);
	}
	else {
		pauseParsingAction->setEnabled(true);
		resumeParsingAction->setEnabled(false);
	}
	

	//Change the title of the window
	changeCaption(currentManager->getLogMode()->name);
	
	//If the tab name has been change, regive it its old name
	changeTab(currentManager->getView(), currentManager->getLogMode()->name);
	
	//Modify the menu button to help the user know what is the currently log mode
	//setModeToAction(currentManager->getLogMode(), true);
	TDEToggleAction* action=getCorrespondingLogAction(currentManager->getLogMode());
	if (action!=NULL)
		action->setChecked(true);
	
	setCurrentLogManager(currentManager);

	
	if (detailDialog!=NULL) {
		detailDialog->setView(currentManager->getView());
	}
	
}


void KSystemLog::setupStatusBar() {
	statusBar()->insertItem("", STATUS_BAR_LINE_COUNT, 0, true);
	statusBar()->insertItem("", STATUS_BAR_LAST_MODIFICATION, 0, true);
	
	//Displays the Status Bar
	statusBar()->show();
}

void KSystemLog::setupActions() {

	KStdAction::open(this, TQ_SLOT(fileOpen()), actionCollection(), "file_open");
	actionCollection()->action("file_open")->setToolTip(i18n("Open a file in KSystemLog"));
	actionCollection()->action("file_open")->setWhatsThis(i18n("Opens a file in KSystemLog and displays its content in the current tab."));	
	
	//TODO Not used for the moment
	//KStdAction::print(this, TQ_SLOT(filePrint()), actionCollection());
	
	saveAction=KStdAction::saveAs(this, NULL, actionCollection(), "file_save");
	//TODO Retrieve the system's shortcut of the save action (and not Save as...)
	saveAction->setShortcut(CTRL+Key_S);
	saveAction->setToolTip(i18n("Save the selection to a file"));
	saveAction->setWhatsThis(i18n("Saves the selection to a file. This action is useful if you want to create an attachment or a backup of a particular log."));	
	saveAction->setEnabled(false);
	
	KStdAction::quit(this, TQ_SLOT(quit()), actionCollection(), "file_quit");
	actionCollection()->action("file_quit")->setToolTip(i18n("Quit KSystemLog"));
	actionCollection()->action("file_quit")->setWhatsThis(i18n("Quits KSystemLog."));	
	
	copyAction=KStdAction::copy(this, NULL, actionCollection(), "copy");
	copyAction->setToolTip(i18n("Copy the selection to the clipboard"));
	copyAction->setWhatsThis(i18n("Copies the selection to the clipboard. This action is useful if you want to paste the selection in a chat or an email."));	
	copyAction->setEnabled(false);
	
	expandAllAction=new TDEAction(i18n("Ex&pand All"), NULL, CTRL+Key_X, this, NULL, actionCollection(), "expand_all" );
	expandAllAction->setToolTip(i18n("Expand all categories"));
	expandAllAction->setWhatsThis(i18n("<qt>This action opens all main categories. This is enabled only if an option has been selected in the <b>Group By</b> menu.</qt>"));
	expandAllAction->setEnabled(false);
	
	collapseAllAction=new TDEAction(i18n("Col&lapse All"), NULL, CTRL+Key_L, this, NULL, actionCollection(), "collapse_all" );
	collapseAllAction->setToolTip(i18n("Collapse all categories"));
	collapseAllAction->setWhatsThis(i18n("<qt>This action closes all main categories. This is enabled only if an option has been selected in the <b>Group By</b> menu.</qt>"));
	collapseAllAction->setEnabled(false);
	
	sendMailAction=new TDEAction(i18n("&Email Selection..."), "mail_generic", CTRL+Key_M, this, NULL, actionCollection(), "send_mail" );
	sendMailAction->setToolTip(i18n("Send the selection by mail"));
	sendMailAction->setWhatsThis(i18n("Sends the selection by mail. Simply select the important lines and click on this menu entry to send the selection to a friend or a mailing list."));	
	sendMailAction->setEnabled(false);
	
	logMessageAction=new TDEAction(i18n("&Send Message..."), "document-new", CTRL+Key_L, this, TQ_SLOT(slotLogMessage()), actionCollection(), "log_message" );
	logMessageAction->setToolTip(i18n("Send a message to the log system"));
	logMessageAction->setWhatsThis(i18n("This action will open a dialog which lets you send a message to the log system."));
	
	KStdAction::selectAll(this, TQ_SLOT(slotSelectAll()), actionCollection(), "select_all");
	actionCollection()->action("select_all")->setToolTip(i18n("Select all lines of the current log"));
	actionCollection()->action("select_all")->setWhatsThis(i18n("Selects all lines of the current log. This action is useful if you want, for example, to save all the content of the current log in a file."));
	
	KStdAction::find(findManager, TQ_SLOT(slotFind()), actionCollection(), "find");
	KStdAction::findNext(findManager, TQ_SLOT(slotFindNext()), actionCollection(), "find_next");

	//TODO Find a solution to display at the right place this action (see Akregator interface)
	filterBarAction=new TDEToggleAction(i18n("Show &Filter Bar"), TQString(), 0, this, TQ_SLOT(slotToggleFilterBar()), actionCollection(), "toggle_filter_bar");
	filterBarAction->setEnabled(true);

	KStdAction::preferences(this, TQ_SLOT(slotOptions()), actionCollection());
	
	newTabAction=new TDEAction(i18n("&New Tab"), "tab_new", CTRL+Key_T, this, TQ_SLOT(newTab()), actionCollection(), "new_tab" );
	newTabAction->setToolTip(i18n("Create a new tab"));
	newTabAction->setWhatsThis(i18n("Creates a new tab which can display another log."));
	
	closeTabAction=new TDEAction(i18n("&Close Tab"), "tab_remove", CTRL+Key_W, this, TQ_SLOT(closeTab()), actionCollection(), "close_tab" );
	closeTabAction->setToolTip(i18n("Close the current tab"));
	closeTabAction->setWhatsThis(i18n("Closes the current tab."));
	
	duplicateTabAction=new TDEAction(i18n("&Duplicate Tab"), "tab_duplicate", SHIFT+CTRL+Key_N, this, TQ_SLOT(duplicateTab()), actionCollection(), "duplicate_tab" );
	duplicateTabAction->setToolTip(i18n("Duplicate the current tab"));
	duplicateTabAction->setWhatsThis(i18n("Duplicates the current tab."));
	
	moveTabLeftAction=new TDEAction(i18n("Move Tab &Left"), "1leftarrow", SHIFT+CTRL+Key_Left, this, TQ_SLOT(moveTabLeft()), actionCollection(), "move_tab_left" );
	moveTabLeftAction->setToolTip(i18n("Move the current tab to the left"));
	moveTabLeftAction->setWhatsThis(i18n("Moves the current tab to the left."));
	
	moveTabRightAction=new TDEAction(i18n("Move Tab &Right"), "1rightarrow", SHIFT+CTRL+Key_Right, this, TQ_SLOT(moveTabRight()), actionCollection(), "move_tab_right" );
	moveTabRightAction->setToolTip(i18n("Move the current tab to the right"));
	moveTabRightAction->setWhatsThis(i18n("Moves the current tab to the right."));
	
	
	reloadAction=new TDEAction(i18n("&Reload"), "reload", Key_F5, this, TQ_SLOT(reloadCurrent()), actionCollection(), "reload" );
	reloadAction->setToolTip(i18n("Reload the current log"));
	reloadAction->setWhatsThis(i18n("Reloads the current log, if you want to be sure that the view is correctly updated."));
	
	resumeParsingAction=new TDEAction(i18n("Resu&me Parsing"), "media-playback-start", CTRL+Key_M, this, TQ_SLOT(resumeParsing()), actionCollection(), "resume_parsing");
	resumeParsingAction->setToolTip(i18n("Resume the watching of the current log"));
	resumeParsingAction->setWhatsThis(i18n("Resumes the watching of the current log. This action is only available when the user has already paused the reading."));
	resumeParsingAction->setEnabled(true);
	
	pauseParsingAction=new TDEAction(i18n("S&top Parsing"), "media-playback-stop", CTRL+Key_P, this, TQ_SLOT(pauseParsing()), actionCollection(), "pause_parsing");
	pauseParsingAction->setToolTip(i18n("Pause the watching of the current log"));
	pauseParsingAction->setWhatsThis(i18n("Pauses the watching of the current log. This action is particularly useful when the system is writing too many lines to log files, causing KSystemLog to reload too frequently."));

	detailAction=new TDEAction(i18n("&Details"), "viewmag", ALT+Key_Return, this, TQ_SLOT(slotDetails()), actionCollection(), "details");
	detailAction->setToolTip(i18n("Display details on the currently selected line"));
	detailAction->setWhatsThis(i18n("Displays a dialog box which contains details on the currently selected line. You are able to navigate through the logs from this dialog box with the <b>Previous</b> / <b>Next</b> buttons."));
	detailAction->setEnabled(false);

	tooltipEnabledAction=new TDEToggleAction(i18n("&Enable Detailed Tooltips"), 0, actionCollection(), "enable_tooltip");
	tooltipEnabledAction->setToolTip(i18n("Disable/Enable the tooltips on the current view"));
	tooltipEnabledAction->setWhatsThis(i18n("Disables/Enables the tooltips displayed when the cursor hovers a log line."));
	
	
	connect(tooltipEnabledAction, TQ_SIGNAL(toggled(bool)), this, TQ_SLOT(slotTooltipEnabled(bool)));
	
	newLinesDisplayedAction=new TDEToggleAction(i18n("&Display New Lines"), 0, actionCollection(), "display_new_line");
	newLinesDisplayedAction->setToolTip(i18n("Display or not new lines if the log changes"));
	newLinesDisplayedAction->setWhatsThis(i18n("Displays or not the new lines if the log changes. This option is useful when you want to see an old log lines and that KSystemLog often refreshes the current view."));
	
	connect(newLinesDisplayedAction, TQ_SIGNAL(toggled(bool)), this, TQ_SLOT(slotNewLinesDisplayed(bool)));

	setupGroupBy();

	setupLogActions();
	
	
}

void KSystemLog::setupLogActions() {
	
	//Define a macro allowing the connection of the signal from log action to the slotLogAction object
	#define CONNECTED_SLOT(action) connect(action, TQ_SIGNAL(activated(TDEAction::ActivationReason, TQt::ButtonState)), slotLogAction, TQ_SLOT(slotLogAction(TDEAction::ActivationReason, TQt::ButtonState)));
	
	
	//Construct the slotLogAction object
	slotLogAction=new SlotLogAction(this);
	
	TQString exclusiveGroup="LogActions";

	//System Log Action
	TDEToggleAction* systemAction=new TDEToggleAction(i18n("S&ystem Log"), SYSTEM_MODE_ICON, 0, NULL, NULL, actionCollection(), "system_log" );
	systemAction->setToolTip(i18n("Display the system log."));
	systemAction->setWhatsThis(i18n("Displays the system log in the current tab. This log is generally used by non-specialized processes (like \"sudo\" or \"fsck\" commands)"));
	systemAction->setExclusiveGroup(exclusiveGroup);
	mapActionLogModes[systemAction]=Globals::systemMode;
	CONNECTED_SLOT(systemAction)
	
	//Kernel Log Action
	TDEToggleAction* kernelAction=new TDEToggleAction(i18n("&Kernel Log"), KERNEL_MODE_ICON, 0, NULL, NULL, actionCollection(), "kernel_log" );
	kernelAction->setToolTip(i18n("Display the kernel log."));
	kernelAction->setWhatsThis(i18n("<qt>Displays the kernel log in the current tab. This log is only useful for users who want to know why the Kernel does not detect their hardware or what is the cause of the last <i>kernel panic/oops</i>.</qt>"));
	kernelAction->setExclusiveGroup(exclusiveGroup);
	mapActionLogModes[kernelAction]=Globals::kernelMode;
	CONNECTED_SLOT(kernelAction)
	
	//Boot Log Action
	TDEToggleAction* bootAction=new TDEToggleAction(i18n("&Boot Log"), BOOT_MODE_ICON, 0, NULL, NULL, actionCollection(), "boot_log" );
	bootAction->setToolTip(i18n("Display the boot log."));
	bootAction->setWhatsThis(i18n("<qt>Displays the boot log in the current tab. This log is useful if you want to verify if all startup services have been correctly started.</qt>"));
	bootAction->setExclusiveGroup(exclusiveGroup);
	mapActionLogModes[bootAction]=Globals::bootMode;
	CONNECTED_SLOT(bootAction)
	
	//Authentication Log Action
	TDEToggleAction* authenticationAction=new TDEToggleAction(i18n("A&uthentication Log"), AUTHENTICATION_MODE_ICON, 0, NULL, NULL, actionCollection(), "authentication_log" );
	authenticationAction->setToolTip(i18n("Display the authentication log."));
	authenticationAction->setWhatsThis(i18n("<qt>Displays the authentication log in the current tab. This log displays all log in made by each user of the system, and can help you to know if someone tried to crack your system.</qt>"));
	authenticationAction->setExclusiveGroup(exclusiveGroup);
	mapActionLogModes[authenticationAction]=Globals::authenticationMode;
	CONNECTED_SLOT(authenticationAction)
	
	//Daemon Log Action
	TDEToggleAction* daemonAction=new TDEToggleAction(i18n("&Daemons Log"), DAEMON_MODE_ICON, 0, NULL, NULL, actionCollection(), "daemon_log" );
	daemonAction->setToolTip(i18n("Display the daemons log."));
	daemonAction->setWhatsThis(i18n("<qt>Displays the daemons log in the current tab. The daemons are all processes launched in the background of the system. See this log if you want to know what it occurs in the background of your system.</qt>"));
	daemonAction->setExclusiveGroup(exclusiveGroup);
	mapActionLogModes[daemonAction]=Globals::daemonMode;
	CONNECTED_SLOT(daemonAction)
	
	//Cron Log Action
	TDEToggleAction* cronAction=new TDEToggleAction(i18n("&Planned Tasks Cron Log"), CRON_MODE_ICON, 0, NULL, NULL, actionCollection(), "cron_log" );
	cronAction->setToolTip(i18n("Display the planned tasks log (or Cron log)."));
	cronAction->setWhatsThis(i18n("<qt>Displays the planned tasks log in the current tab. Cron process is a program in charged of launching planned tasks on your system, like security checks, or auto-restarting of some services. Use this menu to see the last-launched processes.</qt>"));
	cronAction->setExclusiveGroup(exclusiveGroup);
	mapActionLogModes[cronAction]=Globals::cronMode;
	CONNECTED_SLOT(cronAction)
	
	//Xorg Log Action
	TDEToggleAction* xorgAction=new TDEToggleAction(i18n("&X.org Log"), XORG_MODE_ICON, 0, NULL, NULL, actionCollection(), "xorg_log" );
	xorgAction->setToolTip(i18n("Display the X.org log."));
	xorgAction->setWhatsThis(i18n("<qt>Displays the X.org log in the current tab. X.org is the service which displays on screen your desktop and manage your graphical hardware. See this log if you want to know why you do not have 3D accelerations or why your input device is not recognized.</qt>"));
	xorgAction->setExclusiveGroup(exclusiveGroup);
	mapActionLogModes[xorgAction]=Globals::xorgMode;
	CONNECTED_SLOT(xorgAction)
	
	//ACPId Log Action
	TDEToggleAction* acpidAction=new TDEToggleAction(i18n("&ACPI Log"), ACPID_MODE_ICON, 0, NULL, NULL, actionCollection(), "acpid_log" );
	acpidAction->setToolTip(i18n("Display the ACPI log."));
	acpidAction->setWhatsThis(i18n("<qt>Displays the ACPI log in the current tab. ACPI is used to manage the hardware components of your computer, like notebook batteries, reset buttons...</qt>"));
	acpidAction->setExclusiveGroup(exclusiveGroup);
	mapActionLogModes[acpidAction]=Globals::acpidMode;
	CONNECTED_SLOT(acpidAction)

	//Cups Log Action
	TDEToggleAction* cupsAction=new TDEToggleAction(i18n("&Cups Log"), CUPS_MODE_ICON, 0, NULL, NULL, actionCollection(), "cups_log" );
	cupsAction->setToolTip(i18n("Display the Cups log."));
	cupsAction->setWhatsThis(i18n("<qt>Displays the CUPS log in the current tab. CUPS is the program which manage printing on your computer.</qt>"));
	cupsAction->setExclusiveGroup(exclusiveGroup);
	mapActionLogModes[cupsAction]=Globals::cupsMode;
	CONNECTED_SLOT(cupsAction)

	//Cups Access Log Action
	TDEToggleAction* cupsAccessAction=new TDEToggleAction(i18n("&Cups Web Log"), CUPS_ACCESS_MODE_ICON, 0, NULL, NULL, actionCollection(), "cups_access_log" );
	cupsAccessAction->setToolTip(i18n("Display the CUPS Web Server Access log."));
	cupsAccessAction->setWhatsThis(i18n("<qt>Displays the CUPS Web Server Access log in the current tab. CUPS is the program which manage printing on your computer. This log saves all requests performed to the CUPS embedded web server (default: <i>http://localhost:631</i>).</qt>"));
	cupsAccessAction->setExclusiveGroup(exclusiveGroup);
	mapActionLogModes[cupsAccessAction]=Globals::cupsAccessMode;
	CONNECTED_SLOT(cupsAccessAction)
	

	//Apache Log Action
	TDEToggleAction* apacheAction=new TDEToggleAction(i18n("&Apache log"), APACHE_MODE_ICON, 0, NULL, NULL, actionCollection(), "apache_log" );
	apacheAction->setToolTip(i18n("Display the Apache log."));
	apacheAction->setWhatsThis(i18n("<qt>Displays the Apache log in the current tab. Apache is the main used Web server in the world.</qt>"));
	apacheAction->setExclusiveGroup(exclusiveGroup);
	mapActionLogModes[apacheAction]=Globals::apacheMode;
	CONNECTED_SLOT(apacheAction)

	//Apache Access Log Action
	TDEToggleAction* apacheAccessAction=new TDEToggleAction(i18n("&Apache Web log"), APACHE_ACCESS_MODE_ICON, 0, NULL, NULL, actionCollection(), "apache_access_log" );
	apacheAccessAction->setToolTip(i18n("Display the Apache Access log."));
	apacheAccessAction->setWhatsThis(i18n("<qt>Displays the Apache Access log in the current tab. CUPS is the program which manage printing on your computer. This log saves all requests performed by the Apache web server.</qt>"));
	apacheAccessAction->setExclusiveGroup(exclusiveGroup);
	mapActionLogModes[apacheAccessAction]=Globals::apacheAccessMode;
	CONNECTED_SLOT(apacheAccessAction)
	
	//Mail Log Action
	TDEToggleAction* mailAction=new TDEToggleAction(i18n("&Mail Log"), MAIL_MODE_ICON, 0, NULL, NULL, actionCollection(), "mail_log" );
	mailAction->setToolTip(i18n("Display the Mail log."));
	mailAction->setWhatsThis(i18n("<qt>Displays the mail log in the current tab. Mail is the most known and used mail server in the Linux world.</qt>"));
	mailAction->setExclusiveGroup(exclusiveGroup);
	mapActionLogModes[mailAction]=Globals::mailMode;
	CONNECTED_SLOT(mailAction)
	
	//Samba Log Action
	TDEToggleAction* sambaAction=new TDEToggleAction(i18n("&Samba Log"), SAMBA_MODE_ICON, 0, NULL, NULL, actionCollection(), "samba_log" );
	sambaAction->setToolTip(i18n("Display the Samba log."));
	sambaAction->setWhatsThis(i18n("<qt>Displays the Samba log in the current tab. Samba is the file sharing server which interacts with Microsoft Windows network.</qt>"));
	sambaAction->setExclusiveGroup(exclusiveGroup);
	mapActionLogModes[sambaAction]=Globals::sambaMode;
	CONNECTED_SLOT(sambaAction)
	
}


void KSystemLog::reloadCurrent() {
	LogManager* manager=activeLogManager();
	
	if (manager!=NULL) {
		manager->reload();
	}
	
}


void KSystemLog::reloadAll() {
	TQPtrListIterator<LogManager> it(logManagers);
	
	//Inform the Loading Dialog on how many Log Managers we have to load
	loadingDialog->setTabCount(logManagers.count());
	
	int index=1;
	
	LogMode* mode;
	
	LogManager* current=it.current();
	while(current!=NULL) {
		
		//Inform the Loading Dialog that there is a new loading
		loadingDialog->setCurrentTab(index);

		//TODO Experimental Code... The manager is now using the Log mode passed in parameter
		mode=current->getLogMode();
		
		//The no log mode does not have to be reloaded
		if (mode==Globals::noMode) {
			++it;
			current=it.current();
			index++;
			continue;
		}
		
		
		if (mode!=Globals::openingMode)
			current->initialize(mode);
		
		current->reload();
		
		++it;
		current=it.current();
		index++;
	}
	
	//Reposition the count total to its default value
	loadingDialog->setTabCount(0);

}

void KSystemLog::slotSelectionChanged() {
	//kdDebug() << "KSystemLog selectionChanged()" << endl;
	
	LogListItem* item=activeLogManager()->getView()->getFirstSelectedItem();
	
	bool selection;
	
	//No item selected
	if (item==NULL) {
		selection=false;
	}
	else {
		selection=true;
	}

	copyAction->setEnabled(selection);
	saveAction->setEnabled(selection);
	detailAction->setEnabled(selection);
	sendMailAction->setEnabled(selection);

	if (detailDialog!=NULL) {
		detailDialog->selectionChanged();
	}
}

void KSystemLog::moveTabLeft() {
	LogManager* currentManager=activeLogManager();
	
	int position=tabs->indexOf(currentManager->getView());
	
	if (position<=0)
		return;

	logManagers.remove(position);
	
	logManagers.insert(position-1, currentManager);
	
	tabs->moveTab(position, position-1);

}

void KSystemLog::moveTabRight() {
	LogManager* currentManager=activeLogManager();
	
	int position=tabs->indexOf(currentManager->getView());
	
	if (position>=tabs->count()-1)
		return;
		
	logManagers.remove(position);
		
	logManagers.insert(position+1, currentManager);
	
	tabs->moveTab(position, position+1);
	
}


LogManager* KSystemLog::duplicateTab() {
	LogManager* currentManager=activeLogManager();
	
	LogManager* newManager=newTab();
	
	LogMode* mode=currentManager->getLogMode();
	if (mode==Globals::openingMode) {
		//We retrieve the path of the URL of the first file of the file list of the current manager ;-)
		ReaderFactory::lastOpenedURL=currentManager->getLogFiles().first()->url;

		this->load(mode, newManager);
	}
	else {
		this->load(mode, newManager);
	}
	
	//Returns the newly created LogManager
	return(newManager);
}


LogManager* KSystemLog::newTab() {
	LogManager* manager=new LogManager(this, loadingDialog);
	
	//Signals from LogManager to Main Class
	connect(manager, TQ_SIGNAL(changeTitle(View*, const TQString&)), this, TQ_SLOT(changeTab(View*, const TQString& )));
	connect(manager, TQ_SIGNAL(changeTitle(View*, const TQIconSet&, const TQString&)), this, TQ_SLOT(changeTab(View*, const TQIconSet&, const TQString&)));
	connect(manager, TQ_SIGNAL(changeCaption(const TQString&)), this, TQ_SLOT(setCaption(const TQString&)));
	connect(manager, TQ_SIGNAL(changeStatusbar(const TQString&)), this, TQ_SLOT(changeStatusbar(const TQString&)));
	connect(manager, TQ_SIGNAL(logUpdated(int)), this, TQ_SLOT(logUpdated(int)));
	connect(manager, TQ_SIGNAL(reloaded()), this, TQ_SLOT(logManagerReloaded()));
	connect(manager, TQ_SIGNAL(GUIUpdated()), this, TQ_SLOT(updateGUI()));
	connect(manager, TQ_SIGNAL(detailsCalled()), this, TQ_SLOT(slotDetails()));
	connect(manager, TQ_SIGNAL(selectionChanged()), this, TQ_SLOT(slotSelectionChanged()));
	
	//Signals from Main Actions to LogManager
	connect(expandAllAction, TQ_SIGNAL(activated()), manager, TQ_SLOT(slotExpandAll()));
	connect(collapseAllAction, TQ_SIGNAL(activated()), manager, TQ_SLOT(slotCollapseAll()));
	connect(saveAction, TQ_SIGNAL(activated()), manager, TQ_SLOT(slotFileSave()));
	connect(copyAction, TQ_SIGNAL(activated()), manager, TQ_SLOT(slotCopyToClipboard()));
	connect(sendMailAction, TQ_SIGNAL(activated()), manager, TQ_SLOT(slotSendMail()));
	
	logManagers.append(manager);
	
	tabs->insertTab(manager->getView(), SmallIcon(NO_MODE_ICON), i18n("No Log"));
	
	if (tabs->count()>1) {
		tabs->setTabBarHidden(false);
	}
	else {
		tabs->setTabBarHidden(true);
	}

	tabs->setCurrentPage(tabs->count()-1);
	
	//Correctly initialize the Status Bar
	updateStatusBar();

	//Returns the newly created LogManager
	return(manager);
}

void KSystemLog::changeTab(View* view, const TQString& label) {
	tabs->changeTab(view, label);
}

void KSystemLog::changeTab(View* view, const TQIconSet& icon, const TQString& label) {
	tabs->changeTab(view, icon, label);
}

int KSystemLog::getIndex(LogManager* manager) {
	
	TQPtrListIterator<LogManager> it(logManagers);
	
	LogManager* temp=it.current();
	int pos=0;
	while(temp!=NULL) {
		
		if (temp==manager) {
			return(pos);
		}
		
		++pos;
		++it;
		temp=it.current();
	}

	//Should never happen
	kdDebug() << "Log manager not found in the list" << endl;
	return(-1);
}


void KSystemLog::setCurrentLogManager(LogManager* currentManager) {
	currentManager->setCurrent(true);
	
	TQPtrListIterator<LogManager> it(logManagers);
	
	LogManager* manager=it.current();
	while(manager!=NULL) {
		if (manager!=currentManager) {
			manager->setCurrent(false);
		}
		
		++it;
		manager=it.current();
	}

	
}

void KSystemLog::closeTab() {
	if (tabs->count()==1)
		return;
	
	LogManager* currentManager=activeLogManager();
	
	tabs->removePage(currentManager->getView());
	
	logManagers.remove(currentManager);
	
	this->setCurrentLogManager(logManagers.last());
	
	//TODO Delete the current Manager correctly ! (this crash KSystemLog)
	//TODO Do correctly the disconnection of signal (disconnect(... ...)) before deleting the object
	//currentManager
	//delete currentManager;
	
	
	/* 
	//TODO Strange result : (mail this to KDE Developer)
	if (tabs->count()==2) {
		tabs->removePage(currentView);
		
		View* currentView=activeView();
		tabs->removePage(currentView);
	}
	else {
		tabs->removePage(currentView);	
	}
	*/
	
	if (tabs->count()==1) {
		tabs->setTabBarHidden(true);
	}
}


void KSystemLog::quit() {
	saveConfig();
	
	kapp->quit();
}

void KSystemLog::slotToggleFilterBar() {

	//Update the configuration
	KSystemLogConfig::setToggleFilterBar(filterBarAction->isChecked());
	
	//And call an updating method on each Log Manager
	TQPtrListIterator<LogManager> it(logManagers);
	
	LogManager* current=it.current();
	while (current!=NULL) {
		
		current->toggleFilterBar();
		
		++it;
		current=it.current();
	}
	
	
}

void KSystemLog::slotDetails() {
	LogListItem* item=activeLogManager()->getView()->getFirstSelectedItem();
	
	//If no item are selected, we don't open the dialog
	if (item==NULL)
		return;
	
	//If the dialog has not been created, we create it
	if (detailDialog==NULL) {
		detailDialog=new DetailDialog(activeLogManager()->getView(), this, "detail_dialog");
		connect(activeLogManager()->getView()->getLogList(), TQ_SIGNAL(selectionChanged()), detailDialog, TQ_SLOT(selectionChanged()));
		//connect(activeLogManager()->getView()->getLogList(), TQ_SIGNAL(triggerUpdate()), detailDialog, TQ_SLOT(selectionChanged()));
	}

	detailDialog->show();

}

void KSystemLog::slotSelectAll() {
	activeLogManager()->getView()->getLogList()->selectAll(true);
}

void KSystemLog::slotTooltipEnabled(bool enabled) {
	KSystemLogConfig::setTooltipEnabled(enabled);

	TQPtrListIterator<LogManager> it(logManagers);
	while(it.current()!=NULL) {
		(it.current())->setTooltipEnabled(enabled);
		++it;
	}
	
}

void KSystemLog::slotNewLinesDisplayed(bool displayed) {
	KSystemLogConfig::setNewLinesDisplayed(displayed);

	TQPtrListIterator<LogManager> it(logManagers);
	while(it.current()!=NULL) {
		(it.current())->setNewLinesDisplayed(displayed);
		++it;
	}


}


void KSystemLog::logUpdated(int /*lines*/) {
	kdDebug() << "KSystemLog logUpdated()" << endl;

	updateStatusBar();
}

void KSystemLog::updateStatusBar() {
	LogManager* currentManager=activeLogManager();

	TQString lineCount=i18n("1 log line.", "%n log lines.", currentManager->getView()->getItemCount());
	
	statusBar()->changeItem(lineCount, STATUS_BAR_LINE_COUNT);
	
	TQString time=i18n("Last updated: %1.").arg(currentManager->getLastUpdate().toString(TQt::LocalDate));
	
	statusBar()->changeItem(time, STATUS_BAR_LAST_MODIFICATION);


}


void KSystemLog::pauseParsing() {
	activeLogManager()->setParsingPaused(true);

	//Desactivate the pause action, and activate the resume one
	resumeParsingAction->setEnabled(true);
	pauseParsingAction->setEnabled(false);
}

void KSystemLog::resumeParsing() {
	activeLogManager()->setParsingPaused(false);

	//Desactivate the resume action, and activate the pause one
	resumeParsingAction->setEnabled(false);
	pauseParsingAction->setEnabled(true);
}

//If no actions are selected, than all are deselected
void KSystemLog::deactiveLogActions() {
	TQValueList<TDEToggleAction*> actions=mapActionLogModes.keys();
	
	TDEToggleAction* action;
	TQValueList<TDEToggleAction*>::iterator it;
	for (it=actions.begin(); it!=actions.end(); ++it) {
		action=*it;
		
		action->setChecked(false);
	}
	
}

TDEToggleAction* KSystemLog::getCorrespondingLogAction(LogMode* mode) {
	//Special case for no and opening mode
	//TODO Maybe use a list for "special" log mode, and pre-test the parameter with it
	if (mode==Globals::noMode || mode==Globals::openingMode)
		return(NULL);

	TQValueList<TDEToggleAction*> keys=mapActionLogModes.keys();
	
	TQValueList<TDEToggleAction*>::iterator it;
	
	TDEToggleAction* key;
	
	
	for (it=keys.begin(); it!=keys.end(); ++it) {
		key=*it;
		
		if (mapActionLogModes[key]==mode)
			return(key);
	}	

	kdDebug() << "Strange : The corresponding log action does not exist" << endl;	
	return(NULL);
}


TDEToggleAction* KSystemLog::getLogAction(const char* name) {
	return( static_cast<TDEToggleAction*> (actionCollection()->action(name)) );
}

void KSystemLog::logActionClicked(const TQObject* sender, TDEAction::ActivationReason reason, TQt::ButtonState state) {
	TDEToggleAction* action=getLogAction(sender->name());
	
	LogMode* mode=mapActionLogModes[action];
	
	if (mode==NULL) {
		kdDebug() << "Strange : The selected mode does not exist" << endl;
		return;
	}
	
	//TODO Be sure that the + is the right symbol to combine TQt Constants
	//If the user uses the middle button OR left button + shift OR left button + control : = it opens the log in a new tab
	if (state==TQt::MidButton || (state==TQt::ControlButton+TQt::LeftButton) || (state==TQt::ShiftButton+TQt::LeftButton))
		newTab();
	
	this->load(mode, activeLogManager());
	
	//If don't know why it needs a false parameter (useful if user reclick on the same log mode than previous one)
	action->setChecked(false);


}

void KSystemLog::fileOpen() {
	//Open a standard Filedialog
	KURL openingFileName(KFileDialog::getOpenURL(TQString(), TQString(), this, i18n("Open Location")));
	kdDebug() << "Opening file : " << openingFileName.url() << endl;
	
	if (!openingFileName.isEmpty()) {
		if (openingFileName.isValid()) {
			//Deactive the old action mode
			deactiveLogActions();
			
			ReaderFactory::lastOpenedURL=openingFileName;
			//Launch the actualizing
			this->load(Globals::openingMode, activeLogManager());
		}
		else {
			TQString message(i18n("Malformed URL. Unable to open this file."));
			KMessageBox::error(this, message, i18n("Unable to open this file."), KMessageBox::Notify);
		}
	}
}

/**
 * This slot is called whenever the File->Print menu is selected,
 * the Print shortcut is pressed (usually CTRL+P) or the Print toolbar
 * button is clicked
 */
void KSystemLog::filePrint() {
	if (!printer)
		printer=new KPrinter();
	
	if (printer->setup(this)) {
		// setup the printer.  with TQt, you always "print" to a
		// TQPainter.. whether the output medium is a pixmap, a screen,
		// or paper
		TQPainter p;
		p.begin(printer);
		
		// we let our view do the actual printing
		TQPaintDeviceMetrics metrics(printer);
		activeLogManager()->getView()->print(&p, metrics.height(), metrics.width());
		
		// and send the result to the printer
		p.end();
	}
}


void KSystemLog::slotOptions() {
	kdDebug() << "Launching the option dialog box..." << endl;

	Options dialog(this, "config_dialog", false);
	if (dialog.exec()) {
		//Once the option dialog is close, we can make a simple reloading of each LogManager
		reloadAll();
	}

}

void KSystemLog::slotLogMessage() {
	kdDebug() << "Launching the Send message dialog box..." << endl;

	//TODO Create a pointer if this dialog begun non-modal
	LoggerDialog dialog(this, "logger_dialog");
	dialog.exec();

}


void KSystemLog::changeStatusbar(const TQString& text) {
	//Display this text on the statusbar
	statusBar()->message(text);
}

void KSystemLog::changeCaption(const TQString& text) {
	//Display this text on the caption
	setCaption(text);
}

void KSystemLog::setupProgressDialog() {
	//TODO Move this to the LoadingDialog constructor
	loadingDialog=new LoadingDialog((TQWidget*)this, "progress_dialog", true);
	loadingDialog->setAllowCancel(false);
	loadingDialog->setAutoClose(false);
	loadingDialog->setMinimumDuration(500);
	loadingDialog->progressBar()->setTotalSteps(100);

}


void KSystemLog::readConfig() {
	kdDebug() << "Reading KSystemLog configuration..." << endl;
	
	//Filter Bar is displayed depending on the config file
	filterBarAction->setChecked(KSystemLogConfig::toggleFilterBar());
	
	TQValueList<int> groupByTypes=KSystemLogConfig::groupBy();
	TQValueList<int> groupByColumns=KSystemLogConfig::groupByColumns();
	
	TQValueList<int>::iterator itGroupBy=groupByTypes.begin();
	TQValueList<int>::iterator itGroupByColumn=groupByColumns.begin();

	TQValueList<int> modes=KSystemLogConfig::logModes();
	TQStringList fileList=KSystemLogConfig::openedURLs();
	
	TQValueList<int>::iterator it;
	TQStringList::iterator itString=fileList.begin();
	
	//Inform the Loading Dialog on how many Log Managers we have to load
	loadingDialog->setTabCount(modes.count());
	loadingDialog->setFirstLoading(true);
	
	int index=1;
	
	int mode;
	LogMode* logMode;
	
	for(it=modes.begin(); it!=modes.end(); ++it) {
		mode=*it;
		
		logMode=Globals::logModes.at(mode);
		//If the mode is not valid, we go to the next one
		if (logMode==NULL) {
			++index;
			++itGroupByColumn;
			++itGroupBy;
			continue;
		}
		
		//The specific opening file special case
		if (logMode==Globals::openingMode) {
			//If this file is not valid, we go to the next mode
			if (itString==fileList.end()) {
				++itString;
				++index;
				++itGroupByColumn;
				++itGroupBy;
				continue;
			}
			
			KURL file(*itString);
			
			//If this file is not valid, we go to the next mode
			if (!file.isValid()) {
				++itString;
				++index;
				++itGroupByColumn;
				++itGroupBy;
				continue;
			}
			
			ReaderFactory::lastOpenedURL=file;
			
			++itString;
		}
		
		//Inform the Loading Dialog that there is a new loading
		loadingDialog->setCurrentTab(index);
		
		//Create a new tab
		LogManager* manager=newTab();
		
		//If this file is not valid, we go to the next mode
		if (logMode==Globals::noMode) {
			++index;
			++itGroupByColumn;
			++itGroupBy;
			continue;
		}
		
		//Test the value from config file
		groupByType groupBy;
		if (itGroupBy==groupByTypes.end())
			groupBy=NO_GROUP_BY;
		else
			groupBy=(groupByType) (*itGroupBy);
		
		//Test the value from config file
		int groupByColumn;
		if (itGroupByColumn==groupByColumns.end())
			groupByColumn=-1;
		else
			groupByColumn=*itGroupByColumn;

		//Retrieve the group by parameters from configuration, and set them to the new manager
		manager->setGroupBy(groupBy, groupByColumn);
		
		//Open the matching mode to this tab
		this->load(logMode, activeLogManager());
			

		++index;
		++itGroupByColumn;
		++itGroupBy;
		
	}
	
	int selection=KSystemLogConfig::selectedTab();
	if (selection<0 || selection>=(int)logManagers.count())
		selection=0;

	kdDebug() << "Selection=" << selection << endl;
	
	tabs->setCurrentPage(selection);


	//Initialize the displaying of new items from config file
	bool value=KSystemLogConfig::newLinesDisplayed();
	newLinesDisplayedAction->setChecked(value);
	slotNewLinesDisplayed(value);

	//Initialize the enabling of Tooltip from config file
	value=KSystemLogConfig::tooltipEnabled();
	tooltipEnabledAction->setChecked(value);
	slotTooltipEnabled(value);
	
	//Reposition the count total to its default value
	loadingDialog->setTabCount(0);
	loadingDialog->setFirstLoading(false);
	
}


void KSystemLog::saveConfig() {
	kdDebug() << "Last configuration saving..." << endl;
	
	TQValueList<int> intList;
	TQStringList stringList;
	
	TQPtrListIterator<LogManager> it(logManagers);
	
	LogManager* manager=it.current();
	
	while(manager!=NULL) {
		//If it's an opening mode, then we save its open file
		if (manager->getLogMode()==Globals::openingMode) {
			//We retrieve the path of the URL of the first file of the file list of the current manager ;-)
			TQString file(manager->getLogFiles().first()->url.path());
			
			stringList.push_back(file);
		}
		
		intList.push_back(manager->getLogMode()->id);
		
		++it;
		manager=it.current();
	}
	
	//Save the log modes
	KSystemLogConfig::setLogModes(intList);
	
	//Save the file list (even if it is empty)
	KSystemLogConfig::setOpenedURLs(stringList);
	
	/**
	 * Save the group by type and the column
	 */
	TQValueList<int> groupByTypes;
	TQValueList<int> groupByColumns;
	
	it=logManagers;
	manager=it.current();
	while(manager!=NULL) {
		groupByTypes.push_back(manager->getGroupBy());
		groupByColumns.push_back(manager->getGroupByColumn());
		
		++it;
		manager=it.current();
	}
	
	//Save the group by types
	KSystemLogConfig::setGroupBy(groupByTypes);
	
	//Save the sort columns
	KSystemLogConfig::setGroupByColumns(groupByColumns);

	//Save the last selected tab
	KSystemLogConfig::setSelectedTab(tabs->currentPageIndex());

	it=logManagers;
	manager=it.current();
	while(manager!=NULL) {
		manager->saveConfig();
		
		++it;
		manager=it.current();
	}
	
	//Write the config to the file
	KSystemLogConfig::writeConfig();
}

void KSystemLog::logManagerReloaded() {
	//Update the detail dialog (because for the first reading, the logUpdated() signal is not sent)
	if (detailDialog!=NULL) {
		detailDialog->selectionChanged();
	}
	
	//Update Group By, because the currentTabChanged() slot is not called the first time we load a reader
	updateGroupBy();

	updateStatusBar();
	
	
	kdDebug() << "Log List reloaded..." << endl;
}

void KSystemLog::load(LogMode* logMode, LogManager* manager) {
	loadingDialog->setFirstLoading(true);
	
	if (manager==NULL || logMode==NULL) {
		kdDebug() << "Error while reloading a manager" << endl;
		return;
	}
	
	//The manager is now using the Log mode passed in parameter
	manager->initialize(logMode);
	
	//Launch the reading
	manager->reload();
	
	loadingDialog->setFirstLoading(false);

}


/** 
 * the 'config' object points to the session managed
 * config file.  anything you write here will be available
 * later when this app is restored
 */
void KSystemLog::saveProperties(TDEConfig* /*config*/) {
	kdDebug() << "saveProperties method." << endl;
}

/**
 * the 'config' object points to the session managed
 * config file.  this function is automatically called whenever
 * the app is being restored.  read in here whatever you wrote
 * in 'saveProperties'
 */
void KSystemLog::readProperties(TDEConfig* /*config*/) {
	kdDebug() << "readProperties method." << endl;
}

void KSystemLog::dragEnterEvent(TQDragEnterEvent *event) {
	//Accept URI drops only
	event->accept(KURLDrag::canDecode(event));
}

void KSystemLog::setupGroupBy() {
	groupBy=new TDEActionMenu(i18n("Group By"), SmallIcon(GROUP_BY_ICON), this, "group_by");
	actionCollection()->insert(groupBy);

	TDEPopupMenu* menu=groupBy->popupMenu();
	
	menu->insertItem(SmallIcon(NO_GROUP_BY_ICON), i18n("None"), NO_GROUP_BY);
	
	menu->insertSeparator();
	
	menu->insertItem(SmallIcon(GROUP_BY_LOG_LEVEL_ICON), i18n("Log Level"), GROUP_BY_LOG_LEVEL);

	menu->insertItem(SmallIcon(GROUP_BY_DAY_ICON), i18n("Day"), GROUP_BY_DAY);

	menu->insertItem(SmallIcon(GROUP_BY_HOUR_ICON), i18n("Hour"), GROUP_BY_HOUR);
	
	menu->insertItem(SmallIcon(GROUP_BY_LOG_FILE_ICON), i18n("Log File"), GROUP_BY_LOG_FILE);
	
	menu->insertSeparator();

	connect(menu, TQ_SIGNAL(activated(int)), this, TQ_SLOT(groupByChanged(int)));
	
}

void KSystemLog::groupByChanged(int group) {
	TDEPopupMenu* menu=groupBy->popupMenu();

	for(int i=0; i<(int) menu->count(); ++i) {
		menu->setItemChecked(menu->idAt(i), false);
	}
	
	menu->setItemChecked(group, true);
	
	LogManager* manager=activeLogManager();
	if (manager==NULL)
		return;
	
	int column=group-DEFAULT_GROUP_BY_COUNT;
	
	//If column<0, it means that we use a standard group by
	if (column<0) {
		kdDebug() << "Using a normal Group By : " << (groupByType)group << endl;
		manager->setGroupBy((groupByType)group);
	}
	//Else we use a specifical column
	else {
		kdDebug() << "Using a column Group By : column=" << column << endl;
		manager->setGroupBy(GROUP_BY_COLUMN, column);
	}
	
	reloadCurrent();
	
}

void KSystemLog::updateGroupBy() {

	kdDebug() << "Updating group by..." << endl;
	
	TDEPopupMenu* menu=groupBy->popupMenu();
	
	//First : removing old TDEAction
	//The deleting begins at default groupby count + 2 separator (in the menu)
	int deleting=DEFAULT_GROUP_BY_COUNT+2;
	int end=menu->count();
	for (int i=deleting; i<end; ++i) {
		menu->removeItemAt(deleting);
	}
	

	LogManager* manager=activeLogManager();
	
	if (manager==NULL) {
		return;
	}
	else {
		//Management of Expand and Collapse actions
		if (manager->getGroupBy()!=NO_GROUP_BY) {
			expandAllAction->setEnabled(true);
			collapseAllAction->setEnabled(true);
		}
		else {
			expandAllAction->setEnabled(false);
			collapseAllAction->setEnabled(false);
		}

		LogViewColumns* columns=manager->getColumns();
		if (columns==NULL)
			return;
		
		int id=DEFAULT_GROUP_BY_COUNT;
		LogViewColumns::Iterator it;
		LogViewColumn* column;
		for(it=columns->begin(); it!=columns->end(); it++) {
			column=*it;
			
			if (column->isGrouped) {
				menu->insertItem(column->columnName, id);
			}

			++id;
		}
		
	}
	
	//Get the selected GroupBy from (new) current LogManager and select it in the popup menu
	
	//First Deselect all items
	for(int i=0; i<(int) menu->count(); ++i) {
		menu->setItemChecked(menu->idAt(i), false);
	}
	
	
	//Then get the active manager and its group by value
	int selection=manager->getGroupBy();
	
	//If no selection, the first item is checked
	if (selection==0) {
		menu->setItemChecked(NO_GROUP_BY, true);
	}
	//If it's one of the predefined selection, we select the right item
	else if (selection!=GROUP_BY_COLUMN) {
		menu->setItemChecked(selection, true);
	}
	//Else, we select the corresponding column
	else {
		selection=selection + manager->getGroupByColumn();
		menu->setItemChecked(selection, true);
	}
	
		
	//Manage the disabling of default GroupBy choice
	LogViewColumns* columns=manager->getColumns();
	menu->setItemEnabled(GROUP_BY_LOG_LEVEL, columns->isGroupByLogLevel());
	menu->setItemEnabled(GROUP_BY_DAY, columns->isGroupByDay());
	menu->setItemEnabled(GROUP_BY_HOUR, columns->isGroupByHour());
	menu->setItemEnabled(GROUP_BY_LOG_FILE, columns->isGroupByLogFile());
	
}

/**
 * This is a very simplistic implementation of a drop event.  we
 * will only accept a dropped URL.  the TQt dnd code can do *much*
 * much more, so please read the docs there
 */
void KSystemLog::dropEvent(TQDropEvent *event) {
	KURL::List urls;
	
	//See if we can decode a URI
	if (KURLDrag::decode(event, urls) && !urls.isEmpty()) {
		//Several URI have been found
		ReaderFactory::lastOpenedURL=urls.first();
		
		this->load(Globals::openingMode, activeLogManager());
	}
}

void KSystemLog::updateGUI() {
	kapp->processEvents();
}


#include "ksystemlog.moc"
