UIMainWindow.cpp 70.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 *	(c) LSIIT, UMR CNRS/UdS
 *	Authors: O. Gnevaux, F. Larue.
 *
 *	See licence.txt for additional information.
 */


#include <GL/glew.h>
#ifndef _WIN32
#include <unistd.h>
#include <stdlib.h>
#endif

#include <QtGui>
#include <QtCore>

#ifdef QT_WEBKIT_AVAILABLE
#include <QWebView>
#endif

22
#include "UIMainWindow.h"
23 24 25
#include "ui_mainwindow.h"
#include "UIDataWidget.h"
#include "Interfaces.h"
26
#include "UIParamDialog.h"
27
#include "ThemeSettingsDialog.h"
28
#include "UISettings.h"
29 30 31 32 33 34 35

#include "NodeEditor.h"
//#include "ShaderGraph.h"

#include <algorithm>
#include <iomanip>
#include <assert.h>
36
#include <fstream>
37 38 39 40




41
UIMainWindow::UIMainWindow(QWidget *parent) :
42 43
    QMainWindow( parent ),
    ui( new Ui::MainWindow ),
Frédéric Larue's avatar
Frédéric Larue committed
44
    m_CurrentViewer( NULL ),
45
    m_CurrentProject( NULL )
46
{
47 48 49 50 51 52 53 54
}


UIMainWindow::~UIMainWindow()
{
}


55 56
bool UIMainWindow::saveUISettings() const
{
Frédéric Larue's avatar
Frédéric Larue committed
57 58
    // Get user settings file.

59
    QSettings *settings = UI::GetUserSettings();
Frédéric Larue's avatar
Frédéric Larue committed
60 61 62 63 64 65 66

    // Store geometry and state of the main window and the dock widgets.

    settings->setValue( "geometry", saveGeometry() );
    settings->setValue( "windowState", saveState() );

    // Store the list of recently used projects.
67 68 69 70

    QStringList recents;
    for( auto r : m_RecentProjects )
        recents.push_back( r->text() );
Frédéric Larue's avatar
Frédéric Larue committed
71
    settings->setValue( "recent", recents );
72

73 74 75 76 77
    // Store the last category/tool used.

    settings->setValue( "lastCategory", ui->toolSelector->currentCategoryId() );
    settings->setValue( "lastTool", ui->toolSelector->currentToolName() );

78
    return true;
79 80 81 82 83
}


bool UIMainWindow::loadUISettings()
{
Frédéric Larue's avatar
Frédéric Larue committed
84 85
    // Get user settings file.

86
    QSettings *settings = UI::GetUserSettings();
Frédéric Larue's avatar
Frédéric Larue committed
87 88

    // Load geometry and state of the main window and the dock widgets.
89

90
    if( !settings->contains("geometry")  ||  !settings->contains("windowState") )
91 92
        return false;

Frédéric Larue's avatar
Frédéric Larue committed
93 94
    restoreGeometry( settings->value("geometry"   ).toByteArray() );
    restoreState   ( settings->value("windowState").toByteArray() );
95

Frédéric Larue's avatar
Frédéric Larue committed
96 97 98
    // Load the list of recently used projects.

    QStringList recents = settings->value( "recent" ).toStringList();
99 100 101
    for( auto r=recents.rbegin(); r!=recents.rend(); ++r )
        updateRecentListEntry( *r );

102 103 104 105 106
    // Load the last category/tool used.

    if( settings->contains("lastCategory")  &&  settings->contains("lastTool") )
        ui->toolSelector->selectTool( settings->value("lastCategory").toInt(), settings->value("lastTool").toString() );

107 108 109 110
    return true;
}


111 112 113 114
void UIMainWindow::updateRecentListEntry( const QString& path )
{
    bool isVeryFirstEntry = m_RecentProjects.empty();

115 116 117 118 119 120
    // If the given path does not correspond to an existing file, do not add it to the list of recent projects.

    QFile fileCheck( path );
    if( !fileCheck.exists() )
        return;

121 122 123 124 125 126 127 128 129 130 131 132 133
    // Search for the given path in the current list of recent projects.

    QList< QAction* >::iterator entry;
    for( entry=m_RecentProjects.begin(); entry!=m_RecentProjects.end(); ++entry )
        if( (*entry)->text() == path )
            break;

    // If the path is not already referenced in the list, create a new entry.

    QAction *newFirstEntry;

    if( entry == m_RecentProjects.end() )
    {
134
        newFirstEntry = new QAction( path, NULL );
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
        connect( newFirstEntry, SIGNAL(triggered(bool)), this, SLOT(loadRecent()) );
    }

    // Otherwise, remove it from the list since it must be moved to the beginning.

    else if( entry != m_RecentProjects.begin() )
    {
        newFirstEntry = *entry;

        ui->menuFile->removeAction( *entry );
        m_RecentProjects.erase( entry );
    }
    else
        return;

150 151
    // Insert the path to the beginning of the list.

152 153 154 155 156 157
    if( m_RecentProjects.empty() )
        ui->menuFile->insertAction( ui->menuFile->actions().back(), newFirstEntry );
    else
        ui->menuFile->insertAction( m_RecentProjects.front(), newFirstEntry );
    m_RecentProjects.push_front( newFirstEntry );

158 159
    // If the list of recent project exceeds the maximum size allowed, remove its very last element.

160 161 162 163
    if( m_RecentProjects.size() > RECENT_PROJECT_MAX_LIST_SIZE )
    {
        ui->menuFile->removeAction( m_RecentProjects.back() );
        m_RecentProjects.back()->deleteLater();
164
        m_RecentProjects.pop_back();
165 166
    }

167 168
    // If the inserted path is the first one, insert a separator before it in the menu.

169 170 171 172 173 174 175 176 177 178 179
    if( isVeryFirstEntry )
        ui->menuFile->insertSeparator( ui->menuFile->actions().back() );
}


void UIMainWindow::loadRecent()
{
    loadProject( ((QAction*) QObject::sender())->text() );
}


