UIMainWindow.cpp 69.6 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
    return true;
74 75 76 77 78
}


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

81
    QSettings *settings = UI::GetUserSettings();
Frédéric Larue's avatar
Frédéric Larue committed
82 83

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

85
    if( !settings->contains("geometry")  ||  !settings->contains("windowState") )
86 87
        return false;

Frédéric Larue's avatar
Frédéric Larue committed
88 89
    restoreGeometry( settings->value("geometry"   ).toByteArray() );
    restoreState   ( settings->value("windowState").toByteArray() );
90

Frédéric Larue's avatar
Frédéric Larue committed
91 92 93
    // Load the list of recently used projects.

    QStringList recents = settings->value( "recent" ).toStringList();
94 95 96
    for( auto r=recents.rbegin(); r!=recents.rend(); ++r )
        updateRecentListEntry( *r );

97 98 99 100
    return true;
}


101 102 103 104
void UIMainWindow::updateRecentListEntry( const QString& path )
{
    bool isVeryFirstEntry = m_RecentProjects.empty();

105 106 107 108 109 110
    // 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;

111 112 113 114 115 116 117 118 119 120 121 122 123
    // 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() )
    {
124
        newFirstEntry = new QAction( path, NULL );
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
        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;

140 141
    // Insert the path to the beginning of the list.

142 143 144 145 146 147
    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 );

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

150 151 152 153
    if( m_RecentProjects.size() > RECENT_PROJECT_MAX_LIST_SIZE )
    {
        ui->menuFile->removeAction( m_RecentProjects.back() );
        m_RecentProjects.back()->deleteLater();
154
        m_RecentProjects.pop_back();
155 156
    }

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

159 160 161 162 163 164 165 166 167 168 169
    if( isVeryFirstEntry )
        ui->menuFile->insertSeparator( ui->menuFile->actions().back() );
}


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


170
void UIMainWindow::declareCustomMenuAction( const QString& menuName, QAction* action, bool insertSeparatorBefore )
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
{
    // 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()) );
189 190 191 192

    if( insertSeparatorBefore )
        menu->addSeparator();

193 194 195 196
    menu->addAction( action );
}


197
void UIMainWindow::initializeUserSettings()
198
{
199 200
    QString compagnyName, applicationName, shortDescription;
    applicationInfo( compagnyName, applicationName, shortDescription );
201
    UI::InitializeUserSettings( compagnyName + "/" + applicationName );
202
}
Frédéric Larue's avatar
Frédéric Larue committed
203 204


205 206
void UIMainWindow::init()
{
207 208
    onDeclaringToolCategories();    // must be called before setupUi(...) because tool categories are required for the AlgorithmSelector widget.

209 210
    ui->setupUi(this);

211 212
    ui->menuView->addAction( ui->dockProjectManager->toggleViewAction() );
    ui->menuView->addAction( ui->dockTools->toggleViewAction() );
213 214
    onDeclaringCustomMenus();

215 216 217 218 219
    loadPlugins();

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

220
    initRenderOptions();
221 222
    initializeCentralWidgetStack();
    setViewerMode( DISPLAY_DOF_3D );
223

224 225 226 227
    ui->comboProject->setContextMenuPolicy( Qt::CustomContextMenu );
    connect( ui->comboProject, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showProjectContextMenu(QPoint)) );
    connect( ui->comboProject, SIGNAL(currentIndexChanged(int)), this, SLOT(currentProjectChanged()) );

228 229 230 231 232 233 234 235 236
    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()) );

237
    connect( ui->actionRenderOptions, SIGNAL(triggered()), this, SLOT(showRenderingOptionDialog()) );
238 239
	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
240
	connect( ui->actionSaveProject, SIGNAL(triggered()), this, SLOT(saveCurrentProject()) );
241
	connect( ui->actionLoadProject, SIGNAL(triggered()), this, SLOT(openProject()) );
Frédéric Larue's avatar
Frédéric Larue committed
242
	connect( ui->actionCloseProject, SIGNAL(triggered()), this, SLOT(closeCurrentProject()) );
