/***************************** 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 "MvQMethods.h"
#include "MvQAbout.h"
#include "MvQAdvancedSearch.h"
#include "MvQBookmarks.h"
#include "MvQContextMenu.h"
#include "MvQEditorListMenu.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 "IconDescription.h"
#include "Items.h"
#include "Path.h"
#include "PreviewPanel.h"
#include "Folder.h"
#include "Tools.h"

bool MvQFileBrowser::quitStarted_          = false;
bool MvQFileBrowser::sessionLogoutStarted_ = false;

QList<MvQFileBrowser*> MvQFileBrowser::browsers_;

//#define USE_PRODUCT_BROWSER

#ifdef USE_PRODUCT_BROWSER
#include "MvQProductBrowser.h"
#endif


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
    //-----------------------------

    auto* mainLayout = new QVBoxLayout;
    mainLayout->setSpacing(0);
    mainLayout->setContentsMargins(0, 0, 0, 0);

    auto* 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
    //------------------------------

    auto* 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(IconObject*)),
            this, SLOT(slotItemInfo(IconObject*)));


    //Search panel below the folders
    searchPanel_ = new MvQFolderSearchPanel(this);
    centralVb->addWidget(searchPanel_);

    connect(searchPanel_, SIGNAL(find(FolderSearchData*)),
            folderPanel_, SLOT(slotFindIcons(FolderSearchData*)));

    searchPanel_->hide();

    mainSplitter_->setCollapsible(1, false);

    //-----------------------------
    // Right hand side -- sidebar
    //-----------------------------

    previewPanel_ = new PreviewPanel(this);

    mainSplitter_->addWidget(previewPanel_);
    mainSplitter_->setCollapsible(2, false);
    folderPanel_->setPreviewPanel(previewPanel_);
    previewPanel_->hide();

    //Init splitters
    int spWidth = mainSplitter_->size().width();
    if (spWidth > 0) {
        QList<int> spSize;
        spSize << 150 << spWidth - 2 * 150 << 150;
        mainSplitter_->setSizes(spSize);
    }

    //-----------------------------
    // Bottom part  -- drawers
    //-----------------------------

    drawerPanel_ = new MvQFolderDrawerPanel(this);
    mainLayout->addWidget(drawerPanel_);

    connect(drawerPanel_, SIGNAL(itemEntered(IconObject*)),
            this, SLOT(slotItemInfo(IconObject*)));

    //--------------------------------------
    // Setup actions for toolbars and menus
    //--------------------------------------

    setupFileActions();
    setupEditActions();
    setupNavigateActions();
    setupViewActions();
    setupBookmarksActions();
    setupHistoryActions();
    setupEditorActions();
    setupToolsActions();
    setupHelpActions();

    setupMenus(menuItems_);

    //----------------------------------------------------
    // Add history menu to folder panel. Need to do it after
    // the menus were created!!!
    //-----------------------------------------------------

    folderPanel_->setHistoryMenu(findMenu(MvQMainWindow::HistoryMenu));

    auto* bookmarksMenu = new MvQBookmarksMenu(this, findMenu(MvQMainWindow::BookmarksMenu));
    connectBookmarksObject(bookmarksMenu);
    connectBookmarksObject(bookmarksPanel_);

    new MvQEditorListMenu(findMenu(MvQMainWindow::EditorMenu));

    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() = default;

//Show the brower for the first time!
void MvQFileBrowser::showIt()
{
    //We need to reset the size to the expected value. See METV-2271
    QVariant expectedSize = property("expectedSize");
    if (expectedSize.isValid() && expectedSize.toSize().isValid()) {
        resize(expectedSize.toSize());
    }

    setProperty("expectedSize", QVariant());

    show();

    //Minimise the drawer panel!
    drawerPanel_->shrink();
}

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

void MvQFileBrowser::closeEvent(QCloseEvent* event)
{
    qDebug() << "closeEvent";
    if (!quitStarted_) {
        qDebug() << "  start close";
        if (browsers_.count() == 1) {
            qDebug() << "  start quit";
            MvQFileBrowser::aboutToQuit(this);
            qDebug() << "closeEvent finished";
            return;
        }
        qDebug() << "  accept close event";
        browsers_.removeOne(this);
        saveFolderInfo();
        event->accept();
    }
    qDebug() << "closeEvent finished";
}

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 sessionLogoutStarted_ flag to indicate that
//this happened.
void MvQFileBrowser::slotCommitDataRequest(QSessionManager&)
{
    sessionLogoutStarted_ = true;
}

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


void MvQFileBrowser::setupFileActions()
{
    auto* ac = new QAction(this);
    ac->setToolTip(tr("Open a new tab"));
    ac->setText(tr("New &tab"));
    ac->setShortcut(tr("Ctrl+T"));
    auto* 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;

    auto* 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()));

    //Defaults
    actionDefaults_ = new QAction(this);
    actionDefaults_->setToolTip(tr("Defaults"));
    actionDefaults_->setText(tr("&Defaults"));
    connect(actionDefaults_, SIGNAL(triggered()),
            folderPanel_, SLOT(slotChFolderDefaults()));

    //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)));

    auto* 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(actionDefaults_, 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 populate 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 populate it later dinamically
    QAction* action = 0;

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

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

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

void MvQFileBrowser::setupViewActions()
{
    QAction* action;

    //--------------
    // View mode
    //--------------

    QList<QAction*> viewModeLst;

    auto* 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*)));

    //-----------------------------------
    // Preview panel
    //-----------------------------------

    //Preview
    action = new QAction(this);
    action->setObjectName(QString::fromUtf8("actionPreview"));
    action->setCheckable(true);
    action->setChecked(false);  //!!!
    action->setText(tr("&Preview"));
    action->setIcon(QPixmap(QString::fromUtf8(":/desktop/preview.svg")));
    action->setShortcut(tr("Ctrl+P"));
    actionPreview_ = action;
    //sidebarAg_->addAction(action);

    connect(previewPanel_, SIGNAL(closePanel()),
            this, SLOT(slotClosePreview()));

    connect(actionPreview_, SIGNAL(toggled(bool)),
            previewPanel_, SLOT(setVisible(bool)));

    //-------------------------------
    // 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 std::vector<int>& sVec = MvQIconProvider::sizes();
    for (int it : sVec) {
        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->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()));

    auto* sep = new QAction(this);
    sep->setSeparator(true);

    auto* sep1 = new QAction(this);
    sep1->setSeparator(true);

    auto* sep2 = new QAction(this);
    sep2->setSeparator(true);

    auto* 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, MvQMenuItem::MenuTarget));

    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, MvQMenuItem::MenuTarget));
    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) {
        auto* 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(actionPreview_));
    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()
{
    auto* 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
    auto* actionPref = new QAction(this);
    actionPref->setIcon(QPixmap(":/desktop/cogwheel.svg"));
    actionPref->setToolTip(tr("Preferences"));
    actionPref->setText(tr("Preferences..."));

    connect(actionPref, SIGNAL(triggered()),
            this, SLOT(slotPreferences()));

    //Icon filter
    auto* 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()));


    auto* 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()));

    auto* 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
    auto* 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()));

#ifdef USE_PRODUCT_BROWSER
    QAction* actionProduct = new QAction(this);
    actionProduct->setText(tr("Product browser ..."));
    //actionProduct->setShortcut(tr("Ctrl+Alt+F"));

    connect(actionProduct, SIGNAL(triggered()),
            this, SLOT(slotProductBrowser()));
#endif


    //Add actions to menus and toolbars
    MvQMainWindow::MenuType menuType = MvQMainWindow::ToolsMenu;

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

    auto* 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));

    auto* 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));

#ifdef USE_PRODUCT_BROWSER
    menuItems_[menuType].push_back(new MvQMenuItem(actionProduct, MvQMenuItem::MenuTarget));
#endif

    foreach (QAction* ac, lst) {
        menuItems_[menuType].push_back(new MvQMenuItem(ac, MvQMenuItem::MenuTarget));
    }

    auto* 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
    auto* actionAbout = new QAction(this);
    actionAbout->setObjectName(QString::fromUtf8("actionAbout"));
    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
    auto* 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/cogwheel.svg"))));
    tb->setPopupMode(QToolButton::InstantPopup);
    tb->addAction(actionGlobalIconSize_);
    tb->addAction(actionSaveViewAsDefault_);
    tb->addAction(actionRevertViewToDefault_);
    statusBar()->addPermanentWidget(tb);
}

void MvQFileBrowser::slotCurrentFolderChanged()
{
    breadcrumbs_->setPath(folderPanel_->currentFolderPath());
    slotUpdateNavigationActions(folderPanel_->folderNavigation());
    updateViewModeStatus(folderPanel_->viewMode());
    updateIconSizeActionState();
    updateSearchPanel();

    //Update window title
    updateWindowTitle();
}

void MvQFileBrowser::slotPathChanged()
{
    breadcrumbs_->setPath(folderPanel_->currentFolderPath());
    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 (!txt.isEmpty() && txt != "/") {
            if (f->parent() && !f->parent()->fullName().empty() && f->parent()->fullName() != "/") {
                txt += " - " + QString::fromStdString(f->parent()->fullName());
            }
            txt += " - Metview";
        }
        else {
            txt = "Metview";
        }
    }
    else {
        txt = "Metview";
    }
    setWindowTitle(txt);
}

void MvQFileBrowser::slotUpdateNavigationActions(MvQFolderNavigation* nav)
{
    if (!nav)
        return;

    //nav->print();

    breadcrumbs_->setPath(folderPanel_->currentFolderPath());
    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(IconObject* obj)
{
    itemInfoLabel_->setText(IconDescription::Instance()->info(obj));
    previewPanel_->setItem(obj);
}

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());
}

void MvQFileBrowser::slotProductBrowser()
{
#ifdef USE_PRODUCT_BROWSER
    MvQProductBrowser pb(this);
    pb.exec();

    //MvQAdvancedSearchDialog::open(this,folderPanel_->currentFolder());
#endif
}

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

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

    connect(bk, SIGNAL(lookupOrOpenInTab(QString)),
            this, SLOT(slotLookupOrOpenInTab(QString)));

    connect(bk, SIGNAL(openInNewTab(QString)),
            this, SLOT(slotOpenInNewTab(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::slotLookupOrOpenInTab(QString fullName)
{
    folderPanel_->slotLookupOrOpenInTab(fullName);
}

void MvQFileBrowser::slotOpenInNewTab(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;

    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()
{
    bool hasChecked = false;
    foreach (QAction* ac, sidebarAg_->actions()) {
        if (ac->isChecked()) {
            hasChecked = true;
            break;
        }
    }

    return hasChecked;
}

void MvQFileBrowser::updateSearchPanel(bool)
{
    searchPanel_->targetChanged();
}

void MvQFileBrowser::slotClosePreview()
{
    previewPanel_->hide();
    actionPreview_->setChecked(false);
}

//=============================================
//
// 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 | MvQAbout::InterpolationPackage);
    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);
    }

    actionPreview_->setChecked(browser->actionPreview_->isChecked());
    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());

    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("previewStatus", actionPreview_->isChecked());
    settings.setValue("drawersStatus", actionDrawers_->isChecked());
    settings.setValue("statusbar", actionStatusbar_->isChecked());

    folderPanel_->writeSettings(settings);
}

void MvQFileBrowser::readSettings(QSettings& settings)
{
    restoreGeometry(settings.value("geometry").toByteArray());

    //we need to save the expected size to reset the size later. See METV-2271
    setProperty("expectedSize", size());

    restoreState(settings.value("state").toByteArray());
    mainSplitter_->restoreState(settings.value("mainSplitter").toByteArray());
    //drawerSplitter_->restoreState(settings.value("drawerSplitter").toByteArray());

    /*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("previewStatus").isNull()) {
        actionPreview_->setChecked(false);
    }
    else {
        actionPreview_->setChecked(settings.value("previewStatus").toBool());
    }

    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)
{
    auto* 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();
}

void MvQFileBrowser::aboutToQuit(MvQFileBrowser* topBrowser)
{
    qDebug() << "aboutToQuit";
    quitStarted_ = true;

    //Save bookmarks
    MvQBookmarks::save();

    //Save most recent icons list
    MvQRecentIcons::save();

    //Save browser settings
    MvQFileBrowser::save(topBrowser);

    qDebug() << "  save done!";
    qDebug() << "  calls app quit";

    //Exit metview
    QApplication::quit();
    qDebug() << "  app quit called!";
}

void MvQFileBrowser::init()
{
    //Read the settings
    QSettings settings(MVQ_QSETTINGS_DEFAULT_ARGS, "MV4-Desktop");
    std::cout << "MvQFileBrowser::init settings path is: " << settings.fileName().toStdString() << std::endl;

    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(MVQ_QSETTINGS_DEFAULT_ARGS, "MV4-Desktop");
    std::cout << "MvQFileBrowser::save settings path is: " << settings.fileName().toStdString() << std::endl;

    //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();
    }
}
