/***************************** LICENSE START ***********************************

 Copyright 2014 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "MvQFileBrowser.h"

#include <QAction>
#include <QActionGroup>
#include <QApplication>
#include <QCloseEvent>
#include <QDebug>
#include <QDockWidget>
#include <QHBoxLayout>
#include <QLabel>
#include <QMenu>
#include <QMenuBar>
#include <QMessageBox>
#include <QSplitter>
#include <QStackedWidget>
#include <QStatusBar>
#include <QToolBar>
#include <QToolButton>
#include <QVBoxLayout>

#include "MvQAbout.h"
#include "MvQAdvancedSearch.h"
#include "MvQBookmarks.h"
#include "MvQContextMenu.h"
#include "MvQFolderDrawerPanel.h" 
#include "MvQFileDialog.h"
#include "MvQFolderHistory.h"
#include "MvQFolderNavigation.h"
#include "MvQFolderPanel.h"
#include "MvQDesktopSettings.h"
#include "MvQNewIconWidget.h"
#include "MvQIconProvider.h"
#include "MvQPathWidget.h"
#include "MvQRecentIcons.h"
#include "MvQSearchPanel.h"
#include "MvQSlider.h"
#include "MvQTools.h"

#include "MvApplication.h"
#include "MvRequest.h"
#include "FolderSettings.h"
#include "IconClass.h"
#include "Items.h"
#include "Path.h"
#include "Folder.h"
#include "Tools.h"
 
bool MvQFileBrowser::quitStarted_=false;
bool MvQFileBrowser::logoutStarted_=false;

QList<MvQFileBrowser*> MvQFileBrowser::browsers_;

MvQFileBrowser::MvQFileBrowser(QStringList relPathLst,QWidget *parent) : 
        MvQMainWindow(parent),
        ignoreSidebarAction_(false),
        ignoreIconSizeSlider_(false) 
{	 
  	setAttribute(Qt::WA_DeleteOnClose);
	
	setWindowTitle("Metview - Desktop");
	
	//Initial size
	setInitialSize(1100,800);
	
	setMovableToolBars(false);
	
	//-----------------------------
	// Layout 
	//-----------------------------
	
	QVBoxLayout *mainLayout = new QVBoxLayout;
	mainLayout->setSpacing(0); 
	mainLayout->setContentsMargins(0,0,0,0);
	
	QWidget *w=new QWidget;
	w->setLayout(mainLayout);

	setCentralWidget(w);
			
	//------------------------------
	// Central Splitter
	//------------------------------
	
	mainSplitter_=new QSplitter(this);
	mainSplitter_->setOpaqueResize(false);	
	//drawerSplitter_->addWidget(mainSplitter_);
	mainLayout->addWidget(mainSplitter_,1);
	
	//------------------------------
	// Left side
	//------------------------------
	
	sidebar_=new QStackedWidget(this);
	
	mainSplitter_->addWidget(sidebar_);
	mainSplitter_->setCollapsible(0,false);	
	
	//User bookmarks	
	bookmarksPanel_=new MvQBookmarksPanel(this);
	sidebar_->addWidget(bookmarksPanel_->widget());
		
	sidebar_->hide();
		
	//------------------------------
	// Central part
	//------------------------------

	QVBoxLayout *centralVb=new QVBoxLayout;
	centralVb->setSpacing(0); 
	centralVb->setContentsMargins(0,0,0,0);
	
	w=new QWidget;
	w->setLayout(centralVb);
	mainSplitter_->addWidget(w);
	mainSplitter_->setStretchFactor(1,1);
			
	//Folder panel to store all the widgets
	folderPanel_=new MvQFolderPanel(this);
	centralVb->addWidget(folderPanel_);
		
	connect(folderPanel_,SIGNAL(currentWidgetChanged()),
		this,SLOT(slotCurrentFolderChanged()));
	
	connect(folderPanel_,SIGNAL(pathChanged()),
		this,SLOT(slotPathChanged()));
	
	connect(folderPanel_,SIGNAL(itemInfoChanged(QString)),
		this,SLOT(slotItemInfo(QString)));	
		
	
	//Search panel below the folders	
	searchPanel_=new MvQFolderSearchPanel(this);
	centralVb->addWidget(searchPanel_);
	
	connect(searchPanel_,SIGNAL(find(FolderSearchData*)),
		folderPanel_,SLOT(slotFindIcons(FolderSearchData*)));
	
	searchPanel_->hide();
		
	//Init splitters	
	mainSplitter_->setCollapsible(1,false);

	int spWidth=mainSplitter_->size().width();
	if(spWidth > 0)
	{
		QList<int> spSize;
		spSize << 150;
		spSize << spWidth-spSize[0];
		mainSplitter_->setSizes(spSize);
	}
	
	
	//-----------------------------
	// Bottom part  -- drawers
	//-----------------------------
	
	drawerPanel_=new MvQFolderDrawerPanel(this);
	mainLayout->addWidget(drawerPanel_);
	
	connect(drawerPanel_,SIGNAL(itemEntered(QString)),
		this, SLOT(slotItemInfo(QString)));
	
	//--------------------------------------
	// Setup actions for toolbars and menus
	//--------------------------------------
	
	setupFileActions();
	setupEditActions();
	setupNavigateActions();
	setupViewActions();
	setupBookmarksActions();
	setupHistoryActions();
	setupToolsActions();
	setupHelpActions();

	setupMenus(menuItems_);
	
	//----------------------------------------------------
	// Add history menu to folder panel. Need to do it after
	// the menus were created!!!
	//-----------------------------------------------------

	folderPanel_->setHistoryMenu(findMenu(MvQMainWindow::HistoryMenu));
	
	MvQBookmarksMenu *bookmarksMenu=new MvQBookmarksMenu(this,findMenu(MvQMainWindow::BookmarksMenu));
	connectBookmarksObject(bookmarksMenu);	
	connectBookmarksObject(bookmarksPanel_);
	
	connect(searchPanel_,SIGNAL(iconSelected(IconObject*)),
		folderPanel_,SLOT(slotShowIconInCurrent(IconObject*)));
		
	//Setup
	//updateNavigationActionState();	
	
	//-----------------------------
	// Statusbar
	//-----------------------------
	
	itemInfoLabel_=new QLabel(this);
	statusBar()->addWidget(itemInfoLabel_);
		
	setupIconSizeWidget();
	
	if(relPathLst.count() > 0)
	  	folderPanel_->resetWidgets(relPathLst);
    
	connect(qApp,SIGNAL(commitDataRequest(QSessionManager&)),
			this,SLOT(slotCommitDataRequest(QSessionManager&)),Qt::DirectConnection);
}

MvQFileBrowser::~MvQFileBrowser()
{
}

//Show the brower for the first time!
void MvQFileBrowser::showIt()
{
  	show();
	
	//Minimise the drawer panel!
	drawerPanel_->shrink();
}	

//==============================================================
//
//  Close and quit
//
//==============================================================

void MvQFileBrowser::closeEvent(QCloseEvent* event)
{
	qDebug() << "closeEvent";
    
    if(MvQFileBrowser::aboutToClose(this))
	{	
		browsers_.removeOne(this);
		saveFolderInfo();		
		event->accept();
		//deleteLater();
	}
	else
	{
	  	event->ignore();
	}	
}
 
void MvQFileBrowser::slotQuit()
{
	 MvQFileBrowser::aboutToQuit(this);  
}  


//This slot is called when the window mangager quits to ask the app to
//close in a correct way. We set the logoutStarted_ flag to indicate that 
//this happened. 
void MvQFileBrowser::slotCommitDataRequest(QSessionManager& manager)
{
	qDebug() << "commit";    
	logoutStarted_=true;
}

//==============================================================
//
//  Set up actions
//
//==============================================================


void MvQFileBrowser::setupFileActions()
{
	QAction* ac=new QAction(this);
	ac->setToolTip(tr("Open a new tab"));
	ac->setText(tr("New &tab"));
        ac->setShortcut(tr("Ctrl+T"));
	QAction *newTabAction=ac;
	
	connect(newTabAction,SIGNAL(triggered(bool)),
		folderPanel_,SLOT(slotNewTab(bool)));
  			
	ac=new QAction(this);
	ac->setToolTip(tr("Open a new window"));
	ac->setText(tr("New &window"));
        //ac->setShortcut(tr("Ctrl+N"));
	QAction *newWinAction=ac;
	
	connect(newWinAction,SIGNAL(triggered(bool)),
		folderPanel_,SLOT(slotNewWindow(bool)));	
			
  	//Close
	QAction *closeAction=createAction(MvQMainWindow::CloseAction,this);
	connect(closeAction,SIGNAL(triggered()),
		this,SLOT(close()));
				
	//Quit application
	QAction *quitAction=createAction(MvQMainWindow::QuitAction,this);
	connect(quitAction,SIGNAL(triggered()),
		this,SLOT(slotQuit()));	
	
				
	MvQMainWindow::MenuType menuType=MvQMainWindow::FileMenu;

	QAction *sep=new QAction(this);
	sep->setSeparator(true);
	
	menuItems_[menuType].push_back(new MvQMenuItem(newTabAction,MvQMenuItem::MenuTarget));	
	menuItems_[menuType].push_back(new MvQMenuItem(newWinAction,MvQMenuItem::MenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(sep,MvQMenuItem::MenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(closeAction,MvQMenuItem::MenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(quitAction,MvQMenuItem::MenuTarget));
}

void MvQFileBrowser::setupEditActions()
{
	/*QAction *actionSearch=MvQMainWindow::createAction(MvQMainWindow::FindAction,this);
	connect(actionSearch,SIGNAL(triggered(bool)),
		searchPanel_,SLOT(openPanel(bool)));
				
	QAction *actionSearchNext=MvQMainWindow::createAction(MvQMainWindow::FindNextAction,this);
	connect(actionSearchNext,SIGNAL(triggered()),
		searchPanel_,SLOT(slotFindNext()));	
		
	QAction *actionSearchPrev=MvQMainWindow::createAction(MvQMainWindow::FindPreviousAction,this);
	connect(actionSearchPrev,SIGNAL(triggered()),
		searchPanel_,SLOT(slotFindPrev()));
	
	
	//Add actions to menu and toolbar	
	MvQMainWindow::MenuType menuType=MvQMainWindow::EditMenu;
	
	menuItems_[menuType].push_back(new MvQMenuItem(actionSearch,MvQMenuItem::MenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(actionSearchNext,MvQMenuItem::MenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(actionSearchPrev,MvQMenuItem::MenuTarget));*/
			
	//Icon object actions	
	/*MvQContextItemSet set("DesktopMain");
	QActionGroup *iconObjAg=new QActionGroup(this);
		
	foreach(MvQContextItem *item,set.icon())
	{
		if(QAction *ac=static_cast<QAction*>(item))
		{	
		  	iconObjAg->addAction(ac);
			folderPanel_->addIconAction(ac);
			menuItems_[menuType].push_back(new MvQMenuItem(ac,MvQMenuItem::MenuTarget));
		}
	}
	
	connect(iconObjAg,SIGNAL(triggered(QAction*)),
		folderPanel_,SLOT(slotIconCommand(QAction*)));*/
}