243 244 245
	connect( ui->comboTypeFilter, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(updateCurrentProjectContent()) );
	connect( ui->actionAbout, SIGNAL(triggered()), this, SLOT(showAboutDialog()) );
	connect( ui->actionDisplayPluginsList, SIGNAL(triggered()), this, SLOT(displayPluginsList()) );
246 247
    connect( ui->action2DViewer, SIGNAL(triggered()), this, SLOT(setDefault3DViewer()) );
	connect( ui->action3DViewer, SIGNAL(triggered()), this, SLOT(setDefault2DViewer()) );
248 249 250
	connect( ui->actionClone, SIGNAL(triggered()), this, SLOT(cloneSelectedManageables()) );
    connect( ui->actionWireframeMode, SIGNAL(triggered()), this, SLOT(toWireframeMode()) );
    connect( ui->actionSolidMode, SIGNAL(triggered()), this, SLOT(toSolidMode()) );
251
    connect( m_CurrentViewer, SIGNAL(keyPressed(QKeyEvent*)), this, SLOT(keyPressedInGLViewer(QKeyEvent*)) );
252
    connect( ui->actionCustomizeTheme, SIGNAL(triggered()), this, SLOT(showThemeSettingsDialog()) );
253 254 255 256 257 258 259

    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*)) );
260
	connect( ui->tableCurrentProjContent, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(modifyItem(QTreeWidgetItem*,int)) );
261
	connect( ui->tableCurrentProjContent, SIGNAL(visibilityChanged(QList<QTreeWidgetItem*>)), this, SLOT(modifyVisibility(QList<QTreeWidgetItem*>)) );
262 263
	connect( ui->tableCurrentProjContent, SIGNAL(removalAsked()), this, SLOT(removeFromCurrentProject()) );
    connect( ui->tableCurrentProjContent, SIGNAL(itemDoubleClicked(GenericUIData*)), this, SLOT(onItemDoubleClicked(GenericUIData*)) );
264
    connect( ui->tableCurrentProjContent, SIGNAL(parentDataChanged(GenericUIData*,GenericUIData*,GenericUIData*)), this, SLOT(dataParentChanged(GenericUIData*,GenericUIData*,GenericUIData*)) );
265
    connect( m_CurrentViewer, SIGNAL(dataSelected(GenericUIData*,Qt::KeyboardModifiers)), ui->tableCurrentProjContent, SLOT(updateSelection(GenericUIData*,Qt::KeyboardModifiers)) );
266
    connect( ui->tableCurrentProjContent, SIGNAL(itemSelectionChanged()), this, SLOT(selectionChanged()) );
267 268 269 270 271

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


272
    setMainWindowTitleInfos( "" );
273 274 275 276 277

    if( loadUISettings() )
        show();
    else
    	showMaximized();
278 279 280
}


281 282
void UIMainWindow::release()
{
283 284
    saveUISettings();

285
    releaseCentralWidgetStack();
286 287 288

    closeAllProjects();

289
    UI::ReleaseUserSettings();
Frédéric Larue's avatar
Frédéric Larue committed
290

291 292 293 294
    ui->toolSelector->releaseAllTools();
    delete ui;

    unloadPlugins();
295 296 297
}


298
void UIMainWindow::setMainWindowTitleInfos( const QString& str )
299
{
Frédéric Larue's avatar
Frédéric Larue committed
300 301 302 303
    QString compagnyName, applicationName, shortDescription;
    applicationInfo( compagnyName, applicationName, shortDescription );

    QString title = applicationName + " / " + shortDescription;
304 305 306 307 308 309 310 311 312 313 314

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

	setWindowTitle( title );
}


315
void UIMainWindow::loadPlugins()
316 317 318 319 320 321
{
    // Recover the list of all files contained in the plugin directory.
    QDir pluginsDir( qApp->applicationDirPath() );
    if( !pluginsDir.cd( "plugins" ) )
        return;

322

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
	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) );

338
		if( !loader->load() )
