/***************************************************************************
                          kbearmainwindow.cpp  -  description
                             -------------------
    begin                : smån jan 13 2003
    copyright            : (C) 2003 by Björn Sahlström
    email                : kbjorn@users.sourceforge.net
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   mainWindow() 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.                                   *
 *                                                                         *
 ***************************************************************************/

//////////////////////////////////////////////////////////////////////
// Qt specific include files
#include <qfile.h>
#include <qwhatsthis.h>
#include <qtimer.h>
#include <qsize.h>
//////////////////////////////////////////////////////////////////////
// KDE specific include files
#include <kconfig.h>
#include <dcopclient.h>
#include <kstdaction.h>
#include <kshortcut.h>
#include <kstatusbar.h>
#include <ktoolbar.h>
#include <kstandarddirs.h>
#include <kapplication.h>
#include <kconfigbase.h>
#include <dcopobject.h>
#include <ktip.h>
#include <kxmlguiclient.h>
#include <kdebug.h>
//////////////////////////////////////////////////////////////////////
// Application specific include files
#include "kbearmainwindow.h"
#include "kbearpartmanager.h"
#include "kbearfilesyspartiface.h"
#include "transfermanager.h"
#include "kbearpartiface.h"
#include "kbearcore.h"
#include "api.h"
#include "resource.h"
#include "kbearoutputtoolbar.h"
#include "kbearoutputframe.h"
#include "siteinfo.h"
#include "misc.h"
#include "kbearpartiface.h"

#include "kbearmainwindow.moc"

using namespace KBear;