180
void UIMainWindow::declareCustomMenuAction( const QString& menuName, QAction* action, bool insertSeparatorBefore )
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
{
    // Add custom menu actions to the menubar.

    QString menuSimplifiedName = menuName;
    menuSimplifiedName.remove( '&' );

    QMenu *menu = NULL;
    for( auto m : ui->menuBar->children() )
        if( dynamic_cast<QMenu*>(m)  &&  menuSimplifiedName == ((QMenu*)m)->title().remove('&') )
            menu = (QMenu*) m;

    if( !menu )
    {
        menu = new QMenu( menuName );
        ui->menuBar->insertMenu( ui->menuHelp->menuAction(), menu );
    }

    connect( action, SIGNAL(triggered(bool)), this, SLOT(customMenuActionTriggered()) );
199 200 201 202

    if( insertSeparatorBefore )
        menu->addSeparator();

203 204 205 206
    menu->addAction( action );
}


207
void UIMainWindow::initializeUserSettings()
208
{
209 210
    QString compagnyName, applicationName, shortDescription;
    applicationInfo( compagnyName, applicationName, shortDescription );
211
    UI::InitializeUserSettings( compagnyName + "/" + applicationName );
212
}
Frédéric Larue's avatar
Frédéric Larue committed
213 214


215 216
void UIMainWindow::init()
{
217 218
    onDeclaringToolCategories();    // must be called before setupUi(...) because tool categories are required for the AlgorithmSelector widget.

219 220
    ui->setupUi(this);

221 222
    ui->menuView->addAction( ui->dockProjectManager->toggleViewAction() );
    ui->menuView->addAction( ui->dockTools->toggleViewAction() );
223 224
    onDeclaringCustomMenus();

225 226 227 228 229
    loadPlugins();

    connect( ui->tableCurrentProjContent, SIGNAL(askForReframing()), this, SLOT(reframeScene()) );
    connect( ui->tableCurrentProjContent, SIGNAL(exportLaunched(ExportInterface*,int,QString)), this, SLOT(launchExport(ExportInterface*,int,QString)) );

230
    initRenderOptions();
231 232
    initializeCentralWidgetStack();
    setViewerMode( DISPLAY_DOF_3D );
233

234 235 236 237 238 239
    //QGroupBox *groupBox = new QGroupBox("plop");
    //groupBox->setLayout( new QHBoxLayout() );
    //groupBox->layout()->addWidget( new QPushButton("yop") );
    //groupBox->layout()->addWidget( new QPushButton("zap") );
    //ui->toolBar->addWidget( groupBox );

240 241 242 243
    ui->comboProject->setContextMenuPolicy( Qt::CustomContextMenu );
    connect( ui->comboProject, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showProjectContextMenu(QPoint)) );
    connect( ui->comboProject, SIGNAL(currentIndexChanged(int)), this, SLOT(currentProjectChanged()) );

244 245 246 247 248 249 250 251 252
    connect( ui->projectViewButtonCollapseAll, SIGNAL(clicked(bool)), ui->tableCurrentProjContent, SLOT(collapseAll()) );
    connect( ui->projectViewButtonExpandAll, SIGNAL(clicked(bool)), ui->tableCurrentProjContent, SLOT(expandAll()) );
    connect( ui->projectViewButtonExpandSelected, SIGNAL(clicked(bool)), ui->tableCurrentProjContent, SLOT(expandCollapseSelectedData()) );
    connect( ui->projectViewButtonSelectAll, SIGNAL(clicked(bool)), ui->tableCurrentProjContent, SLOT(selectAll()) );
    connect( ui->projectViewButtonSelectTree, SIGNAL(clicked(bool)), ui->tableCurrentProjContent, SLOT(selectSubTrees()) );
    connect( ui->projectViewButtonSelectByType, SIGNAL(clicked(bool)), ui->tableCurrentProjContent, SLOT(selectSameTypesAsSelected()) );
    connect( ui->projectViewButtonRemove, SIGNAL(clicked(bool)), this, SLOT(removeFromCurrentProject()) );
    connect( ui->projectViewButtonRename, SIGNAL(clicked(bool)), ui->tableCurrentProjContent, SLOT(editSelectedDataName()) );

253
    connect( ui->actionRenderOptions, SIGNAL(triggered()), this, SLOT(showRenderingOptionDialog()) );
254 255
	connect( ui->actionLoadImage, SIGNAL(triggered()), this, SLOT(addToCurrentProject()) );
	connect( ui->actionNewProject, SIGNAL(triggered()), this, SLOT(newProject()) );
Frédéric Larue's avatar
Frédéric Larue committed
256
	connect( ui->actionSaveProject, SIGNAL(triggered()), this, SLOT(saveCurrentProject()) );
257
	connect( ui->actionLoadProject, SIGNAL(triggered()), this, SLOT(openProject()) );
Frédéric Larue's avatar
Frédéric Larue committed
258
	connect( ui->actionCloseProject, SIGNAL(triggered()), this, SLOT(closeCurrentProject()) );
259 260
	connect( ui->comboTypeFilter, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(updateCurrentProjectContent()) );
	connect( ui->actionAbout, SIGNAL(triggered()), this, SLOT(showAboutDialog()) );
261 262
    connect( ui->actionShowLogos, SIGNAL(toggled(bool)), m_CurrentViewer, SLOT(setDemoModeEnabled(bool)) );
    connect( ui->actionDisplayPluginsList, SIGNAL(triggered()), this, SLOT(displayPluginsList()) );
263 264
    connect( ui->action2DViewer, SIGNAL(triggered()), this, SLOT(setDefault3DViewer()) );
	connect( ui->action3DViewer, SIGNAL(triggered()), this, SLOT(setDefault2DViewer()) );
265 266 267
	connect( ui->actionClone, SIGNAL(triggered()), this, SLOT(cloneSelectedManageables()) );
    connect( ui->actionWireframeMode, SIGNAL(triggered()), this, SLOT(toWireframeMode()) );
    connect( ui->actionSolidMode, SIGNAL(triggered()), this, SLOT(toSolidMode()) );
268
    connect( m_CurrentViewer, SIGNAL(keyPressed(QKeyEvent*)), this, SLOT(keyPressedInGLViewer(QKeyEvent*)) );
269
    connect( ui->actionCustomizeTheme, SIGNAL(triggered()), this, SLOT(showThemeSettingsDialog()) );