339 340 341 342 343 344 345 346 347
		{
			delete loader;
		}
		else
		{
        	QObject *plugin = loader->instance();

	        if( plugin )
    	    {
348
				m_pluginLoaders.push_back( loader );
349 350 351 352 353 354 355

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

	            DisplayableFactoryInterface *dispFactory = qobject_cast<DisplayableFactoryInterface*>( plugin );
	            if( dispFactory )
356
                {
357 358
	                m_DisplayablePlugins.push_back( dispFactory );

359 360 361 362 363 364
                    QVector<QString> acceptedTypes;
                    dispFactory->acceptedDataTypes( acceptedTypes );
                    for( auto &type : acceptedTypes )
                        m_DisplayableFactoryByTypes[ type ] = dispFactory;
                }

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
	            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();
}


403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
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;
}


423
QList<GenericUIData*> UIMainWindow::selection( const QStringList& typeFilters )
424
{
425 426 427 428 429 430 431
    return ui->tableCurrentProjContent->selectedData( typeFilters );
}


QList<GenericUIData*> UIMainWindow::selection( const QString& typeFilter )
{
    return selection( QStringList(typeFilter) );
432 433 434
}


435
void UIMainWindow::giveSelectionToTool()
436
{
437 438
	QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) );

439
    m_ToolTimer.start();
440
    ui->toolSelector->applyCurrentToolOn( selection(), this, m_CurrentViewer, getCurrentProject() );
441 442 443
}


444
void UIMainWindow::toolExecutionFinished( bool needUpdate )
445
{
446 447 448 449 450 451
    if( needUpdate )
    {
	    updateTypeFilters();
	    updateCurrentProjectContent();

        updateDisplayables();
452

453
        m_CurrentViewer->updateSelectionZBuffer();
454

455 456
        update();
    }
457 458

	QApplication::restoreOverrideCursor();
459 460 461
}