//-----------------------------------------------
KBearMainWindow::KBearMainWindow()
	:	KMdiMainFrm( 0L, "KBear",WDestructiveClose | WStyle_ContextHelp ),
		m_viewLocal( 0L ),
		m_viewLocalCaption( i18n("Your Local File System" ) ),
		m_isClosing( false ),
		m_shared( new KBearMainWindowShared( this ) ),
		m_autoChildFrameMode( true ),
		m_childFrameMode( KBear::TileVertically ),
		m_rememberTopLevelChildPos( true )
{
	setInstance( KGlobal::instance() );
	setCaption( VERSION );
	setStandardToolBarMenuEnabled( true );
	m_shared->createOutputToolbar( m_pDockbaseAreaOfDocumentViews );
	KParts::DockMainWindow::statusBar()->show();
	setAutoSaveSettings( "MainWindow" );
	setupActions();
	setXMLFile("kbearui.rc");
	setMenuForSDIModeSysButtons( menuBar() );
	actionCollection()->setHighlightingEnabled( true );
	// Important !!!!! we need to call createGUI before creating the outputtoolbar

	// This is needed since we use our own menu based on actions
	delete m_pWindowMenu;

}
//-----------------------------------------------
KBearMainWindow::~KBearMainWindow() {
	delete m_shared;
}
//-----------------------------------------------
void KBearMainWindow::init() {
	createGUI( 0L );
	m_shared->init();

	m_pTaskBar->setFullSize( true );
	m_pTaskBar->setNewLine( true );
	m_pTaskBar->setMovingEnabled( true );
	m_pTaskBar->setEnableContextMenu( false );
//	m_pTaskBar->saveState();
	connect( m_pTaskBar, SIGNAL( visibilityChanged( bool ) ), m_toggleTaskBar, SLOT( setChecked( bool ) ) );
	m_toggleTaskBar->setChecked( m_pTaskBar->isVisible() );

	API::getInstance()->partManager()->setAllowNestedParts( true );

	connect( API::getInstance()->partManager(), SIGNAL( activePartChanged( KParts::Part* ) ), this, SLOT( createGUI( KParts::Part* ) ) );
	connect( API::getInstance()->core(), SIGNAL( newToolbarConfig() ), this, SLOT( fillWindowMenu() ) );

	setupToolTips();
	initViewLocal();

	KParts::DockMainWindow::statusBar()->message(i18n( "Ready." ));

	fillWindowMenu();
	QObject::connect( m_pWindowMenu, SIGNAL(aboutToShow()), this, SLOT(fillWindowMenu()) );

	kapp->processEvents();
}
//-----------------------------------------------
bool KBearMainWindow::event( QEvent* e) {
	if( e->type() == QEvent::User) {
		KMdiChildView* pWnd = (KMdiChildView*)((KMdiViewCloseEvent*)e)->data();
		if( pWnd != 0L ) {
			KBearChildView* view = m_childViewMap[ pWnd ];
			if( view ) {
				view->stop(); // stop listing first
				if( pWnd == m_childViewLocal ) {
					// if it's the local fileview we don't close it, just hiding it
					// otherwise the part gets unloaded
					static_cast<KToggleAction*>(actionCollection()->action("show_local"))->setChecked( false );
					showViewLocal();
					// for auto tiling
					if( m_autoChildFrameMode && mdiMode() == KMdi::ChildframeMode )
						QTimer::singleShot( 100, this, SLOT( switchToChildframeMode() ) );
					return false;
				}
			}
			closeWindow( pWnd);
			// for auto tiling
			if( m_autoChildFrameMode && mdiMode() == KMdi::ChildframeMode ) {
				switchToChildframeMode();
			}
			return true;
		}
	}

	return KMdiMainFrm::event( e);
}
//-----------------------------------------------
bool KBearMainWindow::queryClose() {
	if( m_isClosing )
		return true;

	QTimer::singleShot( 0, API::getInstance()->core(), SLOT( requestShutDown() ) );
	return false;
}
//-----------------------------------------------
void KBearMainWindow::realClose() {
	// if user want to save ' run time settings'
	KConfigGroupSaver cs( kapp->config(), kapp->config()->group() );
	kapp->config()->setGroup( "General" );
	kapp->config()->writeEntry( "First Run", false );
	if( kapp->config()->readBoolEntry( "Run Time Settings", true) )
		saveProperties( kapp->config() );

	kapp->config()->sync();

	closeAllViews();

	m_isClosing = true;
	QTimer::singleShot( 0, this , SLOT( slotClose() ) );
}
//-----------------------------------------------
void KBearMainWindow::raiseMainWindow() {
	raise();
}
//-----------------------------------------------
void KBearMainWindow::slotClose() {
	close();
}
//-----------------------------------------------
void KBearMainWindow::slotCloseChildView() {
	KBearChildView* view = (KBearChildView*)QObject::sender();
	KMdiChildView* childView = m_widgetMap[ view ];
	if( childView )
		closeWindow( childView );
}
//-----------------------------------------------
KBearChildViewIface* KBearMainWindow::createClient( const SiteInfo& info, const QString& whatsThis ) {
	KBearChildView* w = new KBearChildView( 0L, info );
	connect( w, SIGNAL( closeMe() ), this, SLOT( slotCloseChildView() ) );
	QWhatsThis::add( w, whatsThis );
	QString label = info.label();
	KMdiChildView* pMDICover = createWrapper( w, label, label );
	connect( pMDICover, SIGNAL( gotFocus( KMdiChildView* ) ),
		this, SLOT( slotChildViewGotFocus( KMdiChildView* ) ) );
	w->installEventFilter( pMDICover );
	pMDICover->setFirstFocusableChildWidget( w );
	pMDICover->setMDICaption( label );
	m_widgetMap.insert( w, pMDICover );
	m_childViewMap.insert( pMDICover, w );

	unsigned int mdiFlags = KMdi::StandardAdd | KMdi::UseQextMDISizeHint;
	addWindow( pMDICover, mdiFlags );

	pMDICover->setGeometry( geometry().left(), geometry().top(), 400, 300 );

	// hack for a strange geometry problem (otherwise the childview doesn't move to the right position in the childframe)
	if( ( mdiMode() == KMdi::ChildframeMode ) && isInMaximizedChildFrmMode() ) {
		QWidget* v;
		if( pMDICover->mdiParent() ) {
			v = pMDICover->mdiParent();
		}
		else {
			v = pMDICover;
		}
		QRect geom = v->geometry();
		v->setGeometry(geom.left(),geom.top(),geom.width()+1,geom.height()+1);
		v->setGeometry(geom.left(),geom.top(),geom.width(),geom.height());
	}

	if( m_autoChildFrameMode && mdiMode() == KMdi::ChildframeMode )
		QTimer::singleShot( 0, this , SLOT( switchToChildframeMode() ) );
	else if( mdiMode() == KMdi::ToplevelMode && m_rememberTopLevelChildPos )
		readTopChildPositionFromIndex( m_pWinList->count() - 1 );

	return w;
}
//-----------------------------------------------
void KBearMainWindow::setLocalPath( const QString& path ) {
	m_viewLocal->setPath( path );
}
//-----------------------------------------------
void KBearMainWindow::initViewLocal() {
	KURL u( QDir::homeDirPath() );
	SiteInfo c( u );
	c.setProtocol( "file" );
	c.setLabel( m_viewLocalCaption );

	QString whatsThis = i18n("This Window displays your local file system.\n"
												"You can use this to transfer files and folders to or "
												"from a remote host by drag and drop.");
	m_viewLocal = dynamic_cast<KBearChildView*>( createClient( c, whatsThis ) );
	m_childViewLocal = m_widgetMap[ m_viewLocal ];
	static_cast<KToggleAction*>(actionCollection()->action("show_local"))->setChecked( true );
}
//-----------------------------------------------
const KBearChildViewIface* KBearMainWindow::getCurrentView() {
	KMdiChildView* view = dynamic_cast<KMdiChildView*>( activeWindow() );
	if( ! view )
		return 0L;
	KBearChildViewIface* w = m_childViewMap[ view ];
	return w;

}
//-----------------------------------------------
const KBearChildViewIface* KBearMainWindow::getLocalView() {
	return m_viewLocal;
}
//-----------------------------------------------
DCOPRef KBearMainWindow::currentChildView() {
	DCOPRef res;
	KMdiChildView* view = dynamic_cast<KMdiChildView*>( activeWindow() );
	if( ! view )
		return res;
	KBearChildView* w = m_childViewMap[ view ];
	if( ! w )
		return res;

	return DCOPRef( kapp->dcopClient()->appId(), w->objId() );
}
//-----------------------------------------------
void KBearMainWindow::embedOutputPluginView( QWidget* view, const QString& name, const QString& toolTip ) {
	m_shared->embedOutputPluginView( view, name, toolTip );
}
//-----------------------------------------------
void KBearMainWindow::removeOutputPluginView( QWidget* view ) {
	m_shared->removeOutputPluginView( view );
}
//-----------------------------------------------
QPopupMenu * KBearMainWindow::windowPopup(KMdiChildView* pWnd, bool /*bIncludeTaskbarPopup*/ ) {
	QPopupMenu* popup = 0L;
	KBearChildView* view = m_childViewMap[ pWnd ];
	if( view ){
		popup = view->popupMenu();
	}
	return popup;
}
//-----------------------------------------------
void KBearMainWindow::raiseView(QWidget* view ) {
	KMdiChildView* v = dynamic_cast<KMdiChildView*>( view );
	if( v )
		activateView( v );
	// More to come ?
}
//-----------------------------------------------
KParts::DockMainWindow* KBearMainWindow::mainWindow() {
	return this;
}
//-----------------------------------------------
void KBearMainWindow::saveProperties( KConfig* config ) {
	QString group = config->group();
	KConfigGroupSaver cs( config, group.isEmpty() ? "General": group   );

	m_shared->saveProperties( config );

	config->setGroup("View Options");
	config->writeEntry( "Auto ChildFrameMode", m_autoChildFrameMode);
	config->writeEntry( "ChildFrameMode", m_childFrameMode );
	config->writeEntry( "MDI mode", mdiMode() );
	config->writeEntry("Maximized Childframes", isInMaximizedChildFrmMode() );
//	writeDockConfig(config, "DockState");
	m_viewLocal->saveProperties( config, "View Settings" );

	if( m_rememberTopLevelChildPos && mdiMode() == KMdi::ToplevelMode)
		saveTopChildPositions(config);

//	saveMainWindowSettings(kapp->config(), "Mainwindow");

	config->sync();
}
//-----------------------------------------------
void KBearMainWindow::readProperties( KConfig* config ) {
	m_shared->readProperties( config );
	QString group = config->group();
	KConfigGroupSaver cs( config, group.isEmpty() ? "General": group   );

	applyUISettings();

/*
	config->setGroup( "General" );
	if(m_mdiMode == KMdi::ToplevelMode) {
		m_pDockbaseAreaOfDocumentViews->setDockSite(KDockWidget::DockCorner);
		readDockConfig(config, "DockState");
		m_pDockbaseAreaOfDocumentViews->setDockSite(KDockWidget::DockNone);
	}
	else {
		readDockConfig(config, "DockState");
	}
*/
//	applyMainWindowSettings(kapp->config(), "Mainwindow");
}
//-----------------------------------------------
 void KBearMainWindow::readViewSettings() {
	KConfigGroupSaver cs( kapp->config(), kapp->config()->group() );
	QMap<KMdiChildView*,KBearChildView*>::Iterator it;
	for( it = m_childViewMap.begin(); it != m_childViewMap.end(); ++it ) {
		it.data()->readProperties( kapp->config(), "View Settings" );
	}
}
//-----------------------------------------------
void KBearMainWindow::applyUISettings() {
	KConfig* config = kapp->config();
	QString group = config->group();
	KConfigGroupSaver cs( config, group.isEmpty() ? "General": group   );

	config->setGroup("View Options");
	m_autoChildFrameMode = config->readBoolEntry( "Auto ChildFrameMode", true);
	m_childFrameMode = config->readUnsignedNumEntry( "ChildFrameMode", KBear::TileVertically );
	m_rememberTopLevelChildPos = config->readBoolEntry( "Remember Child Positions", true);
	int mdiMode = config->readNumEntry( "MDI mode", KMdi::ChildframeMode );
	switch( mdiMode ) {
		case KMdi::ToplevelMode: {
			switchToToplevelMode();
			break;
		}
		case KMdi::TabPageMode: {
			switchToTabPageMode();
			break;
		}
		default: {
			switchToChildframeMode();
		}
	}
	setChildFrameMode( m_childFrameMode ); // just to make sure the actions are checked correctly
	// restore a possible maximized Childframe mode
	bool maxChildFrmMode = config->readBoolEntry("Maximized Childframes", true);
	setEnableMaximizedChildFrmMode( maxChildFrmMode );
	if( maxChildFrmMode && activeWindow() ) {
		activeWindow()->maximize( true );
	}

	readViewSettings();
}
//-----------------------------------------------
void KBearMainWindow::showViewLocal(){
	if( m_viewLocal == 0L )
		return;

	KToggleAction* action = static_cast<KToggleAction*>(actionCollection()->action("show_local"));
	QPtrListIterator<KParts::Part> it( * API::getInstance()->partManager()->parts() );
	bool partRegistered = false;
	for( ; it.current(); ++it ) {
		if( m_viewLocal->part() == it.current() ) {
			partRegistered = true;
			break;
		}
	}
	if( action->isChecked() ) {

		if( ! partRegistered )
			API::getInstance()->partManager()->addPart( m_viewLocal->part() );
		addWindow( m_childViewLocal );

 		m_childViewLocal->show();
		m_pWinList->remove( m_childViewLocal );
		m_pWinList->prepend( m_childViewLocal ); // we always want the local view to be the first in list
		activateView( m_childViewLocal );
	}
	else if( ! action->isChecked() ) {
		if( activeWindow() == m_childViewLocal )
			activateNextWin();
		m_childViewLocal->hide();
		if( partRegistered )
			API::getInstance()->partManager()->removePart( m_viewLocal->part() );
		removeWindowFromMdi( m_childViewLocal );
	}
	setChildFrameMode( m_childFrameMode );
}
//-----------------------------------------------
 void KBearMainWindow::setupActions() {
	m_mdiModeMenu = new KActionMenu( i18n("MD&I Mode..."), actionCollection(), "window_mdimode_menu" );
	m_tileMenu = new KActionMenu( i18n("&Tile..."), actionCollection(), "window_tile_menu" );
	m_dockUndockMenu = new KActionMenu( i18n("&Dock/Undock..."), actionCollection(), "window_dock_undock_menu" );

	// Settings menu
	m_toggleTaskBar = new KToggleAction( i18n("Show &Taskbar"), 0, this, SLOT( slot_toggleTaskBar() ), actionCollection(), "show_taskbar" );

	// Window menu
	new KAction( i18n("&Minimize All"), 0, this, SLOT( iconifyAllViews() ), actionCollection(), "window_minimize_all" );
	KRadioAction* radioAction = new KRadioAction( i18n("&Toplevel mode"), CTRL+SHIFT+Key_F5, this, SLOT( switchToToplevelMode() ), actionCollection(), "mdimode_toplevel" );
	radioAction->setExclusiveGroup( "mdimode" );
	m_mdiModeMenu->insert( radioAction );
	radioAction = new KRadioAction( i18n("C&hildframe mode"), CTRL+SHIFT+Key_F6, this, SLOT( switchToChildframeMode() ), actionCollection(), "mdimode_childframe" );
	radioAction->setExclusiveGroup( "mdimode" );
	m_mdiModeMenu->insert( radioAction );
	radioAction = new KRadioAction( i18n("Ta&b Page mode"), CTRL+SHIFT+Key_F7, this, SLOT( switchToTabPageMode() ), actionCollection(), "mdimode_tabpage" );
	radioAction->setExclusiveGroup( "mdimode" );
	m_mdiModeMenu->insert( radioAction );

	KAction* tmpAction = KStdAction::redisplay( this, SLOT(switchToChildframeMode()), actionCollection(), "tile_rearrange" );
	tmpAction->setText( i18n("Re-arrange") );
	tmpAction->setShortcut( CTRL+SHIFT+Key_F8 );
	m_tileMenu->insert( tmpAction );
	m_tileMenu->popupMenu()->insertSeparator();
	radioAction = new KRadioAction( i18n("Ca&scade windows"), 0, this, SLOT( cascadeWindows() ), actionCollection(), "tile_cascade" );
	radioAction->setExclusiveGroup( "tiles" );
	m_tileMenu->insert( radioAction );
	radioAction = new KRadioAction( i18n("Cascade &maximized"), 0, this, SLOT( cascadeMaximized() ), actionCollection(), "tile_cascade_maximized" );
	radioAction->setExclusiveGroup( "tiles" );
	m_tileMenu->insert( radioAction );
	radioAction = new KRadioAction( i18n("Expand &vertically"), 0, this, SLOT( expandVertical() ), actionCollection(), "tile_expand_vertical" );
	radioAction->setExclusiveGroup( "tiles" );
	m_tileMenu->insert( radioAction );
	radioAction = new KRadioAction( i18n("Expand &horizontally"), 0, this, SLOT( expandHorizontal() ), actionCollection(), "tile_expand_horizontally" );
	radioAction->setExclusiveGroup( "tiles" );
	m_tileMenu->insert( radioAction );
	radioAction = new KRadioAction( i18n("Tile &non-overlapped"), 0, this, SLOT( tileAnodine() ), actionCollection(), "tile_anodine" );
	radioAction->setExclusiveGroup( "tiles" );
	m_tileMenu->insert( radioAction );
	radioAction = new KRadioAction( i18n("Tile overla&pped"), 0, this, SLOT( tilePragma() ), actionCollection(), "tile_pragma" );
	radioAction->setExclusiveGroup( "tiles" );
	m_tileMenu->insert( radioAction );
	radioAction = new KRadioAction( i18n("Tile v&ertically"), 0, this, SLOT( tileVertically() ), actionCollection(), "tile_vertically" );
	radioAction->setExclusiveGroup( "tiles" );
	m_tileMenu->insert( radioAction );

}
//-----------------------------------------------
void KBearMainWindow::setupToolTips(){
	m_toggleTaskBar->setToolTip( i18n("Toggle taskbar...") );
}
//-----------------------------------------------
void KBearMainWindow::createGUI( KParts::Part* part ) {
	KMdiMainFrm::createGUI( part );
	if( ! m_pWindowMenu ) {
		m_pWindowMenu = static_cast<QPopupMenu*>(guiFactory()->container("window", this));
	  	connect( m_pWindowMenu, SIGNAL(aboutToShow()), this, SLOT(fillWindowMenu()) );
	}
}
//-----------------------------------------------
KBearChildView * KBearMainWindow::findMdiChildViewByName(const QString& name ) {
	QMap<KMdiChildView*,KBearChildView*>::Iterator it;
	for( it = m_childViewMap.begin(); it != m_childViewMap.end(); ++it ) {
		if( it.data()->name() == name )
			return it.data();
	}
	return 0L;
}
//-----------------------------------------------
void KBearMainWindow::fillWindowMenu() {
	static QString windowListStr = QString::fromLatin1("window_list_");
	static QString dockUndockStr = QString::fromLatin1("dock_undock_list_)");

	m_pWindowMenu = static_cast<QPopupMenu*>(guiFactory()->container("window", this));
	bool bTabPageMode = (m_mdiMode == KMdi::TabPageMode);
	bool bNoViewOpened = m_pWinList->isEmpty();
	action("window_close")->setEnabled( ! bNoViewOpened );
	action("window_close_all")->setEnabled( ! bNoViewOpened );
	action("window_minimize_all")->setEnabled( ! bNoViewOpened && ! bTabPageMode );
	m_dockUndockMenu->setEnabled( ! bNoViewOpened && ! bTabPageMode );
	m_tileMenu->setEnabled( m_mdiMode == KMdi::ChildframeMode );

	// for all child frame windows: give an ID to every window and connect them in the end with windowMenuItemActivated()
	unplugActionList("window_list");
	QPtrListIterator<KAction> iter(m_dockUndockActions);
	for( ; iter.current(); ++iter) {
		m_dockUndockMenu->remove( iter.current() );
	}

	m_windowListActions.clear();
	m_dockUndockActions.clear();
	int i = 100;
	KMdiChildView* pView = 0L;
	QPtrListIterator<KMdiChildView> it(*m_pWinList);


	for( ; it.current(); ++it) {
		pView = it.current();
		if( pView->isToolView())
			continue;

		QString item;
		// set titles of minimized windows in brackets
		if( pView->isMinimized()) {
			item = "(";
			item += pView->caption();
			item += ")";
		}
		else {
			item = " ";
			item += pView->caption();
		}

		// insert the window entry sorted in alphabetical order
		unsigned int indx;
		unsigned int windowItemCount = m_windowListActions.count();
		bool inserted = false;
		QString tmpString = windowListStr + item;
		KRadioAction* radioAction = new KRadioAction( item, 0, pView, SLOT(slot_clickedInWindowMenu()), this, tmpString.latin1() );
         	radioAction->setChecked( pView == m_pCurrentWindow );
		KToggleAction* toggleAction = 0L;
		if( ! bNoViewOpened ) {
			tmpString = dockUndockStr + item;
			toggleAction = new KToggleAction( item, 0, pView, SLOT(slot_clickedInDockMenu()), this, tmpString.latin1() );
		}
		for( indx = 0; indx < windowItemCount; indx++) {
			tmpString = m_windowListActions.at( indx )->text();
			if( tmpString.right( tmpString.length()-2) > item.right( item.length()-2)) {
				m_windowListActions.insert( indx, radioAction );
				pView->setWindowMenuID( i );
				if( ! bTabPageMode && ! bNoViewOpened ) {
					m_dockUndockActions.insert( indx, toggleAction );
					toggleAction->setChecked( pView->isAttached() );
				}
				inserted = true;
				indx = windowItemCount+1;  // break the loop
			}
		}
		if( ! inserted ) {  // append it
			m_windowListActions.append( radioAction );
			pView->setWindowMenuID( i );
			if( ! bTabPageMode && ! bNoViewOpened ) {
				m_dockUndockActions.append( toggleAction );
				toggleAction->setChecked( pView->isAttached() );
			}
		}
		i++;
	}
	for( iter.toFirst(); iter.current(); ++iter) {
		m_dockUndockMenu->insert( iter.current() );
	}
	plugActionList("window_list", m_windowListActions );
}
//-----------------------------------------------
void KBearMainWindow::slot_toggleTaskBar() {
	KParts::DockMainWindow::statusBar()->message( m_toggleTaskBar->toolTip(), 2000 );
	m_pTaskBar->switchOn( m_toggleTaskBar->isChecked() );
}
//-----------------------------------------------
void KBearMainWindow::switchToToplevelMode() {
	if( mdiMode() == KMdi::TabPageMode ) {
		slot_toggleTaskBar();
	}
	m_toggleTaskBar->setEnabled( true );

	bool hidden = m_shared->outputToolBar()->outputFrame()->isHidden();
	makeDockVisible( m_shared->outputToolBar()->outputFrame() );

	KMdiMainFrm::switchToToplevelMode();

	if(m_rememberTopLevelChildPos)
		readAllTopChildPositions();

	m_pDockbaseAreaOfDocumentViews->setDockSite( KDockWidget::DockCorner );
	m_shared->outputToolBar()->outputFrame()->manualDock( m_pDockbaseAreaOfDocumentViews, KDockWidget::DockBottom, 70 );
	if( hidden )
		makeDockInvisible( m_shared->outputToolBar()->outputFrame() );
	else
		makeDockVisible( m_shared->outputToolBar()->outputFrame() );

	setMinimumHeight( m_oldMainFrmMinHeight);
	setMaximumHeight( m_oldMainFrmMaxHeight);
	QApplication::sendPostedEvents();
	int h = height() + m_shared->outputToolBar()->outputFrame()->height() + m_shared->outputToolBar()->height() + m_pTaskBar->height();
	if( KMainWindow::statusBar()->isHidden() )
		resize( width(), h );
	else
		resize( width(), h + KMainWindow::statusBar()->height() );
	static_cast<KRadioAction*>(action("mdimode_toplevel"))->setChecked( true );
}
//-----------------------------------------------
void KBearMainWindow::switchToTabPageMode() {
	if( isViewTaskBarOn() ) {
		slot_toggleTaskBar();
	}
	m_toggleTaskBar->setEnabled( false );

	bool hidden = m_shared->outputToolBar()->outputFrame()->isHidden();
	makeDockVisible( m_shared->outputToolBar()->outputFrame() );
	kapp->processEvents();

	KMdiMainFrm::switchToTabPageMode();

	if( hidden )
		makeDockInvisible( m_shared->outputToolBar()->outputFrame() );
	else
		makeDockVisible( m_shared->outputToolBar()->outputFrame() );

	static_cast<KRadioAction*>(action("mdimode_tabpage"))->setChecked( true );
}
//-----------------------------------------------
void KBearMainWindow::switchToChildframeMode() {
	if( mdiMode() == KMdi::TabPageMode ) {
		slot_toggleTaskBar();
	}
	m_toggleTaskBar->setEnabled( true );
	bool hidden = m_shared->outputToolBar()->outputFrame()->isHidden();

	KMdiMainFrm::switchToChildframeMode();

	int oldDockSite = m_pDockbaseAreaOfDocumentViews->dockSite();
	m_pDockbaseAreaOfDocumentViews->setDockSite( KDockWidget::DockCorner );
	m_shared->outputToolBar()->outputFrame()->manualDock( m_pDockbaseAreaOfDocumentViews, KDockWidget::DockBottom, 70 );
	if( hidden )
		makeDockInvisible( m_shared->outputToolBar()->outputFrame() );
	else
		makeDockVisible( m_shared->outputToolBar()->outputFrame() );

	if( m_autoChildFrameMode ) {
		setChildFrameMode( m_childFrameMode );
	}

	m_pDockbaseAreaOfDocumentViews->setDockSite( oldDockSite );

	static_cast<KRadioAction*>(action("mdimode_childframe"))->setChecked( true );
}
//-----------------------------------------------
void KBearMainWindow::addWindow( KMdiChildView* pWnd, int flags) {
	if( mdiMode() == KMdi::TabPageMode ) {
		bool hidden = m_shared->outputToolBar()->outputFrame()->isHidden();
		makeDockVisible( m_shared->outputToolBar()->outputFrame() );
		kapp->processEvents();

		KMdiMainFrm::addWindow( pWnd, flags );
/*
	m_pDockbaseOfTabPage->setDockSite( KDockWidget::DockCorner );
	m_shared->outputToolBar()->outputFrame()->manualDock( m_pDockbaseOfTabPage, KDockWidget::DockBottom, 70 );
*/
	if( hidden )
		makeDockInvisible( m_shared->outputToolBar()->outputFrame() );
	else
		makeDockVisible( m_shared->outputToolBar()->outputFrame() );
	}
	else {
		KMdiMainFrm::addWindow( pWnd, flags );
	}
}
//-----------------------------------------------
void KBearMainWindow::closeWindow(KMdiChildView *pWnd, bool layoutTaskBar) {
	if( mdiMode() == KMdi::TabPageMode ) {
		bool hidden = m_shared->outputToolBar()->outputFrame()->isHidden();
		makeDockVisible( m_shared->outputToolBar()->outputFrame() );
		kapp->processEvents();

		KMdiMainFrm::closeWindow( pWnd, layoutTaskBar );

		m_pDockbaseOfTabPage->setDockSite( KDockWidget::DockCorner );
		m_shared->outputToolBar()->outputFrame()->manualDock( m_pDockbaseOfTabPage, KDockWidget::DockBottom, 70 );

		if( hidden )
			makeDockInvisible( m_shared->outputToolBar()->outputFrame() );
		else
			makeDockVisible( m_shared->outputToolBar()->outputFrame() );
		}
		else {
			KMdiMainFrm::closeWindow( pWnd, layoutTaskBar );
	}
}
//-----------------------------------------------
void KBearMainWindow::setChildFrameMode( unsigned int mode ){
	if( mdiMode() != KMdi::ChildframeMode )
		return;
	switch( mode ) {
		case KBear::Cascade:
			cascadeWindows();break;
		case KBear::CascadeMaximized:
			cascadeMaximized();break;
		case KBear::ExpandVertical:
			expandVertical();break;
		case KBear::ExpandHorizontal:
			expandHorizontal();break;
		case KBear::AnodinesTile:
			tileAnodine();break;
		case KBear::PragmasTile:
			tilePragma();break;
		case KBear::TileVertically:
			tileVertically();break;
	}
}
//-----------------------------------------------
QPtrList<KBearChildViewIface> KBearMainWindow::childViews() {
	QPtrList<KBearChildViewIface> childViews;
	QMap<KMdiChildView*,KBearChildView*>::Iterator it;
	for( it = m_childViewMap.begin(); it != m_childViewMap.end(); ++it ) {
		childViews.append( it.data() );
	}
	return childViews;
}
//-----------------------------------------------
void KBearMainWindow::closeCurrentView() {
	KMdiMainFrm::closeActiveView();
}
//-----------------------------------------------
void KBearMainWindow::closeAll() {
	KMdiMainFrm::closeAllViews();
}
//-----------------------------------------------
void KBearMainWindow::cascadeWindows() {
	KMdiMainFrm::cascadeWindows();
	m_childFrameMode = KBear::Cascade;
	static_cast<KRadioAction*>(action("tile_cascade"))->setChecked( true );
}
//-----------------------------------------------
void KBearMainWindow::cascadeMaximized() {
	KMdiMainFrm::cascadeMaximized();
	m_childFrameMode = KBear::CascadeMaximized;
	static_cast<KRadioAction*>(action("tile_cascade_maximized"))->setChecked( true );
}
//-----------------------------------------------
void KBearMainWindow::expandVertical() {
	KMdiMainFrm::expandVertical();
	m_childFrameMode = KBear::ExpandVertical;
	static_cast<KRadioAction*>(action("tile_expand_vertical"))->setChecked( true );
}
//-----------------------------------------------
void KBearMainWindow::expandHorizontal() {
	KMdiMainFrm::expandHorizontal();
	m_childFrameMode = KBear::ExpandHorizontal;
	static_cast<KRadioAction*>(action("tile_expand_horizontally"))->setChecked( true );
}
//-----------------------------------------------
void KBearMainWindow::tilePragma() {
	KMdiMainFrm::tilePragma();
	m_childFrameMode = KBear::PragmasTile;
	static_cast<KRadioAction*>(action("tile_pragma"))->setChecked( true );
}
//-----------------------------------------------
void KBearMainWindow::tileAnodine() {
	KMdiMainFrm::tileAnodine();
	m_childFrameMode = KBear::AnodinesTile;
	static_cast<KRadioAction*>(action("tile_anodine"))->setChecked( true );
}
//-----------------------------------------------
void KBearMainWindow::tileVertically() {
	KMdiMainFrm::tileVertically();
	m_childFrameMode = KBear::TileVertically;
	static_cast<KRadioAction*>(action("tile_vertically"))->setChecked( true );
}
//-----------------------------------------------
void KBearMainWindow::saveTopChildPositions( KConfig* config ) {
	QValueList<int> topChildPositions;
	KConfigGroupSaver cs( config, config->group() );
	config->setGroup( "View Options" );

	for( KMdiChildView* w = m_pWinList->first(); w; w = m_pWinList->next() ) {
		QRect rect = w->restoreGeometry();
		topChildPositions.append( rect.x() );
		topChildPositions.append( rect.y() );
		topChildPositions.append( rect.width() );
		topChildPositions.append( rect.height() );
	}

	config->writeEntry( QString::fromLatin1("Toplevel Child Positions"), topChildPositions);
}
//-----------------------------------------------
void KBearMainWindow::readTopChildPositionFromIndex( unsigned int index ) {
	QValueList<int> topChildPositions;
	KConfig* config = kapp->config();
	KConfigGroupSaver cs( config, config->group() );
	config->setGroup( "View Options" );
	topChildPositions = config->readIntListEntry( QString::fromLatin1("Toplevel Child Positions") );

	KMdiChildView* child = dynamic_cast<KMdiChildView*>( m_pWinList->at(index) );

	if( child ) {
		if( topChildPositions.count() > index * 4 ) {
			child->setRestoreGeometry( QRect( topChildPositions[ 4 * index ],		// X
														topChildPositions[ 4 * index+1 ],  // Y
														topChildPositions[ 4 * index+2 ],  // width
														topChildPositions[ 4 * index+3 ] )); // height
		}
		else {
			child->setRestoreGeometry( QRect( 10, 10, 300, 400 ) );
		}
	}
}
//-----------------------------------------------
void KBearMainWindow::readAllTopChildPositions() {
	for( unsigned int i = 0; i < m_pWinList->count(); ++i )
		readTopChildPositionFromIndex( i );
}
//-----------------------------------------------
void KBearMainWindow::slotChildViewGotFocus( KMdiChildView* view ) {
	if( view == m_childViewLocal )
		emit localViewGotFocus( true );
	else
		emit localViewGotFocus( false );
}
//-----------------------------------------------