270 271 272 273 274 275 276

    ui->actionSolidMode->setVisible( false );

    connect( ui->actionToggleShading, SIGNAL(toggled(bool)), this, SLOT(toggleShading(bool)) );
    ui->actionToggleShading->setChecked( true );

	connect( ui->tableCurrentProjContent, SIGNAL(contentDropped(QDropEvent*)), this, SLOT(tableItemsContentDropped(QDropEvent*)) );
277
	connect( ui->tableCurrentProjContent, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(modifyItem(QTreeWidgetItem*,int)) );
278
	connect( ui->tableCurrentProjContent, SIGNAL(visibilityChanged(QList<QTreeWidgetItem*>)), this, SLOT(modifyVisibility(QList<QTreeWidgetItem*>)) );
279 280
	connect( ui->tableCurrentProjContent, SIGNAL(removalAsked()), this, SLOT(removeFromCurrentProject()) );
    connect( ui->tableCurrentProjContent, SIGNAL(itemDoubleClicked(GenericUIData*)), this, SLOT(onItemDoubleClicked(GenericUIData*)) );
281
    connect( ui->tableCurrentProjContent, SIGNAL(parentDataChanged(GenericUIData*,GenericUIData*,GenericUIData*)), this, SLOT(dataParentChanged(GenericUIData*,GenericUIData*,GenericUIData*)) );
282
    connect( m_CurrentViewer, SIGNAL(dataSelected(GenericUIData*,Qt::KeyboardModifiers)), ui->tableCurrentProjContent, SLOT(updateSelection(GenericUIData*,Qt::KeyboardModifiers)) );
283
    connect( ui->tableCurrentProjContent, SIGNAL(itemSelectionChanged()), this, SLOT(selectionChanged()) );
284 285 286 287 288

    connect( ui->toolSelector, SIGNAL(askItemsToApplyToolOn()), this, SLOT(giveSelectionToTool()) );
    connect( ui->toolSelector, SIGNAL(toolExecutionFinished(bool)), this, SLOT(toolExecutionFinished(bool)) );


289
    setMainWindowTitleInfos( "" );
290 291 292 293 294

    if( loadUISettings() )
        show();
    else
    	showMaximized();
295 296 297
}


298 299
void UIMainWindow::release()
{
300 301
    saveUISettings();

302
    releaseCentralWidgetStack();
303 304 305

    closeAllProjects();

306
    UI::ReleaseUserSettings();
Frédéric Larue's avatar
Frédéric Larue committed
307

308 309 310 311
    ui->toolSelector->releaseAllTools();
    delete ui;

    unloadPlugins();
312 313 314
}


315
void UIMainWindow::setMainWindowTitleInfos( const QString& str )
316
{
Frédéric Larue's avatar
Frédéric Larue committed
317 318 319 320
    QString compagnyName, applicationName, shortDescription;
    applicationInfo( compagnyName, applicationName, shortDescription );

    QString title = applicationName + " / " + shortDescription;
321 322 323 324 325 326 327 328 329 330 331

	if( str.length() )
	{
		title += " - ";
		title += str;
	}

	setWindowTitle( title );
}


332
void UIMainWindow::loadPlugins()
333 334 335 336 337 338
{
    // Recover the list of all files contained in the plugin directory.
    QDir pluginsDir( qApp->applicationDirPath() );
    if( !pluginsDir.cd( "plugins" ) )
        return;

339

340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
	QStringList nameFilters;

#ifdef _WIN32
	nameFilters << "*.dll";
#else
	nameFilters << "*.so";
#endif

	pluginsDir.setFilter(QDir::Files);
	pluginsDir.setNameFilters(nameFilters);

    foreach( QString fileName, pluginsDir.entryList() )
    {
        QPluginLoader* loader = new QPluginLoader( pluginsDir.absoluteFilePath(fileName) );

355
		if( !loader->load() )
356 357 358 359 360 361 362 363 364
		{
			delete loader;
		}
		else
		{
        	QObject *plugin = loader->instance();

	        if( plugin )
    	    {
365
				m_pluginLoaders.push_back( loader );
366 367 368 369 370 371 372

    	        ToolInterface *tool = qobject_cast<ToolInterface*>( plugin );
        	    if( tool )
            	    ui->toolSelector->populateTools( tool );

	            DisplayableFactoryInterface *dispFactory = qobject_cast<DisplayableFactoryInterface*>( plugin );
	            if( dispFactory )
373
                {
374 375
	                m_DisplayablePlugins.push_back( dispFactory );

376 377 378 379 380 381
                    QVector<QString> acceptedTypes;
                    dispFactory->acceptedDataTypes( acceptedTypes );
                    for( auto &type : acceptedTypes )
                        m_DisplayableFactoryByTypes[ type ] = dispFactory;
                }

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
	            ExportInterface *exporter = qobject_cast<ExportInterface*>( plugin );
	            if( exporter )
	                ui->tableCurrentProjContent->populateExports( exporter );

    	        ImportInterface *importer = qobject_cast<ImportInterface*>( plugin );
	            if( importer )
	            {
	                QList<int> importIds;
	                importer->importIds( importIds );

	                QStringList importNames;
	                importer->importNames( importNames );

	                QStringList::iterator name = importNames.begin();
	                foreach( int id, importIds )
    	            {
        	            ImportHandle importHdl;
            	        importHdl.plugin = importer;
                	    importHdl.id = id;
                    	importHdl.name = *name;
	                    m_ImportPlugins.push_back( importHdl );

    	                QStringList extensions, descriptions;
        	            importer->fileFilters( id, extensions, descriptions );
            	        foreach( QString ext, extensions )
                	        m_ImportSortedByExtensions[ ext ] = importHdl;

                    	++ name;
	                }
	            }
			}
        }
    }

    ui->toolSelector->finalizeTools();
}


420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
bool UIMainWindow::unloadPlugins()
{
    bool ok = true;

	for( QList<QPluginLoader*>::iterator p=m_pluginLoaders.begin(); p!=m_pluginLoaders.end();  )
        if( (*p)->unload() )
        {
    		delete *p;
            p = m_pluginLoaders.erase( p );
        }
        else
        {
            ok = false;
            ++ p;
        }

    return ok;
}