462
void UIMainWindow::update( bool mustBeUpdated )
463 464 465 466 467 468 469 470 471 472 473
{
	if( mustBeUpdated )
	{
		QMainWindow::update();

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


474
void UIMainWindow::newProject()
475
{
476
    /* Create the dialog box for asking information about the project to create */
477 478 479
    UIParamDialog dlg( "Project settings", this );
    dlg.Add( new UIParamString("name", "Project name", "Name of the new project to create.", "Default project" ) );
    onDeclaringNewProjectParameters( dlg.GetParameters() );
480

481 482
    dlg.GetParameters().GetString("name")->Widget()->setFocus();

483
	/* */
484
	if( dlg.exec() == QDialog::Accepted )
485
	{
486
        QString projectName = dlg.GetParameters().GetString("name")->Value();
487
		if( !projectName.size() )
488 489 490 491 492 493 494 495 496
		{
			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
497
        ProjectHandle *pHndl = new ProjectHandle();
498
        pHndl->project = onCreatingProject( projectName, &dlg.GetParameters() );
Frédéric Larue's avatar
Frédéric Larue committed
499 500
	    ui->comboProject->addItem( pHndl->project->Name(), QVariant::fromValue<void*>(pHndl) );
	    ui->comboProject->setCurrentIndex( ui->comboProject->count()-1 );
501 502 503 504
	}
}


505
void UIMainWindow::openProject()
506
{
507
	QString fileName = QFileDialog::getOpenFileName( this, tr("Loading an existing project"), "", tr("Project Files (*.")+projectFileExtension()+")" );
508
	if( fileName.isNull() )
509 510
		return;

511
	loadProject(fileName);
512 513 514 515 516 517 518 519
}


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

    if( viewer->isAbleToDisplay(data) )
520 521
    {
        item->setFlags( item->flags() | Qt::ItemIsUserCheckable );
522
        item->setCheckState( 0, viewer->isDisplayed(data)? Qt::Checked : Qt::Unchecked );
523 524 525
    }
    else
        item->setFlags( item->flags() & ~Qt::ItemIsUserCheckable );
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546

    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 );
547 548

    item->setExpanded( data->IsExpanded() );
549 550 551
}


552
void UIMainWindow::updateCurrentProjectContent()
553
{
554 555 556 557
    UIDataWidget *treeView = ui->tableCurrentProjContent;
    UIProject *project = getCurrentProject();
    QString typeFilter = ui->comboTypeFilter->currentText();

558
    QSet<GenericUIData*> selectedItemSet;
559
    for( auto s : treeView->selectedData() )
560 561
        selectedItemSet.insert( s );

562 563 564
	QScrollBar *scrollBar = treeView->verticalScrollBar();
	int scrollBarValue = scrollBar->value();

565 566
    treeView->updateContentBegin();
	treeView->clear();
567

568
	if( project )
569
	{
570
		auto &data = project->GetAll();
571

572
		treeView->setSortingEnabled( false );
573 574 575 576

		for( auto d : data )
		{
			QString typeName = d->GetTypeString();
577
			if( !d->HasParent()  &&  typeFilter.isNull()  ||  typeName == typeFilter )
578
				treeView->addTopLevelItem( buildItemTree(d,m_CurrentViewer) );
579 580
		}

581
		treeView->setSortingEnabled( true );
582
        //treeView->resizeColumnToContents(0);
583

584 585
        for( int i=0; i<treeView->topLevelItemCount(); ++i )
            updateTreeSelection( treeView->topLevelItem(i), selectedItemSet );
586
    }
587 588

    treeView->updateContentEnd();
589 590 591 592 593

	if( scrollBarValue <= scrollBar->maximum() )
		scrollBar->setValue( scrollBarValue );
	else
		scrollBar->setValue( scrollBar->maximum() );
594 595 596
}


597
void UIMainWindow::updateTypeFilters()
598 599 600 601 602 603
{
	QString currentFilterBackup = ui->comboTypeFilter->currentText();


	ui->comboTypeFilter->clear();

604
	if( getCurrentProject() )
605
	{
606
		auto &data = getCurrentProject()->GetAll();
607 608 609 610 611
		std::set<QString> foundTypeNames;

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

612
		ui->comboTypeFilter->addItem( QString() );
613 614 615 616 617 618 619 620 621 622 623 624 625
		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 );
}


626
bool UIMainWindow::closeCurrentProject()
627
{
Frédéric Larue's avatar
Frédéric Larue committed
628
    if( m_CurrentProject )
629
    {
630 631 632
        if( !onClosingProject(m_CurrentProject->project) )
            return false;

633 634 635
        for( auto d : m_CurrentProject->project->GetAll() )
            emit aboutToDelete( d );

Frédéric Larue's avatar
Frédéric Larue committed
636 637 638
        m_CurrentProject->project->RemoveAndDeleteAll();
        delete m_CurrentProject->project;
        delete m_CurrentProject; m_CurrentProject = NULL;
639
        ui->comboProject->removeItem( ui->comboProject->currentIndex() );
640 641 642
    }

    return true;
643 644 645
}


646
bool UIMainWindow::closeAllProjects()
647
{
Frédéric Larue's avatar
Frédéric Larue committed
648
	while( getCurrentProject() )
649
		if( !closeCurrentProject() )
650 651 652 653 654 655
			return false;

	return true;
}


656
void UIMainWindow::modifyItem( QTreeWidgetItem* entryInTable, int column )
657 658 659 660 661 662 663 664 665 666 667 668 669 670
{
	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
671 672 673
        getCurrentProject()->Rename( item, newName );
		entryInTable->setText( 0, item->GetFileName() );
        if( item->GetDisplayOptions() )
674
            item->GetDisplayOptions()->setTitle( item->GetBaseName() );
675
	}
676 677 678 679 680
}


void UIMainWindow::modifyVisibility( const QList<QTreeWidgetItem*>& entriesInTable )
{
681 682
    int previousDisplayedCount = (int) m_CurrentViewer->getDisplayables().size();
    int nActivatedDisplays = 0;
683 684 685 686 687 688 689 690 691

    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) )
692
            {
693
			    m_CurrentViewer->addDisplayable( item );
694 695
                nActivatedDisplays ++;
            }
696 697 698 699 700
		    else
	    	    m_CurrentViewer->removeDisplayable( item );
	    }
    }