void MvQFileBrowser::setupNavigateActions()
{  
	//Back
	actionBack_ = new QAction(this);
	actionBack_->setIcon(QPixmap(QString::fromUtf8(":/desktop/big_arrow_left.svg"))); 
        actionBack_->setToolTip(tr("Back"));
	actionBack_->setText(tr("&Back"));
        actionBack_->setShortcut(tr("Alt+Left"));

	connect(actionBack_,SIGNAL(triggered()),
		folderPanel_,SLOT(slotChFolderBack()));

	//Forward
	actionForward_ = new QAction(this);
	actionForward_->setIcon(QPixmap(QString::fromUtf8(":/desktop/big_arrow_right.svg"))); 
	actionForward_->setToolTip(tr("Forward"));
	actionForward_->setText(tr("&Forward"));
        actionForward_->setShortcut(tr("Alt+Right"));

	connect(actionForward_,SIGNAL(triggered()),
		folderPanel_,SLOT(slotChFolderForward()));

	//Parent
	actionParent_= new QAction(this);
	actionParent_->setIcon(QPixmap(QString::fromUtf8(":/desktop/big_arrow_up.svg"))); 
        actionParent_->setToolTip(tr("Up"));
	actionParent_->setText(tr("&Up"));
	actionParent_->setIconText(tr("Up"));
        actionParent_->setShortcut(tr("Alt+Up"));

	connect(actionParent_,SIGNAL(triggered()),
		folderPanel_,SLOT(slotChFolderParent()));
				
	//Home
	actionMvHome_= new QAction(this);
	actionMvHome_->setIcon(QPixmap(QString::fromUtf8(":/desktop/home.svg")));
        actionMvHome_->setToolTip(tr("Metview home"));
	actionMvHome_->setText(tr("Mv &home"));
	actionMvHome_->setIconText(tr("home"));
        actionMvHome_->setShortcut(tr("Alt+Home"));

	connect(actionMvHome_,SIGNAL(triggered()),
		folderPanel_,SLOT(slotChFolderMvHome()));
		
	//Wastebin
	actionWastebasket_= new QAction(this);
	actionWastebasket_->setIcon(QPixmap(QString::fromUtf8(":/desktop/wastebasket.svg")));
        actionWastebasket_->setToolTip(tr("&Wastebasket"));
	actionWastebasket_->setText(tr("Wastebasket"));
	actionWastebasket_->setIconText(tr("Wastebasket"));
        actionWastebasket_->setShortcut(tr("Alt+W"));

	connect(actionWastebasket_,SIGNAL(triggered()),
		folderPanel_,SLOT(slotChFolderWastebasket()));	
			
	//Breadcrumbs
	breadcrumbs_=new MvQPathWidget(this);
	
	connect(breadcrumbs_,SIGNAL(dirChanged(QString)),
		folderPanel_,SLOT(slotChFolderFromBreadcrumbs(QString)));
					
	connect(breadcrumbs_,SIGNAL(commandRequested(QString,QString)),
		folderPanel_,SLOT(slotPathCommand(QString,QString)));
			
	QAction *sep=new QAction(this);
	sep->setSeparator(true);
	
	MvQMainWindow::MenuType menuType=MvQMainWindow::NavigateMenu;
	
	menuItems_[menuType].push_back(new MvQMenuItem(actionBack_));
	menuItems_[menuType].push_back(new MvQMenuItem(actionForward_));
	menuItems_[menuType].push_back(new MvQMenuItem(actionParent_));
	menuItems_[menuType].push_back(new MvQMenuItem(sep,MvQMenuItem::MenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(actionMvHome_,MvQMenuItem::MenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(actionWastebasket_,MvQMenuItem::MenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(breadcrumbs_,MvQMenuItem::ToolBarTarget));
	//menuItems_[menuType].push_back(new MvQMenuItem(locationCombo_,MvQMenuItem::ToolBarTarget));
	
	breadcrumbs_->setPath("/");
} 

void MvQFileBrowser::setupBookmarksActions()
{	
	//We need at least one action to create the menu. We will populati it later dinamically
  	QAction *action=0;

	MvQMainWindow::MenuType menuType=MvQMainWindow::BookmarksMenu;	
	menuItems_[menuType].push_back(new MvQMenuItem(action,MvQMenuItem::MenuTarget));
}

void MvQFileBrowser::setupHistoryActions()
{	
	//We need at least one action to create the menu. We will populati it later dinamically
  	QAction *action=0;

	MvQMainWindow::MenuType menuType=MvQMainWindow::HistoryMenu;	
	menuItems_[menuType].push_back(new MvQMenuItem(action,MvQMenuItem::MenuTarget));
}
		
void MvQFileBrowser::setupViewActions()
{		
	QAction *action;
	
	//--------------
	// View mode
	//--------------
	
	QList<QAction*> viewModeLst;
	
	QMenu* viewModeMenu=new QMenu(this);
	viewModeMenu->setObjectName(QString::fromUtf8("viewModeSubMenu"));
	viewModeMenu->setTitle(tr("&View mode"));
		
        action = new QAction(this);
        action->setObjectName(QString::fromUtf8("actionIconView"));
        action->setCheckable(true);
	action->setIcon(QPixmap(":/desktop/icon_view.svg"));
	action->setText(tr("&Classic icon"));
	action->setToolTip(tr("Classic icon view"));
	action->setShortcut(tr("Ctrl+1"));
	
	actionViewMode_[Desktop::IconViewMode]=action;

	action = new QAction(this);
        action->setObjectName(QString::fromUtf8("actionSimpleView"));
        action->setCheckable(true);
	action->setIcon(QPixmap(":/desktop/simple_view.svg"));
	action->setText(tr("&Simple icon"));
	action->setToolTip(tr("Simple icon view"));
	action->setShortcut(tr("Ctrl+2"));
	
	actionViewMode_[Desktop::SimpleViewMode]=action;
	
	action=new QAction(this);
        action->setObjectName(QString::fromUtf8("actionDetailedView"));
        action->setCheckable(true);
	action->setIcon(QPixmap(":/desktop/detailed_view.svg"));
	action->setText(tr("&Detailed"));
	action->setToolTip(tr("Detailed view"));
	action->setShortcut(tr("Ctrl+3"));
	
	actionViewMode_[Desktop::DetailedViewMode]=action;
	
	//-------------
	// Sorting
	//-------------
	
	gridMenu_=new QMenu(this);
	gridMenu_->setObjectName(QString::fromUtf8("gridSubMenu"));
	gridMenu_->setTitle(tr("&Arrange on grid by ..."));
	
	action = new QAction(this);
	action->setText(tr("&Name"));
	action->setData("toGridByName");
	folderPanel_->addDesktopAction(action);
	QAction* actionGridByName=action;
			
	action = new QAction(this);
	action->setText(tr("&Size"));
	action->setData("toGridBySize");
	folderPanel_->addDesktopAction(action);
	QAction* actionGridBySize=action;
	
	action = new QAction(this);
	action->setText(tr("&Type"));
	action->setData("toGridByType");
	folderPanel_->addDesktopAction(action);
	QAction* actionGridByType=action;
	
	connect(actionGridByName,SIGNAL(triggered(bool)),
		folderPanel_,SLOT(slotGridByName(bool)));
	
	connect(actionGridBySize,SIGNAL(triggered(bool)),
		folderPanel_,SLOT(slotGridBySize(bool)));	
	
	connect(actionGridByType,SIGNAL(triggered(bool)),
		folderPanel_,SLOT(slotGridByType(bool)));
		
	//-------------------------
	// Misc
	//-------------------------	 
		
	action = new QAction(this);
        action->setObjectName(QString::fromUtf8("actionReload"));
	action->setText(tr("&Reload"));
        action->setIcon(QPixmap(QString::fromUtf8(":/desktop/reload.svg")));
	action->setShortcut(tr("F5"));				
	action->setData("reload");
	folderPanel_->addDesktopAction(action);
	QAction* actionReload=action;	
	
	connect(actionReload, SIGNAL(triggered(bool)),
		 folderPanel_, SLOT(slotReload(bool)));
	
		 
	action = new QAction(this);
        action->setObjectName(QString::fromUtf8("actionShowlast"));
	action->setText(tr("Show &last icon created"));
        //action->setIcon(QPixmap(QString::fromUtf8(":/desktop/reload.svg")));
	//action->setShortcut(tr("F5"));				
	action->setData("showLastIcon");
	folderPanel_->addDesktopAction(action);
	QAction* actionLastIcon=action;	
	
	connect(actionLastIcon, SIGNAL(triggered(bool)),
		folderPanel_, SLOT(slotShowLastCreated(bool)));	 
	
	//Add reload action to the breadcrumbs
	breadcrumbs_->setReloadAction(actionReload);
				
	//-----------------------------------
	// Sidebars. The order matters!!!!!
	//-----------------------------------
	
	sidebarAg_=new QActionGroup(this);
	sidebarAg_->setExclusive(false);	
	
	//Bookmarks
	action = new QAction(this);
        action->setObjectName(QString::fromUtf8("actionSidebar"));
        action->setCheckable(true);
	action->setChecked(false); //!!!
	action->setText(tr("&Bookmarks"));
        action->setIcon(QPixmap(QString::fromUtf8(":/desktop/bookmark.svg")));
	action->setShortcut(tr("Ctrl+B"));
	sidebarAg_->addAction(action);
	
	connect(bookmarksPanel_,SIGNAL(closePanel()),
		this,SLOT(slotCloseSidebar()));
									
	connect(sidebarAg_,SIGNAL(triggered(QAction*)),
		this,SLOT(slotSidebar(QAction*)));
		
	//-------------------------------
	// Bottom part
	//-------------------------------
	
	//Drawers
	actionDrawers_ = new QAction(this);
        actionDrawers_->setObjectName(QString::fromUtf8("actionDrawers"));
        actionDrawers_->setCheckable(true);
	actionDrawers_->setChecked(true); //!!!
	actionDrawers_->setText(tr("&Drawers"));
        actionDrawers_->setIcon(QPixmap(QString::fromUtf8(":/desktop/drawer.svg")));
	//actionDrawers_->setShortcut(tr("Ctrl+"));
	
	connect(actionDrawers_,SIGNAL(toggled(bool)),
		drawerPanel_,SLOT(setVisible(bool)));
	
	//Statusbar
	actionStatusbar_ = new QAction(this);
        actionStatusbar_->setObjectName(QString::fromUtf8("actionStatusbar"));
        actionStatusbar_->setCheckable(true);
	actionStatusbar_->setChecked(true); //!!!
	actionStatusbar_->setText(tr("S&tatusbar"));       
	actionStatusbar_->setIcon(QPixmap(QString::fromUtf8(":/desktop/statusbar.svg")));
	//actionStatusbar_->setShortcut(tr("Ctrl+"));
	
	connect(actionStatusbar_,SIGNAL(toggled(bool)),
		statusBar(),SLOT(setVisible(bool)));	
		
	//-------------------------
	// Icon resize
	//-------------------------
	
	const vector<int>& sVec=MvQIconProvider::sizes();
	for(vector<int>::const_iterator it=sVec.begin(); it != sVec.end(); it++)
	{
		iconSizes_ << *it;
	}

	action=new QAction(this);
	action->setText(tr("De&crease size"));
        action->setIcon(QIcon(QPixmap(QString::fromUtf8(":/desktop/size_down.svg"))));
	action->setShortcut(tr("Ctrl+-"));
	action->setData("sizeDown");
	folderPanel_->addDesktopAction(action);
	actionIconSizeDown_=action;
	
	action=new QAction(this);
	action->setText(tr("&Increase size"));
	action->setIcon(QIcon(QPixmap(QString::fromUtf8(":/desktop/size_up.svg"))));
	action->setShortcut(tr("Ctrl++"));
	action->setData("sizeUp");
	folderPanel_->addDesktopAction(action);
	actionIconSizeUp_=action;	
	
	//Folder settings
	
	action=new QAction(this);
	action->setText(tr("Apply icon size to all open folders"));
	action->setToolTip(tr("Apply icon size to all open folders"));
	action->setIcon(QIcon(QPixmap(QString::fromUtf8(":/desktop/use_global_iconsize.svg"))));
	action->setData("sizeGlobal");
	action->setCheckable(false);
	folderPanel_->addDesktopAction(action);
	actionGlobalIconSize_=action;
		
	action=new QAction(this);
	action->setText(tr("Save view settings as default"));
	action->setToolTip(tr("Save view settings as default"));
	action->setData("saveView");
	action->setCheckable(false);
	folderPanel_->addDesktopAction(action);
	actionSaveViewAsDefault_=action;
	
	action=new QAction(this);
	action->setText(tr("Revert view settings to default"));
	action->setToolTip(tr("Revert view settings to default"));
	action->setData("revertView");
	action->setCheckable(false);
	folderPanel_->addDesktopAction(action);
	actionRevertViewToDefault_=action;
		
	connect(actionIconSizeDown_,SIGNAL(triggered()),
		this,SLOT(slotIconSizeDown()));

	connect(actionIconSizeUp_,SIGNAL(triggered()),
		this,SLOT(slotIconSizeUp()));
		
	//It is important to use triggered because it will not emit a signal if
	//setChecked is called!
	connect(actionGlobalIconSize_,SIGNAL(triggered()),
		this,SLOT(slotGlobalIconSize()));
		
	connect(actionSaveViewAsDefault_,SIGNAL(triggered()),
		this,SLOT(slotSaveViewAsDefault()));
		
	connect(actionRevertViewToDefault_,SIGNAL(triggered()),
		this,SLOT(slotRevertViewToDefault()));	
		
	QAction *sep=new QAction(this);
	sep->setSeparator(true);
	
	QAction *sep1=new QAction(this);
	sep1->setSeparator(true);
	
	QAction *sep2=new QAction(this);
	sep2->setSeparator(true);
	
	QAction *sep3=new QAction(this);
	sep3->setSeparator(true);
	
	//Build menuitems
	
	
	MvQMainWindow::MenuType menuType=MvQMainWindow::ViewMenu;
	
	menuItems_[menuType].push_back(new MvQMenuItem(viewModeMenu));
	
	foreach(QAction* ac,actionViewMode_.values())
	{  
		menuItems_[menuType].push_back(new MvQMenuItem(ac,MvQMenuItem::SubMenuTarget | MvQMenuItem::ToolBarTarget));
	} 
	
	menuItems_[menuType].push_back(new MvQMenuItem(gridMenu_));
	menuItems_[menuType].push_back(new MvQMenuItem(actionGridByName,MvQMenuItem::SubMenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(actionGridBySize,MvQMenuItem::SubMenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(actionGridByType,MvQMenuItem::SubMenuTarget));
	
	menuItems_[menuType].push_back(new MvQMenuItem(sep));

	menuItems_[menuType].push_back(new MvQMenuItem(actionReload,MvQMenuItem::MenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(actionLastIcon,MvQMenuItem::MenuTarget));
	
	menuItems_[menuType].push_back(new MvQMenuItem(sep1));
	menuItems_[menuType].push_back(new MvQMenuItem(actionGlobalIconSize_,MvQMenuItem::MenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(actionSaveViewAsDefault_,MvQMenuItem::MenuTarget));
	
	menuItems_[menuType].push_back(new MvQMenuItem(sep2,MvQMenuItem::MenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(actionIconSizeDown_,MvQMenuItem::MenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(actionIconSizeUp_,MvQMenuItem::MenuTarget));

	menuItems_[menuType].push_back(new MvQMenuItem(sep3,MvQMenuItem::MenuTarget));

	if(sidebarAg_->actions().count() > 1)
	{  
		QMenu* sidebarMenu=new QMenu(this);
		sidebarMenu->setObjectName(QString::fromUtf8("sidebarSubMenu"));
		sidebarMenu->setTitle(tr("Side&bar"));	
	
		menuItems_[menuType].push_back(new MvQMenuItem(sidebarMenu));
		foreach(QAction* ac,sidebarAg_->actions())
		{  
			menuItems_[menuType].push_back(new MvQMenuItem(ac,MvQMenuItem::SubMenuTarget));
		} 
	}
	else
	{ 	
		menuItems_[menuType].push_back(new MvQMenuItem(sidebarAg_->actions().at(0)));
	} 
	
	menuItems_[menuType].push_back(new MvQMenuItem(actionDrawers_,MvQMenuItem::MenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(actionStatusbar_,MvQMenuItem::MenuTarget));
	
	//Viewmode action group
	
	viewModeAg_=new QActionGroup(this);
	viewModeAg_->setExclusive(true);
	foreach(QAction* ac,actionViewMode_.values())
	{  
		viewModeAg_->addAction(ac);
	}

	connect(viewModeAg_,SIGNAL(triggered(QAction*)),
		this,SLOT(slotChangeViewMode(QAction*)));
			
}

void MvQFileBrowser::setupToolsActions()
{				
	QAction *actionLog = new QAction(this);
	actionLog->setIcon(QPixmap(":/desktop/log.svg")); 
        actionLog->setToolTip(tr("Log"));
	actionLog->setText(tr("Log..."));

	connect(actionLog,SIGNAL(triggered()),
		this,SLOT(slotLog()));
			
	QList<QAction*> lst;	
	Tools::make(lst,this);	

	//Preferences
	QAction *actionPref = new QAction(this);
	actionPref->setIcon(QPixmap(":/desktop/configure.svg")); 
        actionPref->setToolTip(tr("Preferences"));
	actionPref->setText(tr("Preferences..."));

	connect(actionPref,SIGNAL(triggered()),
		this,SLOT(slotPreferences()));
						
	//Icon filter
	QAction *actionFilter = new QAction(this);
	actionFilter->setIcon(QPixmap(":/desktop/filter.svg")); 
        actionFilter->setToolTip(tr("Show icon filter bar"));
	actionFilter->setText(tr("Icon filter bar"));
	actionFilter->setShortcut(tr("Ctrl+F"));
 	actionFilter->setCheckable(true);
	actionFilter->setChecked(false);
	
	connect(actionFilter,SIGNAL(toggled(bool)),
		searchPanel_,SLOT(openPanel(bool)));
	
	connect(searchPanel_,SIGNAL(panelClosed()),
		actionFilter,SLOT(toggle()));	
		
		
	QAction *actionFilterNext = new QAction(this);
	actionFilterNext->setIcon(QPixmap(":/desktop/arrow_down.svg")); 
        actionFilterNext->setToolTip(tr("Show next filtered icon"));
	actionFilterNext->setText(tr("Filter show next"));
	actionFilterNext->setShortcut(tr("F3"));
	actionFilterNext->setEnabled(false);
	
	connect(actionFilterNext,SIGNAL(triggered()),
		searchPanel_,SLOT(slotFindNext()));
		
	QAction *actionFilterPrev = new QAction(this);
	actionFilterPrev->setIcon(QPixmap(":/desktop/arrow_up.svg")); 
        actionFilterPrev->setToolTip(tr("Show previous filtered icon"));
	actionFilterPrev->setText(tr("Filter show previous"));
	actionFilterPrev->setShortcut(tr("Shift+F3"));
	actionFilterPrev->setEnabled(false);
	
	connect(actionFilter,SIGNAL(toggled(bool)),
		actionFilterNext,SLOT(setEnabled(bool)));
	
	connect(actionFilter,SIGNAL(toggled(bool)),
		actionFilterPrev,SLOT(setEnabled(bool)));
				
	//Find
	QAction *actionFind = new QAction(this);
	actionFind->setIcon(QPixmap(":/desktop/search.svg")); 
        actionFind->setToolTip(tr("Search icons"));
	actionFind->setText(tr("Search icons..."));
	actionFind->setShortcut(tr("Ctrl+Alt+F"));
	
	connect(actionFind,SIGNAL(triggered()),
		this,SLOT(slotAdvancedSearch()));
	
	
	//Add actions to menus and toolbars
	MvQMainWindow::MenuType menuType=MvQMainWindow::ToolsMenu;
	
	menuItems_[menuType].push_back(new MvQMenuItem(actionLog,MvQMenuItem::MenuTarget)); 
	
	QAction *sep=new QAction(this);
	sep->setSeparator(true);
	menuItems_[menuType].push_back(new MvQMenuItem(sep,MvQMenuItem::MenuTarget));
		
	menuItems_[menuType].push_back(new MvQMenuItem(actionFilter,MvQMenuItem::MenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(actionFilterNext,MvQMenuItem::MenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(actionFilterPrev,MvQMenuItem::MenuTarget));
	
	QAction *sep1=new QAction(this);
	sep1->setSeparator(true);
	menuItems_[menuType].push_back(new MvQMenuItem(sep1,MvQMenuItem::MenuTarget));
	
	menuItems_[menuType].push_back(new MvQMenuItem(actionFind,MvQMenuItem::MenuTarget));
	
	foreach(QAction* ac,lst)
	{
	  	menuItems_[menuType].push_back(new MvQMenuItem(ac,MvQMenuItem::MenuTarget)); 
	}
	
	QAction *sep2=new QAction(this);
	sep2->setSeparator(true);
	menuItems_[menuType].push_back(new MvQMenuItem(sep2,MvQMenuItem::MenuTarget));
	
	menuItems_[menuType].push_back(new MvQMenuItem(actionPref,MvQMenuItem::MenuTarget));
}

void MvQFileBrowser::setupHelpActions()
{		
    	// About
    	QAction *actionAbout = new QAction(this);
    	actionAbout->setObjectName(QString::fromUtf8("actionAbout"));
    	QIcon icon;
    	icon.addPixmap(QPixmap(QString::fromUtf8(":/window/metview_logo")), QIcon::Normal, QIcon::Off);
    	actionAbout->setIcon(icon);
    	actionAbout->setText(tr("&About ") +  "Desktop");

	connect(actionAbout, SIGNAL(triggered()), this, SLOT(slotShowAboutBox()));

	MvQMainWindow::MenuType menuType=MvQMainWindow::HelpMenu;	
	menuItems_[menuType].push_back(new MvQMenuItem(actionAbout,MvQMenuItem::MenuTarget));
}


void MvQFileBrowser::setupIconSizeWidget()
{
	//Descrease size
	QToolButton *tb=new QToolButton(this);
	tb->setDefaultAction(actionIconSizeDown_);
	tb->setAutoRaise(true);
	statusBar()->addPermanentWidget(tb);
	
	//Slider
	iconSizeSlider_=new MvQSlider(this);
	iconSizeSlider_->setOrientation(Qt::Horizontal);	
	iconSizeSlider_->setRange(0,iconSizes_.count()-1);
	//int index=iconSizes_.indexOf(currentIconSize_);
	//iconSizeSlider_->setValue(index);
	iconSizeSlider_->setMaximumWidth(90);
	statusBar()->addPermanentWidget(iconSizeSlider_);
	
	connect(iconSizeSlider_,SIGNAL(valueChanged(int)),
		this,SLOT(slotSetIconSizeByIndex(int)));
		
	//Increase size
	tb=new QToolButton(this);
	tb->setDefaultAction(actionIconSizeUp_);
	tb->setAutoRaise(true);
	statusBar()->addPermanentWidget(tb);
	
	//Global size
	tb=new QToolButton(this);	
	tb->setAutoRaise(true);
	tb->setIcon(QIcon(QPixmap(QString::fromUtf8(":/desktop/configure.svg"))));
	tb->setPopupMode(QToolButton::InstantPopup);
	tb->addAction(actionGlobalIconSize_);
	tb->addAction(actionSaveViewAsDefault_);
	tb->addAction(actionRevertViewToDefault_);	
	statusBar()->addPermanentWidget(tb);
}

void MvQFileBrowser::slotCurrentFolderChanged()
{
	 breadcrumbs_->setPath(folderPanel_->currentFolder());
  	 slotUpdateNavigationActions(folderPanel_->folderNavigation());
	 updateViewModeStatus(folderPanel_->viewMode());	 
	 updateIconSizeActionState();
	 updateSearchPanel();	
	 
	 //Update window title
	 updateWindowTitle();
}  

void MvQFileBrowser::slotPathChanged()
{
	 breadcrumbs_->setPath(folderPanel_->currentFolder());
  	 slotUpdateNavigationActions(folderPanel_->folderNavigation());
	 updateViewModeStatus(folderPanel_->viewMode());	 
	 updateIconSizeActionState();
	 //updateSearchPanel();	
	 
	 //Update window title
	updateWindowTitle();
}  

void MvQFileBrowser::updateWindowTitle()
{ 
	QString txt;
	if(Folder *f=folderPanel_->currentFolder())
	{
	  	txt=QString::fromStdString(f->name());
		if(f->parent())
	 		txt+=" - " + QString::fromStdString(f->parent()->fullName());
		
		txt+=" - Metview";
	}
	else
	  	txt="Metview";
	setWindowTitle(txt);
}

void MvQFileBrowser::slotUpdateNavigationActions(MvQFolderNavigation *nav)
{
	if(!nav)
		return;
	
	nav->print();
	
	breadcrumbs_->setPath(folderPanel_->currentFolder());	
	updateIconSizeActionState();
	
  	if(nav->hasPrev())
	{
		actionBack_->setEnabled(true);
	}
	else
	{
		actionBack_->setEnabled(false);
	}
	
	if(nav->hasNext())
	{
		actionForward_->setEnabled(true);
	}
	else
	{
		actionForward_->setEnabled(false);
	}

	if(nav->current() == "" || nav->current() == "/")
	{
		actionParent_->setEnabled(false);
	}
	else{
		actionParent_->setEnabled(true);
	}
	
	nav->print();
}

void MvQFileBrowser::slotChangeViewMode(QAction* action)
{
  	Desktop::FolderViewMode mode=actionViewMode_.key(action);

	folderPanel_->setViewMode(mode);
	gridMenu_->setEnabled(folderPanel_->viewModeGrid());
}

void MvQFileBrowser::updateViewModeStatus(Desktop::FolderViewMode mode)
{
	if(actionViewMode_.find(mode) != actionViewMode_.end())
	{
	  	actionViewMode_[mode]->setChecked(true);
	}	
}


void MvQFileBrowser::slotItemInfo(QString msg)
{ 
	itemInfoLabel_->setText(msg);  
}  

void MvQFileBrowser::slotPreferences()
{
	IconObject* obj = Items::find("general");
	if(obj) obj->edit(); 
} 

void MvQFileBrowser::slotLog()
{
	Folder::top()->showLog();
} 

void MvQFileBrowser::slotAdvancedSearch()
{
	MvQAdvancedSearchDialog::open(this,folderPanel_->currentFolder());
} 

//=============================================
//
// Bookmarks
//
//=============================================

void MvQFileBrowser::connectBookmarksObject(MvQBookmarks *bk)
{ 
	connect(bk,SIGNAL(openInBrowser(QString)),
		this,SLOT(slotOpenInBrowser(QString)));

	connect(bk,SIGNAL(openInTab(QString)),
		this,SLOT(slotOpenInTab(QString)));
		
	connect(bk,SIGNAL(openInWin(QString)),
		this,SLOT(slotOpenInWin(QString)));
		
	connect(bk,SIGNAL(openGroupInTabs(QStringList)),
		this,SLOT(slotOpenInTabs(QStringList)));	

	connect(bk,SIGNAL(openGroupInWin(QStringList)),
		this,SLOT(slotOpenGroupInWin(QStringList)));
		
	connect(bk,SIGNAL(bookmarkFolder()),
		this,SLOT(slotBookmarkFolder()));	
		
	connect(bk,SIGNAL(bookmarkTabs()),
		this,SLOT(slotBookmarkTabs()));	
}

void MvQFileBrowser::slotOpenInBrowser(QString fullName)
{
  	folderPanel_->slotChFolderFromBookmarks(fullName);
}

void MvQFileBrowser::slotOpenInTab(QString fullName)
{
	folderPanel_->addWidget(fullName);
}

void MvQFileBrowser::slotOpenInWin(QString fullName)
{
  	MvQFileBrowser::openBrowser(fullName);
}

void MvQFileBrowser::slotOpenInTabs(QStringList lst)
{
	folderPanel_->resetWidgets(lst);
}

void MvQFileBrowser::slotOpenGroupInWin(QStringList lst)
{
	MvQFileBrowser::openBrowser(lst);
}

void MvQFileBrowser::slotBookmarkFolder()
{
	MvQBookmarks::addItem(folderPanel_->currentFolder());  
}

void MvQFileBrowser::slotBookmarkTabs()
{
	MvQBookmarks::addItem(folderPanel_->currentFolders()); 
}

//---------------------------------------FolderSettings::setDefaults(folderPanel_->viewMode(),folderPanel_->iconSize());
// Sidebar
//---------------------------------------
	
void MvQFileBrowser::slotSidebar(QAction *action)	
{	
	if(ignoreSidebarAction_) return;

	if(action->isChecked())
	{	
		int index=sidebarAg_->actions().indexOf(action);	  
		if(index >=0 && index < sidebar_->count())
		{
		  	sidebar_->setCurrentIndex(index);
		}		
		sidebar_->show();
		
		updateSidebarStatus();
	}
	else
	{
	  	slotCloseSidebar();
	}
}	
	
void MvQFileBrowser::slotCloseSidebar()
{
  	if(ignoreSidebarAction_==true)
	  	return;
	
	sidebar_->hide();	
	updateSidebarStatus();	
}	

void MvQFileBrowser::updateSidebarStatus()
{
  	ignoreSidebarAction_=true;
	
	qDebug() << sidebarAg_->checkedAction();
	
	if(sidebar_->isVisible() || 
	   (!isVisible() && sidebarEnabled()))
	{	  		  
	  	int index=sidebar_->currentIndex();
		for(int i=0; i < sidebarAg_->actions().count(); i++)
		{
		  	if(i == index)
				sidebarAg_->actions().at(i)->setChecked(true);
			else
			  	sidebarAg_->actions().at(i)->setChecked(false);
		}	
	}
	else
	{
	  	foreach(QAction *ac, sidebarAg_->actions())
		  	ac->setChecked(false);	
	}
	
	ignoreSidebarAction_=false;
}

bool MvQFileBrowser::sidebarEnabled()
{
  	qDebug() << sidebarAg_->checkedAction();
	
	bool hasChecked=false;
	foreach(QAction *ac, sidebarAg_->actions())
	{	
	  	if(ac->isChecked())
		{
		  	hasChecked=true;
			break;
		}		
	}
	
	return hasChecked;
}	
	
void MvQFileBrowser::updateSearchPanel(bool)
{
	searchPanel_->targetChanged();
}

//=============================================
//
// Icon size
//
//=============================================

void MvQFileBrowser::updateIconSizeActionState()
{
	int index=iconSizes_.indexOf(folderPanel_->iconSize());
	if(index <=0)
	{
	  	actionIconSizeDown_->setEnabled(false);	
		actionIconSizeUp_->setEnabled(true);	
	}	
	else if(index >= iconSizes_.count()-1)
	{
	  	actionIconSizeUp_->setEnabled(false);
		actionIconSizeDown_->setEnabled(true);	
	}		
	else
	{
	  	actionIconSizeDown_->setEnabled(true);
		actionIconSizeUp_->setEnabled(true);
	}
	
	ignoreIconSizeSlider_=true;
	iconSizeSlider_->setValue(index);
	ignoreIconSizeSlider_=false;	
}  

void MvQFileBrowser::slotIconSizeDown()
{
  	int index=iconSizes_.indexOf(folderPanel_->iconSize());
	if(index > 0) index--;	
	int size=iconSizes_[index];
	
	folderPanel_->setIconSize(size);
	updateIconSizeActionState();	
}  

void MvQFileBrowser::slotIconSizeUp()
{
  	int index=iconSizes_.indexOf(folderPanel_->iconSize());	
	if(index < iconSizes_.count()-1) index++;	
	int size=iconSizes_[index];	
	
	folderPanel_->setIconSize(size);
	updateIconSizeActionState();		
}  

//Callback from the slider
void MvQFileBrowser::slotSetIconSizeByIndex(int index)
{
	if(ignoreIconSizeSlider_)
	  	return;
	
	if(index >=0 && index <= iconSizes_.count()-1)
	{  				
		int size=iconSizes_[index];
		
		folderPanel_->setIconSize(size);
		updateIconSizeActionState();		
	}	
}  

void MvQFileBrowser::forceIconSize(int size)
{
 	folderPanel_->forceIconSize(size);		
	updateIconSizeActionState();		
}  
  
void MvQFileBrowser::slotGlobalIconSize()
{	
	 /*if(QMessageBox::warning(this,tr("Use global icon size"),"You are about to enter a mode when all the folders has the <b>same icon size</b> and all changes to the iconsize is automatically broadcast to all the open folders. Do you want to proceed?",QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel) == QMessageBox::Cancel)
	{
		return;
	}*/		
  
  	int index=iconSizes_.indexOf(folderPanel_->iconSize());	
	if(index>=0 && index < iconSizes_.count()-1)
	{  	
		broadcastIconSize(iconSizes_[index]);
	}
}  
   
void  MvQFileBrowser::slotSaveViewAsDefault()
{  	
  	/*if(QMessageBox::warning(this,tr("Save view settings as default"),"You are about to save the current view mode and iconsize as defaults. These will be applied for all unvisited folders in the future. Do you want to proceed?",QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel) == QMessageBox::Cancel)
			return;*/
	
	FolderSettings::setDefaults(folderPanel_->viewMode(),folderPanel_->iconSize());
}  

void  MvQFileBrowser::slotRevertViewToDefault()
{  	
	folderPanel_->setViewMode(FolderSettings::defaultViewMode());
	folderPanel_->setIconSize(FolderSettings::defaultIconSize());
	
	updateViewModeStatus(folderPanel_->viewMode());	 
	updateIconSizeActionState();
}  

//========================================
//
// Other
//
//========================================

void MvQFileBrowser::slotShowAboutBox()
{
	MvQAbout about("Desktop","",MvQAbout::MetviewVersion);
	about.exec();
}


void MvQFileBrowser::saveFolderInfo()
{
	folderPanel_->saveFolderInfo();
}

void MvQFileBrowser::slotLoadMetviewUIFolders()
{
	if(QMessageBox::warning(this,tr("Load MetviewUI folders"),"You are about to open all the folders from your latest <b>MetviewUI</b> (this is the former Metview desktop) session. If you proceed all these folders will be open in a new window as a set tabs. Do you want to continue?",QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel) == QMessageBox::Cancel)
			return;
	
	MvQFileBrowser::loadMetviewUIFolders();  
}  

//========================================
// 
//Init
//
//========================================

void MvQFileBrowser::init(MvQFileBrowser *browser)
{
  	if(!browser)
	  	return;
	
	//actionIconSidebar_->setChecked(browser->actionIconSidebar_->isChecked());	
	if(QAction *ac=browser->sidebarAg_->checkedAction()) 
	{	int index=browser->sidebarAg_->actions().indexOf(ac);
		sidebarAg_->actions().at(index)->setChecked(true);
	}	
	
	actionDrawers_->setChecked(browser->actionDrawers_->isChecked());
	actionStatusbar_->setChecked(browser->actionStatusbar_->isChecked());
}  


bool MvQFileBrowser::showIcon(IconObject* obj,bool addFolder)
{
 	return folderPanel_->showIcon(obj,addFolder); 
}  

//====================================================
//
// Read/write settings
//
//====================================================

void MvQFileBrowser::writeSettings(QSettings &settings)
{
	settings.setValue("geometry",saveGeometry());
	settings.setValue("state",saveState());
	//settings.setValue("drawerSplitter",drawerSplitter_->saveState());
	settings.setValue("mainSplitter",mainSplitter_->saveState());
	settings.setValue("minimized",(windowState() & Qt::WindowMinimized)?1:0);
	
	int sidebarIndex=-1;
	for(int i=0; i < sidebarAg_->actions().count(); i++)
	{
	  	if(sidebarAg_->actions().at(i)->isChecked())
		{
		  	sidebarIndex=i;
			break;
		}
	}

	settings.setValue("sidebar",sidebarIndex);
	settings.setValue("drawersStatus",actionDrawers_->isChecked());
	settings.setValue("statusbar",actionStatusbar_->isChecked());
	
	folderPanel_->writeSettings(settings);	
}	

void MvQFileBrowser::readSettings(QSettings &settings)
{
	restoreGeometry(settings.value("geometry").toByteArray());
	restoreState(settings.value("state").toByteArray());	
	mainSplitter_->restoreState(settings.value("mainSplitter").toByteArray());
	//drawerSplitter_->restoreState(settings.value("drawerSplitter").toByteArray());
	
	if(settings.value("minimized").toInt()== 1)
	{
	  	setWindowState(windowState() | Qt::WindowMinimized);
	}	
	
	/*QString viewMode=settings.value("viewMode").toString();
	if(viewMode == MvQFileBrowserWidget::DetailedViewMode)
	 	actionIconView_->trigger();
	else if(viewMode == MvQFileBrowserWidget::DetailedViewMode)
	  	actionDetailedView_->trigger();*/
	
	QVariant var=settings.value("iconSize");
	if(!var.isNull()) 
	{
	  	slotSetIconSizeByIndex(iconSizes_.indexOf(var.toInt()));
	}
	
	//By default sidebar actions are uncheked
	if(!settings.value("sidebar").isNull())
	{
	  	int index=settings.value("sidebar").toInt();
		if(index>=0 && index < sidebarAg_->actions().count())	  
		{
		  	QAction *ac=sidebarAg_->actions().at(index);
		  	ac->setChecked(true);
			slotSidebar(ac);
	
		}	
	}
				
	if(settings.value("drawersStatus").isNull())
	{
		actionDrawers_->setChecked(true);
	}
	else
	{
		actionDrawers_->setChecked(settings.value("drawersStatus").toBool());
	}
	
	if(settings.value("statusbar").isNull())
	{
		actionStatusbar_->setChecked(true);
	}
	else
	{
	  	actionStatusbar_->setChecked(settings.value("statusbar").toBool());
	}
	
	folderPanel_->readSettings(settings);	
}

//====================================================
//
// Static methods
//
//====================================================

MvQFileBrowser* MvQFileBrowser::makeBrowser(QSettings &settings)
{
   	MvQFileBrowser* browser=MvQFileBrowser::makeBrowser();
	browser->readSettings(settings); 
	return browser;
}  

MvQFileBrowser* MvQFileBrowser::makeBrowser()
{	
	QStringList pathLst;
	return MvQFileBrowser::makeBrowser(pathLst);
}

MvQFileBrowser* MvQFileBrowser::makeBrowser(QString fullName)
{	
	QStringList pathLst;
	pathLst << fullName;
	return MvQFileBrowser::makeBrowser(pathLst);
}	
   
MvQFileBrowser* MvQFileBrowser::makeBrowser(QStringList pathLst)
{
	MvQFileBrowser *browser=new MvQFileBrowser(pathLst);
	
	browsers_ << browser;
	
	return browser;
}


void MvQFileBrowser::openBrowser(QString fullName,QWidget *fromW)
{		
  	MvQFileBrowser* browser=MvQFileBrowser::makeBrowser(fullName);	
	browser->init(findBrowser(fromW));
	browser->showIt();
}	

void MvQFileBrowser::openBrowser(QStringList pathLst,QWidget *fromW)
{	
	MvQFileBrowser* browser=MvQFileBrowser::makeBrowser(pathLst);
	browser->init(findBrowser(fromW));
	browser->showIt();
}

void MvQFileBrowser::showBrowsers()
{
  	foreach(MvQFileBrowser *browser,browsers_)  
		browser->showIt();
}	

//Return true if close is allowed, false otherwise
bool MvQFileBrowser::aboutToClose(MvQFileBrowser* browser)
{
	//If quit has already stared we ignore the close signal from
	//the filebrowser windows.
  	if(quitStarted_)
	{	
		return false;
	}
	
	//Otherwise
	else
	{  
  		if(browsers_.count() > 1)
		{
		  	int tabCnt=browser->folderPanel_->count();
			if(tabCnt > 1)
			{
                if(logoutStarted_)
                {
                    return true;
                }    
                
                if(QMessageBox::question(0,tr("Confirm close"),tr("You are about to close <b>") + QString::number(tabCnt) + tr("</b> tabs. Are you sure you want to continue?"),
			    	      QMessageBox::Yes | QMessageBox::Cancel,QMessageBox::Cancel) == QMessageBox::Cancel)
				{		
					return false;
				}
			}	
		}	
		else if(browsers_.count() == 1)
		{			
			return MvQFileBrowser::aboutToQuit(browser);
		}	
		return true;
	}	
	
	return true;
}	

bool MvQFileBrowser::aboutToQuit(MvQFileBrowser* topBrowser)
{
	if(logoutStarted_ || QMessageBox::question(0,tr("Confirm quit"),tr("Do you want to quit Metview?"),
			     QMessageBox::Yes | QMessageBox::Cancel,QMessageBox::Cancel) == QMessageBox::Yes)
	{
		quitStarted_=true;
		
		//Save bookmarks
		MvQBookmarks::save();
		
		//Save most recent icons list
		MvQRecentIcons::save();
		
		//Save browser settings
		MvQFileBrowser::save(topBrowser);		
		
        if(logoutStarted_)
            return true;
        
		//Exit metview
		QApplication::quit();
        
        return true;
	}
	
	return false;
}	
	
void MvQFileBrowser::init()
{
	//Read the settings
  	QSettings settings("ECMWF","MV4-Desktop");
  		
	settings.beginGroup("main");
		
	if(settings.contains("browserCount"))
	{	  
	  	int cnt=settings.value("browserCount").toInt();
		int topBrowserId=settings.value("topBrowserId").toInt();	
		MvQFolderHistory::init(settings.value("history").toStringList());
		settings.endGroup();
	
		MvQDesktopSettings::readSettings(settings);
	
		if(cnt <0 || cnt > 100)
			return;
		
		for(int i=0; i < cnt; i++)
		{ 	
			if(i != topBrowserId)
			{
	  			settings.beginGroup("browser_" + QString::number(i));		
				MvQFileBrowser::makeBrowser(settings);
				settings.endGroup();
			}
		}
	
		if(topBrowserId >=0 &&  topBrowserId < cnt)
		{
	 		settings.beginGroup("browser_" + QString::number(topBrowserId));
			MvQFileBrowser::makeBrowser(settings); 		
			settings.endGroup(); 	
		}
	}
	
	//Try to read the resource file from MetviewUI
	else
	{
	  	loadMetviewUIFolders();	
	}
	 
	//If nothing has been found we open the home folder
	if(browsers_.count() == 0)
	{  	
		MvQFileBrowser::makeBrowser(QString::fromStdString(Folder::top()->fullName()));					
	}			
}

void MvQFileBrowser::loadMetviewUIFolders()
{
	//Try to read the resource file from MetviewUI	
	Path p=Folder::top()->path().add(".MainWindowResources"); 	  	
	MvRequest req(p.loadRequest());
	  	
	if(req)
	{
		QStringList pathLst;
		int cnt = req.iterInit("OPEN");
	 	for( int i=0; i<cnt; ++i )
		{
		  	const char *c=0;
			req.iterGetNextValue(c);
			if(c)
			{
				QString str(c);
				if(str.isEmpty()) str="/";
					pathLst << str;
			}
		}
			
		if(!pathLst.isEmpty())
		{
		  	MvQFileBrowser::openBrowser(pathLst);
		}
	}	
}		
		 
	 
void MvQFileBrowser::save(MvQFileBrowser *topBrowser)
{
	//Save folder info for all the open browsers
	for(int i=0; i < browsers_.count(); i++)
	{
		browsers_.at(i)->saveFolderInfo();				  
	}
				
	QSettings settings("ECMWF","MV4-Desktop");
	
	//We have to clear it not to remember all the previous windows
	settings.clear();
	
	settings.beginGroup("main");
	
	settings.setValue("browserCount",browsers_.count());
	settings.setValue("topBrowserId",browsers_.indexOf(topBrowser));
	settings.setValue("history",MvQFolderHistory::items());	
	settings.endGroup();
	
	MvQDesktopSettings::writeSettings(settings);
	
	for(int i=0; i < browsers_.count(); i++)
	{		
		settings.beginGroup("browser_" + QString::number(i));
		browsers_.at(i)->writeSettings(settings);
		settings.endGroup();
	}	
}

void MvQFileBrowser::broadcastIconSize(int size)
{
	for(int i=0; i < browsers_.count(); i++)
	{
		browsers_.at(i)->forceIconSize(size);				  
	}  	
}

MvQFileBrowser* MvQFileBrowser::findBrowser(QWidget *childW)
{
  	if(!childW)
	  	return 0;
	
	foreach(MvQFileBrowser *b,browsers_)
	{
	  	if(static_cast<QWidget*>(b) == 	childW->window())
			return b;
	}
	
	return 0;
}	

void MvQFileBrowser::locate(QWidget *winPref,QString path,QString name)
{
	//Find the folder of the icon
  	Folder *f=Folder::folder(path.toStdString(),false);
	if(!f)
	{
	  	return;
	}	
	
	//Get the IconObject
	IconObject *obj=f->find(name.toStdString());
	if(!obj)
	  	return;
	
	//The preferred browser to show the icon
	MvQFileBrowser* bPref=findBrowser(winPref);
	
	//We try to show the icon the preferred browser
	if(bPref)
	{
	  	if(bPref->showIcon(obj,false))
		{
		  	bPref->raise();
			return;
		}	
	}
	
	//If the preferred browser does not contan the icon icon we try the other browsers
	for(int i=0; i < browsers_.count(); i++)
	{
		if(browsers_.at(i) != bPref && browsers_.at(i)->showIcon(obj,false))
		{	
		  	browsers_.at(i)->raise();
		  	return;
		}	
	}  
	
	//If none of the browsers contain the icon add its folder 
	//to the preferred browser (as a tab) and locate the icon in it
	if(bPref)
	{
	  	bPref->showIcon(obj,true);
		bPref->raise();
	}
	//In case there is no preffered browser
	else if(browsers_.count() > 0)
	{
	  	
	  	browsers_.at(0)->showIcon(obj,true);
		browsers_.at(0)->raise();
	}
	
}	