440
QList<GenericUIData*> UIMainWindow::selection( const QStringList& typeFilters )
441
{
442 443 444 445 446 447 448
    return ui->tableCurrentProjContent->selectedData( typeFilters );
}


QList<GenericUIData*> UIMainWindow::selection( const QString& typeFilter )
{
    return selection( QStringList(typeFilter) );
449 450 451
}


452
void UIMainWindow::giveSelectionToTool()
453
{
454 455
	QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) );

456
    m_ToolTimer.start();
457
    ui->toolSelector->applyCurrentToolOn( selection(), this, m_CurrentViewer, getCurrentProject() );
458 459 460
}


461
void UIMainWindow::toolExecutionFinished( bool needUpdate )
462
{
463 464 465 466 467 468
    if( needUpdate )
    {
	    updateTypeFilters();
	    updateCurrentProjectContent();

        updateDisplayables();
469

470
        m_CurrentViewer->updateSelectionZBuffer();
471

472 473
        update();
    }
474 475

	QApplication::restoreOverrideCursor();
476 477 478
}


479
void UIMainWindow::update( bool mustBeUpdated )
480 481 482 483 484 485 486 487 488 489 490
{
	if( mustBeUpdated )
	{
		QMainWindow::update();

		if( m_CurrentViewer )
			m_CurrentViewer->update();
	}
}


491
void UIMainWindow::newProject()
492
{
493
    /* Create the dialog box for asking information about the project to create */
494 495 496
    UIParamDialog dlg( "Project settings", this );
    dlg.Add( new UIParamString("name", "Project name", "Name of the new project to create.", "Default project" ) );
    onDeclaringNewProjectParameters( dlg.GetParameters() );
497

498 499
    dlg.GetParameters().GetString("name")->Widget()->setFocus();

500
	/* */
501
	if( dlg.exec() == QDialog::Accepted )
502
	{
503
        QString projectName = dlg.GetParameters().GetString("name")->Value();
504
		if( !projectName.size() )
505 506 507 508 509 510 511 512 513
		{
			QMessageBox::warning(
				this,
				"Project creation error",
				"Unable to create the project. The name field is not specified."
				);
			return;
		}

Frédéric Larue's avatar
Frédéric Larue committed
514
        ProjectHandle *pHndl = new ProjectHandle();
515
        pHndl->project = onCreatingProject( projectName, &dlg.GetParameters() );
Frédéric Larue's avatar
Frédéric Larue committed
516 517
	    ui->comboProject->addItem( pHndl->project->Name(), QVariant::fromValue<void*>(pHndl) );
	    ui->comboProject->setCurrentIndex( ui->comboProject->count()-1 );
518

519
        setViewerMode( DISPLAY_DOF_3D, true );
520
    }
521 522 523
}


524
void UIMainWindow::openProject()
525
{
526
	QString fileName = QFileDialog::getOpenFileName( this, tr("Loading an existing project"), "", tr("Project Files (*.")+projectFileExtension()+")" );
527
	if( fileName.isNull() )
528 529
		return;

530
	loadProject(fileName);
531 532 533 534 535 536 537 538
}


UIDataWidgetItem* buildItemTree( GenericUIData* data, GLViewer *viewer )
{
	UIDataWidgetItem *item = new UIDataWidgetItem( data );

    if( viewer->isAbleToDisplay(data) )
539 540
    {
        item->setFlags( item->flags() | Qt::ItemIsUserCheckable );
541
        item->setCheckState( 0, viewer->isDisplayed(data)? Qt::Checked : Qt::Unchecked );
542 543 544
    }
    else
        item->setFlags( item->flags() & ~Qt::ItemIsUserCheckable );
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565

    for( auto c : data->GetChildren() )
        item->addChild( buildItemTree(c,viewer) );

    return item;
}


void updateTreeSelection( QTreeWidgetItem* item, QSet<GenericUIData*>& selectedItemSet )
{
    GenericUIData *data = ( (UIDataWidgetItem*) item)->getUIData();

    auto foundItem = selectedItemSet.find( data );
    if( foundItem != selectedItemSet.end() )
    {
        item->setSelected( true );
        selectedItemSet.erase( foundItem );
    }

    for( int i=0; i<item->childCount(); ++i )
        updateTreeSelection( item->child(i), selectedItemSet );
566 567

    item->setExpanded( data->IsExpanded() );
568 569 570
}


571
void UIMainWindow::updateCurrentProjectContent()
572
{
573 574 575 576
    UIDataWidget *treeView = ui->tableCurrentProjContent;
    UIProject *project = getCurrentProject();
    QString typeFilter = ui->comboTypeFilter->currentText();

577
    QSet<GenericUIData*> selectedItemSet;
578
    for( auto s : treeView->selectedData() )
579 580
        selectedItemSet.insert( s );

581 582 583
	QScrollBar *scrollBar = treeView->verticalScrollBar();
	int scrollBarValue = scrollBar->value();

584 585
    treeView->updateContentBegin();
	treeView->clear();
586

587
	if( project )
588
	{
589
		auto &data = project->GetAll();
590

591
		treeView->setSortingEnabled( false );
592 593 594 595

		for( auto d : data )
		{
			QString typeName = d->GetTypeString();
596
			if( !d->HasParent()  &&  typeFilter.isNull()  ||  typeName == typeFilter )
597
				treeView->addTopLevelItem( buildItemTree(d,m_CurrentViewer) );
598 599
		}

600
		treeView->setSortingEnabled( true );
601
        //treeView->resizeColumnToContents(0);
602

603 604
        for( int i=0; i<treeView->topLevelItemCount(); ++i )
            updateTreeSelection( treeView->topLevelItem(i), selectedItemSet );
605
    }
606 607

    treeView->updateContentEnd();
608 609 610 611 612

	if( scrollBarValue <= scrollBar->maximum() )
		scrollBar->setValue( scrollBarValue );
	else
		scrollBar->setValue( scrollBar->maximum() );
613 614 615
}