701 702 703 704
    int newDisplayedCount = (int) m_CurrentViewer->getDisplayables().size();

    if( (previousDisplayedCount == 0  &&  newDisplayedCount != 0) ||
        (previousDisplayedCount != 0  &&  newDisplayedCount == 1  &&  nActivatedDisplays != 0) )
705
        reframeScene();
706 707

	m_CurrentViewer->updateSelection( selection() );
708 709 710
}


711
void UIMainWindow::showAboutDialog()
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 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
{
	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();
}


765
void UIMainWindow::displayPluginsList()
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
{
	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

791
	for(QList<QPluginLoader*>::iterator p = m_pluginLoaders.begin() ; p != m_pluginLoaders.end() ; ++p)
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 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
	{
        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();
}


863
void UIMainWindow::addToCurrentProject()
864
{
865
    // Build the list of filters for the file dialog by parsing all the possible import plug-ins.
866

867
    QString allImportFilters, allSupportedFiles;
868

869
    for( ImportHandle& importer : m_ImportPlugins )
870
    {
871
        QStringList filesExt, filesDesc;
872 873
        importer.plugin->fileFilters( importer.id, filesExt, filesDesc );

874
        QMap< QString, QStringList > extensionsSortedByDesc;
875 876 877 878 879 880
        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() + " (";
881
            for( QString& ext : desc.value() )
882 883 884 885 886 887 888 889 890 891 892 893
            {
                allImportFilters  += " *." + ext;
                allSupportedFiles += " *." + ext;
            }
            allImportFilters += " );;";
        }
    }

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


894 895
    // Open the file dialog enabling the user to select the file to be imported.

896 897 898 899 900 901 902 903
    QStringList selectedFiles = QFileDialog::getOpenFileNames( this,
                                                               "Add to current project",
                                                               QString(),
                                                               allImportFilters );


	// Perform import

904 905
    if( !selectedFiles.empty() )
    	importFiles(selectedFiles);
906 907 908
}


909
void UIMainWindow::removeFromCurrentProject()
910 911 912 913 914 915 916 917
{
	QList<QTreeWidgetItem*> tempList = ui->tableCurrentProjContent->selectedItems();
	if( tempList.empty() )
		return;

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


918 919 920 921 922 923 924 925 926 927 928
	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?";
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944

	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 )
        {
945
            emit aboutToDelete( *i );
946
            getCurrentProject()->RemoveAndDelete( *i );
947 948 949 950
        }

		updateTypeFilters();
		updateCurrentProjectContent();
951
        update();
952 953 954 955
	}
}


956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 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
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;
}


1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 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
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 );

1127 1128 1129
                    UIParam *param = d->GetDisplayOptions()->Get( id );
                    if( param )
                        param->SetValueString( value );
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
                }

                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 )
1150 1151 1152 1153 1154
                {
                    UIParam *param = tool->param->Get( id );
                    if( param )
                        param->SetValueString( value );
                }
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191

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


1192
void UIMainWindow::saveCurrentProject()
1193
{
Frédéric Larue's avatar
Frédéric Larue committed
1194 1195 1196 1197 1198 1199 1200
    UIProject *project = getCurrentProject();
	if( !project )
        return;

    QString defaultPath = project->GetSaveDir() + project->GetFileName();
    if( defaultPath == "" )
        defaultPath = project->Name() + "." + projectFileExtension();
1201
        
Frédéric Larue's avatar
Frédéric Larue committed
1202 1203 1204 1205 1206 1207 1208
    QString file = QFileDialog::getSaveFileName(
		this,
		tr("Save project"),
		defaultPath,
		tr("Project Files (*.") + projectFileExtension() + ")"
		);

1209
	if( !file.isNull() )
Frédéric Larue's avatar
Frédéric Larue committed
1210 1211 1212 1213
	{
		QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) );
		bool saveOk = project->Save( file );
		QApplication::restoreOverrideCursor();
1214

Frédéric Larue's avatar
Frédéric Larue committed
1215
		if( saveOk )
1216
		{
Frédéric Larue's avatar
Frédéric Larue committed
1217 1218
			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() );
1219 1220
            saveProjectOptions( project->GetSaveDir()+".project.opt", project );
        }