616
void UIMainWindow::updateTypeFilters()
617 618 619 620 621 622
{
	QString currentFilterBackup = ui->comboTypeFilter->currentText();


	ui->comboTypeFilter->clear();

623
	if( getCurrentProject() )
624
	{
625
		auto &data = getCurrentProject()->GetAll();
626 627 628 629 630
		std::set<QString> foundTypeNames;

		for( auto d=data.begin(); d!=data.end(); ++d )
			foundTypeNames.insert( (*d)->GetTypeString() );

631
		ui->comboTypeFilter->addItem( QString() );
632 633 634 635 636 637 638 639 640 641 642 643 644
		for( auto name=foundTypeNames.begin(); name!=foundTypeNames.end(); ++name )
			ui->comboTypeFilter->addItem( *name );

		ui->comboTypeFilter->setCurrentIndex( 0 );
	}


	int backedupFilterId = ui->comboTypeFilter->findText( currentFilterBackup );
	if( backedupFilterId )
		ui->comboTypeFilter->setCurrentIndex( backedupFilterId );
}


645
bool UIMainWindow::closeCurrentProject()
646
{
Frédéric Larue's avatar
Frédéric Larue committed
647
    if( m_CurrentProject )
648
    {
649 650 651
        if( !onClosingProject(m_CurrentProject->project) )
            return false;

652 653 654
        for( auto d : m_CurrentProject->project->GetAll() )
            emit aboutToDelete( d );

Frédéric Larue's avatar
Frédéric Larue committed
655 656 657
        m_CurrentProject->project->RemoveAndDeleteAll();
        delete m_CurrentProject->project;
        delete m_CurrentProject; m_CurrentProject = NULL;
658
        ui->comboProject->removeItem( ui->comboProject->currentIndex() );
659 660 661

        // Last project closed? Restore the default application view mode.
        if( !m_CurrentProject )
662
            setViewerMode( DISPLAY_DOF_3D, true );
663 664 665
    }

    return true;
666 667 668
}


669
bool UIMainWindow::closeAllProjects()
670
{
Frédéric Larue's avatar
Frédéric Larue committed
671
	while( getCurrentProject() )
672
		if( !closeCurrentProject() )
673 674 675 676 677 678
			return false;

	return true;
}


679
void UIMainWindow::modifyItem( QTreeWidgetItem* entryInTable, int column )
680 681 682 683 684 685 686 687 688 689 690 691 692 693
{
	GenericUIData *item = ((UIDataWidgetItem*) entryInTable)->getUIData();

	/* Perform renaming if the text content of the table entry has changed */
	if( item  &&  entryInTable->text(0) != item->GetFileName() )
	{
		QString newName = entryInTable->text(0);

		if( newName.isEmpty() )
		{
			QMessageBox::information(this, "Invalid renaming", QString("Filename \"") + entryInTable->text(0) + QString("\" is invalid"), QMessageBox::Ok);
			return;
		}

Frédéric Larue's avatar
Frédéric Larue committed
694 695 696
        getCurrentProject()->Rename( item, newName );
		entryInTable->setText( 0, item->GetFileName() );
        if( item->GetDisplayOptions() )
697
            item->GetDisplayOptions()->setTitle( item->GetBaseName() );
698
	}
699 700 701 702 703
}


void UIMainWindow::modifyVisibility( const QList<QTreeWidgetItem*>& entriesInTable )
{
704 705
    int previousDisplayedCount = (int) m_CurrentViewer->getDisplayables().size();
    int nActivatedDisplays = 0;
706 707 708 709 710 711 712 713 714

    for( auto entry : entriesInTable )
    {
    	GenericUIData *item = ((UIDataWidgetItem*) entry)->getUIData();

	    if( (entry->flags() & Qt::ItemIsUserCheckable)  &&
            m_CurrentViewer->isDisplayed(item) != (entry->checkState(0) == Qt::Checked) )
	    {
		    if( !m_CurrentViewer->isDisplayed(item) )
715
            {
716
			    m_CurrentViewer->addDisplayable( item );
717 718
                nActivatedDisplays ++;
            }
719 720 721 722 723
		    else
	    	    m_CurrentViewer->removeDisplayable( item );
	    }
    }

724 725 726 727
    int newDisplayedCount = (int) m_CurrentViewer->getDisplayables().size();

    if( (previousDisplayedCount == 0  &&  newDisplayedCount != 0) ||
        (previousDisplayedCount != 0  &&  newDisplayedCount == 1  &&  nActivatedDisplays != 0) )
728
        reframeScene();
729 730

	m_CurrentViewer->updateSelection( selection() );
731 732 733
}


734
void UIMainWindow::showAboutDialog()
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
{
	QDialog dlg;

	// Back / forward buttons

	QHBoxLayout* btnsLayout = new QHBoxLayout();

	QPushButton* backBtn = new QPushButton();
	QPushButton* fwdBtn = new QPushButton();

	QPixmap leftArrow(":/AboutLicences/resources/AboutLicences/ArrowLeft.png");
	QPixmap rightArrow = QPixmap::fromImage(leftArrow.toImage().mirrored(true));

	backBtn->setIcon(leftArrow);
	fwdBtn->setIcon(rightArrow);

	btnsLayout->addWidget(backBtn);
	btnsLayout->addWidget(fwdBtn);
	btnsLayout->addStretch();

	// Browser view

#ifdef QT_WEBKIT_AVAILABLE
	QWebView* browser = new QWebView(this);
	browser->setUrl(QUrl("qrc:/AboutLicences/resources/AboutLicences/main.html"));

	connect(backBtn, SIGNAL(clicked()), browser, SLOT(back()));
	connect(fwdBtn, SIGNAL(clicked()), browser, SLOT(forward()));
#else
	QTextBrowser* browser = new QTextBrowser(this);	
	browser->setSource(QUrl("qrc:/AboutLicences/resources/AboutLicences/main.html"));

	connect(backBtn, SIGNAL(clicked()), browser, SLOT(backward()));
	connect(fwdBtn, SIGNAL(clicked()), browser, SLOT(forward()));
#endif

	browser->setMinimumSize(QSize(640, 480));


	// Dialog box layout

	QVBoxLayout* layout = new QVBoxLayout;

	layout->addLayout(btnsLayout);
	layout->addWidget(browser);
	dlg.setLayout(layout);

	dlg.setWindowTitle("About");

	dlg.exec();
}


788
void UIMainWindow::displayPluginsList()
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
{
	QString appPath = QApplication::applicationDirPath();

	QChar lastChar = appPath.at(appPath.length() - 1);

	if(!(lastChar == '/' || lastChar == '\\'))
		appPath.append("/");



	// Create categories

	QTreeWidgetItem* categories[5];
		
	static const char* catNames[5] = { "Unknown", "Display", "Import", "Export", "Tools" };
	unsigned int catCount[5] = { 0 };

	categories[0] = NULL;

	for(unsigned int i = 1 ; i < 5 ; i++)
		categories[i] = new QTreeWidgetItem();


	// Populate categories w/ plugins

814
	for(QList<QPluginLoader*>::iterator p = m_pluginLoaders.begin() ; p != m_pluginLoaders.end() ; ++p)
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
	{
        QObject *plugin = (*p)->instance();

		unsigned int cat = 0;

		if(qobject_cast<DisplayableFactoryInterface*>(plugin))
			cat = 1;
		else if(qobject_cast<ImportInterface*>(plugin))
			cat = 2;
		else if(qobject_cast<ExportInterface*>(plugin))
			cat = 3;
        else if(qobject_cast<ToolInterface*>(plugin))
			cat = 4;

		QString name = (*p)->fileName();

		if(name.startsWith(appPath))
			name = name.right(name.length() - appPath.length());

		if(!cat)
			categories[0] = new QTreeWidgetItem(QStringList(QString(catNames[0])));

		categories[cat]->addChild(new QTreeWidgetItem(QStringList(name)));
		catCount[cat]++;
	}


	// Set category-header item's text now that population count is known

	for(unsigned int i = 0 ; i < 5 ; i++)
		if(categories[i])
			categories[i]->setText(0, QString("%1 [%2]").arg(catNames[i]).arg(catCount[i]));


	// Create and display dialog

	QDialog dlg;

	QTreeWidget* tree = new QTreeWidget;
	tree->setColumnCount(1);
	tree->header()->hide();

	tree->setMinimumSize(300, 600);

	for(unsigned int i = 1 ; i < 5 ; i++)
	{
		tree->addTopLevelItem(categories[i]);
		categories[i]->setExpanded(true);
	}

	if(categories[0])
	{
		tree->addTopLevelItem(categories[0]);
		categories[0]->setExpanded(true);
	}

	unsigned int allCount = 0;

	for(unsigned int i = 0 ; i < 5 ; i++)
		allCount += catCount[i];

	QVBoxLayout* layout = new QVBoxLayout;

	layout->addWidget(tree);
	dlg.setLayout(layout);
	dlg.setWindowTitle(QString("Plugins loaded [%1 plugins]").arg(allCount));

	dlg.exec();
}


886
void UIMainWindow::addToCurrentProject()
887
{
888
    // Build the list of filters for the file dialog by parsing all the possible import plug-ins.
889

890
    QString allImportFilters, allSupportedFiles;
891

892
    for( ImportHandle& importer : m_ImportPlugins )
893
    {
894
        QStringList filesExt, filesDesc;
895 896
        importer.plugin->fileFilters( importer.id, filesExt, filesDesc );

897
        QMap< QString, QStringList > extensionsSortedByDesc;
898 899 900 901 902 903
        for( QStringList::iterator ext=filesExt.begin(), desc=filesDesc.begin(); ext!=filesExt.end(); ++ext, ++desc )
            extensionsSortedByDesc[ *desc ].push_back( *ext );

        for( QMap<QString,QStringList>::iterator desc=extensionsSortedByDesc.begin(); desc!=extensionsSortedByDesc.end(); ++desc )
        {
            allImportFilters += desc.key() + " (";
904
            for( QString& ext : desc.value() )
905 906 907 908 909 910 911 912 913 914 915 916
            {
                allImportFilters  += " *." + ext;
                allSupportedFiles += " *." + ext;
            }
            allImportFilters += " );;";
        }
    }

    if( !allSupportedFiles.isNull() )
        allImportFilters = "All supported files (" + allSupportedFiles + " );;" + allImportFilters;


917 918
    // Open the file dialog enabling the user to select the file to be imported.

919 920 921 922 923 924 925 926
    QStringList selectedFiles = QFileDialog::getOpenFileNames( this,
                                                               "Add to current project",
                                                               QString(),
                                                               allImportFilters );


	// Perform import

927 928
    if( !selectedFiles.empty() )
    	importFiles(selectedFiles);
929 930 931
}


932
void UIMainWindow::removeFromCurrentProject()
933 934 935 936 937 938 939 940
{
	QList<QTreeWidgetItem*> tempList = ui->tableCurrentProjContent->selectedItems();
	if( tempList.empty() )
		return;

	QList<UIDataWidgetItem*> *itemsToRemove = (QList<UIDataWidgetItem*>*) &tempList;


941 942 943 944 945 946 947 948 949 950 951
	QString confirmMsg;
    if( itemsToRemove->size() <= 10 )
    {
        confirmMsg = "Remove the following items from the current project?\n";
        auto i = itemsToRemove->begin();
        confirmMsg += (*i)->text(0);
        for( ++i; i!=itemsToRemove->end(); ++i )
            confirmMsg += ",  " + (*i)->text(0);
    }
    else
        confirmMsg = "Remove the " + QString::number(itemsToRemove->size()) + " selected items from the current project?";
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967

	QMessageBox::StandardButton answer = QMessageBox::warning(
		this,
		tr("Removal confirmation"),
		confirmMsg,
		QMessageBox::Ok | QMessageBox::Cancel
		);

	if( answer == QMessageBox::Ok )
	{
		QList<GenericUIData*> toRemove;
		for( auto i=itemsToRemove->begin(); i!=itemsToRemove->end(); ++i )
			toRemove.push_back( (*i)->getUIData() );

		for( auto i=toRemove.begin(); i!=toRemove.end(); ++i )
        {
968
            emit aboutToDelete( *i );
969
            getCurrentProject()->RemoveAndDelete( *i );
970 971 972 973
        }

		updateTypeFilters();
		updateCurrentProjectContent();
974
        update();
975 976 977 978
	}
}