Frédéric Larue's avatar
Frédéric Larue committed
1221 1222 1223 1224 1225 1226 1227 1228 1229
		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;
1230
		}
1231 1232

        updateRecentListEntry( file );
1233 1234 1235 1236
	}
}


1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
void UIMainWindow::initializeCentralWidgetStack()
{
    QWidget *w = new QWidget();
    w->setLayout( new QVBoxLayout() );
    w->layout()->setContentsMargins( 0, 0, 0, 0 );
    w->layout()->setSpacing( 0 );
    setCentralWidget( w );
}


1247 1248 1249 1250 1251 1252 1253
void UIMainWindow::releaseCentralWidgetStack()
{
    while( !m_CentralWidgetStack.isEmpty() )
        popCentralWidget();
}


1254 1255 1256
void UIMainWindow::pushCentralWidget( QWidget* widget )
{
    if( !m_CentralWidgetStack.isEmpty() )
1257
        m_CentralWidgetStack.last().widget->hide();
1258

1259 1260 1261 1262 1263
    WidgetStackItem stackItem;
    stackItem.isSplit = false;
    stackItem.widget  = widget;

    m_CentralWidgetStack.append( stackItem );
1264 1265 1266 1267 1268 1269
    centralWidget()->layout()->addWidget( widget );

    widget->show();
}


1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 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
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();
}


1324 1325
void UIMainWindow::popCentralWidget()
{
1326 1327
    WidgetStackItem stackItem = m_CentralWidgetStack.takeLast();
    stackItem.widget->hide();
1328

1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
    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 );
        widgetToKeep->setParent( NULL );

        centralWidget()->layout()->addWidget( widgetToKeep );
        delete stackItem.widget;
1349

1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
        widgetToKeep->show();
    }
    else
    {
        centralWidget()->layout()->removeWidget( stackItem.widget );
        stackItem.widget->setParent( NULL );
        delete stackItem.widget;

        if( !m_CentralWidgetStack.isEmpty() )
            m_CentralWidgetStack.last().widget->show();
    }
1361 1362 1363
}


1364
void UIMainWindow::setViewerMode( DisplayDoF mode )
1365 1366 1367 1368 1369
{
    if( !m_CurrentViewer )
    {
        // Create the new viewer.

1370
        m_CurrentViewer = new GLViewer( mode );
1371
        m_CurrentViewer->setUpdateBehavior( QOpenGLWidget::NoPartialUpdate );
1372
        pushCentralWidget( m_CurrentViewer );
1373 1374 1375 1376 1377

        // Update UI consequently.

	    connect( ui->actionIncreasePointSize, SIGNAL(triggered()), m_CurrentViewer, SLOT(increasePointSize()) );
	    connect( ui->actionDecreasePointSize, SIGNAL(triggered()), m_CurrentViewer, SLOT(decreasePointSize()) );
1378
        connect( this, SIGNAL(aboutToDelete(GenericUIData*)), m_CurrentViewer, SLOT(removeDisplayable(GenericUIData*)) );
1379 1380 1381 1382 1383
    }
    else
    {
        // If the viewer is created but not set to the central widget, it means that the graph editor is currently running.
        // In that case, restore the OpenGL viewer.
1384 1385 1386 1387 1388
        //if( centralWidget() != m_CurrentViewer )
        //{
        //    setCentralWidget( m_CurrentViewer );
    	   // m_CurrentViewer->show();
        //}
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400

        if( m_CurrentViewer->dof() == mode )
            return;

        m_CurrentViewer->removeAllDisplayables();
        m_CurrentViewer->clearAllFactories();
        m_CurrentViewer->init( mode );
    }

    // Configure the viewer with the list of available display plug-ins.
    m_CurrentViewer->populateDisplayerFactories( m_DisplayablePlugins );

1401 1402
    ui->action2DViewer->setVisible( m_CurrentViewer->dof() == DISPLAY_DOF_2D );
    ui->action3DViewer->setVisible( m_CurrentViewer->dof() == DISPLAY_DOF_3D );
1403 1404 1405 1406 1407 1408

	updateCurrentProjectContent();
	update();
}


1409
void UIMainWindow::onItemDoubleClicked( GenericUIData *d )
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
{
    //if( d->IsOfType<ShaderGraph>() )
    //{
	   // m_CurrentViewer->hide();
    //    takeCentralWidget();

    //    ShaderGraphView *graphView = new ShaderGraphView( d->Content<ShaderGraph>() );

    //    setCentralWidget( graphView );
    //    graphView->show();
    //}
    //else
    //{
        for( auto factory : m_DisplayablePlugins )
        {
            QVector<QString> types;
            factory->acceptedDataTypes( types );

            if( types.contains(d->GetTypeString()) )
            {
                setViewerMode( factory->viewerDoF() );

                if( !m_CurrentViewer->isDisplayed(d) )
                {
                    m_CurrentViewer->addDisplayable( d );
                    m_CurrentViewer->frameAll();
                    updateCurrentProjectContent();
                }
            }
        }
    //}
}


1444
void UIMainWindow::closeEvent( QCloseEvent* evt )
1445
{
1446 1447 1448 1449
	if( closeAllProjects() )
	    evt->accept();
	else
		evt->ignore();
1450 1451 1452
}


1453
void UIMainWindow::updateDisplayables()
1454 1455 1456 1457 1458 1459 1460
{
    foreach( GenericUIData *m, ui->tableCurrentProjContent->selectedData() )
		if( m_CurrentViewer->isDisplayed(m) )
            m_CurrentViewer->updateDisplayable( m );
}


1461
void UIMainWindow::cloneSelectedManageables()
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
{
#if 0
	auto selected = ui->tableCurrentProjContent->selectedData();
	auto existing = m_CurrentProject->GetAll();

	for( QList<BaseManageable*>::iterator m=selected.begin(); m!=selected.end(); ++m )
    {
		BaseManageable *clone = (*m)->Clone( (*m)->GetFileName() );
        if( Manageable<Transform> *xf = Registration::GetTransform(*m) )
        {
            xf->Bind_RO();
            Registration::SetTransform( clone, *xf->Item() );
            xf->Unbind();
        }
    }

	updateCurrentProjectContent();
#endif
}


1483
void UIMainWindow::toWireframeMode()
1484 1485 1486 1487 1488 1489 1490 1491 1492
{
    m_CurrentViewer->setWireframeEnabled( true );
    update();

    ui->actionWireframeMode->setVisible( false );
    ui->actionSolidMode->setVisible( true );
}


1493
void UIMainWindow::toSolidMode()
1494 1495 1496 1497 1498 1499 1500 1501 1502
{
    m_CurrentViewer->setWireframeEnabled( false );
    update();

    ui->actionWireframeMode->setVisible( true );
    ui->actionSolidMode->setVisible( false );
}


1503
void UIMainWindow::toggleShading( bool enabled )
1504 1505 1506 1507 1508 1509
{
    m_CurrentViewer->setLightingEnabled( enabled );
    update();
}