979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
bool UIMainWindow::saveProjectOptions( const QString &filePath, UIProject *project )
{
    // Open the destination file.

    QFile file( filePath );
    if( !file.open( QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text ) )
        return false;

    // Create a stream for writing formatted text to the file.

    QTextStream stream( &file );

    // Write the opening tag of the project option XML root node.

    stream << "<PROJECTOPTIONS Name=\"" << project->GetFileName() << "\">\n";

    // Save current display options for each project datum.

    for( auto d : project->GetAll() )
        if( d->GetDisplayOptions() )
        {
            QList<UIParam*> params = d->GetDisplayOptions()->GetAll();
            if( params.isEmpty() )
                continue;

            stream << "  <DISPLAYOPTIONS Source=\"" << d->GetFileName() << "\">\n";
            for( auto p : params )
            {
                stream << "    <PARAM Id=\"" << p->Id() << "\" ";
                stream << "Value=\"" << p->ValueString().replace( '\\', "\\\\" ).replace( '"', "\\\"" ) << "\"/>\n";
            }
            stream << "  </DISPLAYOPTIONS>\n";
        }

    // Save current option values for each tool.

    for( auto &tool : ui->toolSelector->allTools() )
        if( tool.param )
        {
            QString name = tool.plugin->name( tool.id );

            QList<UIParam*> params = tool.param->GetAll();
            if( params.isEmpty() )
                continue;

            stream << "  <TOOLOPTIONS Name=\"" << name << "\">\n";
            for( auto p : params )
            {
                stream << "    <PARAM Id=\"" << p->Id() << "\" ";
                stream << "Value=\"" << p->ValueString().replace( '\\', "\\\\" ).replace( '"', "\\\"" ) << "\"/>\n";
            }
            stream << "  </TOOLOPTIONS>\n";
        }

    // Save current viewer state.

    // Save the list of displayed data.

    stream << "  <DATASTATE>\n";
    for( auto &d : m_CurrentViewer->getDisplayables() )
        stream << "    <DISPLAYED Source=\"" << d.first->GetFileName() << "\"/>\n";

    // Save the list of selected data.

    for( auto d : ui->tableCurrentProjContent->selectedData() )
        stream << "    <SELECTED Source=\"" << d->GetFileName() << "\"/>\n";
    stream << "  </DATASTATE>\n";

    // Write the closing tag of the project option XML root node.

    // ... rajouter dans le menu Settings une dialog box permettant de choisir ce qui doit tre sauvegard en mme temps que le projet
    // ou bien le rajouter en tant qu'option lors de la sauvegarde indpendante d'un projet.

    stream << "</PROJECTOPTIONS>\n";

    return true;
}


1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
bool UIMainWindow::loadProjectOptions( const QString &filePath, UIProject *project )
{
    // Open the source file.

    QFile file( filePath );
    if( !file.open( QIODevice::ReadOnly | QIODevice::Text ) )
        return false;

    // Create a stream for the XML parsing of the file.

    QXmlStreamReader xml( &file );

    // Start parsing.

    enum ParsingState
    {
        PARSING_STARTS              ,
        IS_AT_ROOT_LEVEL            ,
        IS_READING_DISPLAY_OPTIONS  ,
        IS_READING_TOOL_OPTIONS     ,
        IS_READING_DATA_STATE       ,
    };

    ParsingState currentState = PARSING_STARTS;
    QString source;
    bool mustReadNext = true;

    while( !xml.atEnd() )
    {
        if( mustReadNext  &&  xml.readNext() != QXmlStreamReader::StartElement )
            continue;
        mustReadNext = true;

        QXmlStreamAttributes attr = xml.attributes();

        switch( currentState )
        {
            case PARSING_STARTS:
            {
                if( xml.name() != "PROJECTOPTIONS" )
                    return false;
                currentState = IS_AT_ROOT_LEVEL;
                break;
            }
            case IS_AT_ROOT_LEVEL:
            {
                if( xml.name() == "DISPLAYOPTIONS" )
                {
                    if( attr.hasAttribute("Source") )
                    {
                        source = attr.value("Source").toString();
                        currentState = IS_READING_DISPLAY_OPTIONS;
                        break;
                    }
                }
                else if( xml.name() == "TOOLOPTIONS" )
                {
                    if( attr.hasAttribute("Name") )
                    {
                        source = attr.value("Name").toString();
                        currentState = IS_READING_TOOL_OPTIONS;
                        break;
                    }
                }
                else if( xml.name() == "DATASTATE" )
                {
                    currentState = IS_READING_DATA_STATE;
                    break;
                }

                return false;
            }
            case IS_READING_DISPLAY_OPTIONS:
            {
                if( xml.name() != "PARAM" )
                {
                    mustReadNext = false;
                    currentState = IS_AT_ROOT_LEVEL;
                    break;
                }
                else if( !attr.hasAttribute("Id")  ||  !attr.hasAttribute("Value") )
                    return false;

                QString id = attr.value("Id").toString();
                QString value = attr.value("Value").toString();

                GenericUIData *d = project->GetByFilename( source );
                if( d )
                {
                    if( !d->GetDisplayOptions() )
                        m_DisplayableFactoryByTypes[ d->GetTypeString() ]->allocateDisplayOptions( d );

1150 1151 1152
                    UIParam *param = d->GetDisplayOptions()->Get( id );
                    if( param )
                        param->SetValueString( value );
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
                }

                break;
            }
            case IS_READING_TOOL_OPTIONS:
            {
                if( xml.name() != "PARAM" )
                {
                    mustReadNext = false;
                    currentState = IS_AT_ROOT_LEVEL;
                    break;
                }
                else if( !attr.hasAttribute("Id")  ||  !attr.hasAttribute("Value") )
                    return false;

                QString id = attr.value("Id").toString();
                QString value = attr.value("Value").toString();

                auto tool = ui->toolSelector->getToolByName( source );
                if( tool )
1173 1174 1175 1176 1177
                {
                    UIParam *param = tool->param->Get( id );
                    if( param )
                        param->SetValueString( value );
                }
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214

                break;
            }
            case IS_READING_DATA_STATE:
            {
                if( xml.name() == "DISPLAYED" )
                {
                    if( !attr.hasAttribute("Source") )
                        return false;

                    //GenericUIData *d = project->GetByFilename( attr.value("Source").toString() );
                    //if( d )
                    //    m_CurrentViewer->addDisplayable( d );
                }
                else if( xml.name() == "SELECTED" )
                {
                    if( !attr.hasAttribute("Source") )
                        return false;

                    //ui->tableCurrentProjContent->setItemSelected( )
                }
                else
                {
                    mustReadNext = false;
                    currentState = IS_AT_ROOT_LEVEL;
                }

                break;
            }
        }
    }


    return !xml.hasError();
}