1510 1511 1512
void UIMainWindow::launchExport( ExportInterface *exportPlugIn,
                                 int id,
                                 const QString &name )
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
{
    m_CurrentExportPlugIn = exportPlugIn;
    m_CurrentExportId = id;


    // Recovers the list of possible file filters.
    QStringList fileExtensions, fileFormatDesc;
    exportPlugIn->fileFilters( id, fileExtensions, fileFormatDesc );

    QStringList filters;
    for( QStringList::iterator ext=fileExtensions.begin(), desc=fileFormatDesc.begin(); ext!=fileExtensions.end(); ++ext, ++desc )
        filters << *desc + " (*." + *ext + ")";


    // Recovers the list of parameters available for the export, and shows a dialog window to the user if any.
    QFileDialog dlg( NULL, "Export "+name );
    dlg.setAcceptMode( QFileDialog::AcceptSave );
	dlg.setOption(QFileDialog::DontUseNativeDialog, true);

    m_CurrentExportParams = new UIParamSet( "Export options", this );
    exportPlugIn->parameters( id, *m_CurrentExportParams );

1535
    if( !m_CurrentExportParams->IsEmpty() )
1536 1537 1538
        if( QGridLayout *l = dynamic_cast<QGridLayout*>(dlg.layout()) )
            l->addWidget( m_CurrentExportParams, 1,4 );

1539
    foreach( UIParamAction* act, m_CurrentExportParams->GetActions() )
1540
        connect( act->Widget(), SIGNAL(clicked(bool)), this, SLOT(execExportAction()) );
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563


    // Sorts all selected data wrt. their types.
    QVector<QString> acceptedTypes;
    exportPlugIn->acceptedDataTypes( id, acceptedTypes );

    QList<GenericUIData*> selectedItems;
    QVector< QList<GenericUIData*> > selectedItemsByType;
    selectedItemsByType.resize( acceptedTypes.size() );

    foreach( GenericUIData *m, selection() )
    {
        for( int i=0; i<acceptedTypes.size(); ++i )
            if( m->GetTypeString() == acceptedTypes[i] )
            {
                selectedItems.push_back( m );
                selectedItemsByType[i].push_back( m );
                break;
            }
    }


    // Performs the export of the selected items.
1564
    UIContext ctx;
1565 1566
    ctx.mainwin        = this;
    ctx.glviewer       = m_CurrentViewer;
1567
    ctx.project        = getCurrentProject();
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584

    switch( exportPlugIn->fileExportMode(id) )
    {
        case ExportInterface::INDEPENDENT_FILES:
        {
            if( selectedItems.size() == 1 )
            {
                dlg.setFileMode( QFileDialog::AnyFile );
                dlg.setNameFilters( filters );
                dlg.selectFile( selectedItems.front()->GetBaseName() + '.' + fileExtensions.front() );
                if( !dlg.exec() )
                    return;

                QStringList fileNames = dlg.selectedFiles();
                if( fileNames.empty() )
                    return;

1585 1586 1587
                QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) );
                QCoreApplication::processEvents();

1588
                exportPlugIn->saveSingleFile( id, fileNames.front(), selectedItems.front(), *m_CurrentExportParams, ctx );
1589 1590

                QApplication::restoreOverrideCursor();
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
            }
            else
            {
                dlg.setFileMode( QFileDialog::Directory );
                dlg.setFilter( QDir::AllDirs );
                dlg.setNameFilters( filters );
                if( !dlg.exec() )
                    return;

                QStringList fileNames = dlg.selectedFiles();
                if( fileNames.empty() )
                    return;

1604 1605 1606
                QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) );
                QCoreApplication::processEvents();

1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
                QString path = fileNames.front() + '/';
                QString suffix;
                for( QStringList::iterator flt=filters.begin(), ext=fileExtensions.begin(); flt!=filters.end(); ++flt, ++ext )
					if( *flt == dlg.selectedNameFilter() )
                    {
                        suffix = '.' + *ext;
                        break;
                    }

                foreach( GenericUIData *m, selectedItems )
                {
                    QString filename = path + m->GetBaseName() + suffix;
                    exportPlugIn->saveSingleFile( id, filename, m, *m_CurrentExportParams, ctx );
                }
1621 1622

                QApplication::restoreOverrideCursor();
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
            }

            break;
        }
        case ExportInterface::MULTIPLE_FILES_TO_ONE_DIR:
        {
            dlg.setFileMode( QFileDialog::Directory );
            dlg.setFilter( QDir::AllDirs );
            dlg.setNameFilters( filters );
            if( !dlg.exec() )
                return;

            QStringList fileNames = dlg.selectedFiles();
            if( fileNames.empty() )
                return;

1639 1640 1641
            QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) );
            QCoreApplication::processEvents();

1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
            QString suffix;
            for( QStringList::iterator flt=filters.begin(), ext=fileExtensions.begin(); flt!=filters.end(); ++flt, ++ext )
                if( *flt == dlg.selectedNameFilter() )
                {
                    suffix = *ext;
                    break;
                }

            QString path = fileNames.front() + '/';
            exportPlugIn->saveMultiFiles( id, path, suffix, selectedItemsByType, *m_CurrentExportParams, ctx );

1653 1654
            QApplication::restoreOverrideCursor();