1215
void UIMainWindow::saveCurrentProject()
1216
{
Frédéric Larue's avatar
Frédéric Larue committed
1217 1218 1219 1220 1221 1222 1223
    UIProject *project = getCurrentProject();
	if( !project )
        return;

    QString defaultPath = project->GetSaveDir() + project->GetFileName();
    if( defaultPath == "" )
        defaultPath = project->Name() + "." + projectFileExtension();
1224
        
Frédéric Larue's avatar
Frédéric Larue committed
1225 1226 1227 1228 1229 1230 1231
    QString file = QFileDialog::getSaveFileName(
		this,
		tr("Save project"),
		defaultPath,
		tr("Project Files (*.") + projectFileExtension() + ")"
		);

1232
	if( !file.isNull() )
Frédéric Larue's avatar
Frédéric Larue committed
1233 1234 1235 1236
	{
		QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) );
		bool saveOk = project->Save( file );
		QApplication::restoreOverrideCursor();
1237

Frédéric Larue's avatar
Frédéric Larue committed
1238
		if( saveOk )
1239
		{
Frédéric Larue's avatar
Frédéric Larue committed
1240 1241
			std::cout << "Project <B>" << project->Name().toStdString() << "</B> successfully saved to file <B>" << file.toStdString() << "</B>." << std::endl;
            //SetMainWindowTitleInfos( m_CurrentProject->GetSaveDir()+m_CurrentProject->GetFilename() );
1242 1243
            saveProjectOptions( project->GetSaveDir()+".project.opt", project );
        }
Frédéric Larue's avatar
Frédéric Larue committed
1244 1245 1246 1247 1248 1249 1250 1251 1252
		else
		{
			QMessageBox::critical(
                this,
                "Project save failure",
                QString("Saving project ") + project->Name() + " to file " + file + " failed.",
                QMessageBox::Ok
            );
            std::cout << "Saving project <B>" << project->Name().toStdString() << "</B> to file <B>" << file.toStdString() << "</B> failed." << std::endl;
1253
		}
1254 1255

        updateRecentListEntry( file );
1256 1257 1258 1259
	}
}


1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
void UIMainWindow::initializeCentralWidgetStack()
{
    QWidget *w = new QWidget();
    w->setLayout( new QVBoxLayout() );
    w->layout()->setContentsMargins( 0, 0, 0, 0 );
    w->layout()->setSpacing( 0 );
    setCentralWidget( w );
}


1270 1271 1272 1273 1274 1275 1276
void UIMainWindow::releaseCentralWidgetStack()
{
    while( !m_CentralWidgetStack.isEmpty() )
        popCentralWidget();
}


1277 1278 1279
void UIMainWindow::pushCentralWidget( QWidget* widget )
{
    if( !m_CentralWidgetStack.isEmpty() )
1280
        m_CentralWidgetStack.last().widget->hide();
1281

1282 1283 1284 1285 1286
    WidgetStackItem stackItem;
    stackItem.isSplit = false;
    stackItem.widget  = widget;

    m_CentralWidgetStack.append( stackItem );
1287 1288 1289 1290 1291 1292
    centralWidget()->layout()->addWidget( widget );

    widget->show();
}


1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
void UIMainWindow::splitCentralWidget( QWidget* widget, Qt::Orientation orientation, Qt::AlignmentFlag location, float spaceRatio )
{
    assert( !m_CentralWidgetStack.isEmpty() );
    //assert( orientation == Qt::Horizontal  &&  (location == Qt::AlignLeft  ||  location == Qt::AlignRight ) );
    //assert( orientation == Qt::Vertical    &&  (location == Qt::AlignTop   ||  location == Qt::AlignBottom) );

    QWidget *previous = m_CentralWidgetStack.last().widget;

    QGridLayout *layout = new QGridLayout();
    layout->setContentsMargins( 0, 0, 0, 0 );
    layout->setSpacing( 4 );

    if( orientation == Qt::Horizontal )
    {
        widget->setMaximumWidth( spaceRatio*previous->width() );
        if( location == Qt::AlignLeft )
        {
            layout->addWidget( widget  , 0,0 );
            layout->addWidget( previous, 0,1 );
        }
        else
        {
            layout->addWidget( widget  , 0,1 );
            layout->addWidget( previous, 0,0 );
        }
    }
    else
    {
        widget->setMaximumHeight( spaceRatio*previous->height() );
        if( location == Qt::AlignTop )
        {
            layout->addWidget( widget  , 0,0 );
            layout->addWidget( previous, 1,0 );
        }
        else
        {
            layout->addWidget( widget  , 1,0 );
            layout->addWidget( previous, 0,0 );
        }
    }

    WidgetStackItem stackItem;
    stackItem.isSplit     = true;
    stackItem.widget      = new QWidget();

    stackItem.widget->setLayout( layout );

    m_CentralWidgetStack.append( stackItem );
    centralWidget()->layout()->addWidget( stackItem.widget );

    widget->show();
}


1347 1348
void UIMainWindow::popCentralWidget()
{
1349 1350
    WidgetStackItem stackItem = m_CentralWidgetStack.takeLast();
    stackItem.widget->hide();
1351

1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
    if( stackItem.isSplit )
    {
        QWidget *widgetToDelete, *widgetToKeep;
        for( auto obj : stackItem.widget->children() )
            if( QWidget *w = dynamic_cast<QWidget*>(obj) )
            {
                if( w == m_CentralWidgetStack.last().widget )
                    widgetToKeep = w;
                else
                    widgetToDelete = w;
            }

        centralWidget()->layout()->removeWidget( stackItem.widget );
        stackItem.widget->setParent( NULL );

        stackItem.widget->layout()->removeWidget( widgetToKeep );