void TimeEntryDialog::setElementList( ElementList list )
{
	if( list.isEmpty() ) return;
	// Go through the element list and make sure that
	// each element is in the same project and has
	// the same asset type
	ElementList valid;
	ElementList invalid;
	AssetType type;
	Project p;
	foreach( Element e, list ) {
		if( p.isRecord() && e.project() != p ) continue;
		QVariant v = e.getValue( "allowTime" );
		if( v.toBool() || (v.isNull() && (e.children().size()==0) ) ) {
			if( !type.isRecord() ) {
				type = e.assetType();
				p = e.project();
			} else if( e.assetType() != type )
				continue;
			if( !valid.contains( e ) ) valid += e;
		} else
			invalid += e;
	}

	mAssetTree->setSelection( RecordList() );

	if( valid.isEmpty() ) {
		if( !invalid.isEmpty() ) {
			setProject( invalid[0].project() );
			QStringList sl;
			foreach( Element e, invalid )
				sl += e.displayName(true);
			mAssetFilterEdit->setText( sl.join(",") );
		}
	} else {
		Element first = valid[0];
		QStringList sl;
		foreach( Element e, valid )
			sl += e.displayName(true);
		mAssetFilterEdit->setText( sl.join(",") );
		if( first.isRecord() ) {
			setProject( first.project() );
			setAssetType( type );
			mAssetTree->setSelection( valid );
			mAssetTree->scrollTo( first );
		}
	}
}
Exemple #2
0
void MainWindow::activeWindowStatusChanged()
{
    DocumentWindow::activeWindowStatusChanged();

    if (ProjectContentComponent* const pcc = getProjectContentComponent())
        pcc->updateMissingFileStatuses();

    ProjucerApplication::getApp().openDocumentManager.reloadModifiedFiles();

    if (Project* p = getProject())
    {
        if (p->hasProjectBeenModified())
        {
            const int r = AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
                                                           TRANS ("The .jucer file has been modified since the last save."),
                                                           TRANS ("Do you want to keep the current project or re-load from disk?"),
                                                           TRANS ("Keep"),
                                                           TRANS ("Re-load from disk"));

            if (r == 0)
            {
                File projectFile = p->getFile();
                setProject (nullptr);
                openFile (projectFile);
            }
            else if (r == 1)
            {
                ProjucerApplication::getApp().getCommandManager().invokeDirectly (CommandIDs::saveProject, true);
            }
        }
    }
}
Exemple #3
0
void AccountsView::init()
{
    QVBoxLayout *l = new QVBoxLayout( this );
    m_view = new AccountsTreeView( this );
    l->addWidget( m_view );
    setProject( m_project );
}
Exemple #4
0
bool MainWindow::closeProject (Project* project)
{
    jassert (project == currentProject && project != nullptr);

    if (project == nullptr)
        return true;

    project->getStoredProperties().setValue (getProjectWindowPosName(), getWindowStateAsString());

    if (ProjectContentComponent* const pcc = getProjectContentComponent())
    {
        pcc->saveTreeViewState();
        pcc->saveOpenDocumentList();
        pcc->hideEditor();
    }

    if (! ProjucerApplication::getApp().openDocumentManager.closeAllDocumentsUsingProject (*project, true))
        return false;

    FileBasedDocument::SaveResult r = project->saveIfNeededAndUserAgrees();

    if (r == FileBasedDocument::savedOk)
    {
        setProject (nullptr);
        return true;
    }

    return false;
}
/**
 * @brief Diagram::Diagram
 * Constructor
 * @param project : The project of this diagram and also parent QObject
 */
Diagram::Diagram(QETProject *project) :
	QGraphicsScene           (project),
	project_                 (NULL),
	diagram_qet_version_     (-1),
	draw_grid_               (true),
	use_border_              (true),
	draw_terminals_          (true),
	draw_colored_conductors_ (true)
{
	setProject(project);
	qgi_manager_ = new QGIManager(this);
	setBackgroundBrush(Qt::white);
	conductor_setter_ = new QGraphicsLineItem(0, 0);
	conductor_setter_ -> setZValue(1000000);
	QPen t;
	t.setColor(Qt::black);
	t.setWidthF(1.5);
	t.setStyle(Qt::DashLine);
	conductor_setter_ -> setPen(t);
	conductor_setter_ -> setLine(QLineF(QPointF(0.0, 0.0), QPointF(0.0, 0.0)));
	
		//Init object for manage movement
	elements_mover_      = new ElementsMover();
	element_texts_mover_ = new ElementTextsMover();

	connect(&border_and_titleblock, SIGNAL(needTitleBlockTemplate(const QString &)), this, SLOT(setTitleBlockTemplate(const QString &)));
	connect(&border_and_titleblock, SIGNAL(diagramTitleChanged(const QString &)),    this, SLOT(titleChanged(const QString &)));
}
Exemple #6
0
bool MainWindow::openFile (const File& file)
{
    createProjectContentCompIfNeeded();

    if (file.hasFileExtension (Project::projectFileExtension))
    {
        ScopedPointer<Project> newDoc (new Project (file));

        Result result (newDoc->loadFrom (file, true));

        if (result.wasOk() && closeCurrentProject())
        {
            setProject (newDoc);
            newDoc.release()->setChangedFlag (false);

            jassert (getProjectContentComponent() != nullptr);
            getProjectContentComponent()->reloadLastOpenDocuments();

            if (Project* p = getProject())
                p->updateDeprecatedProjectSettingsInteractively();

            return true;
        }
    }
    else if (file.exists())
    {
        return getProjectContentComponent()->showEditorForFile (file, true);
    }

    return false;
}
Exemple #7
0
void MSBuildQbsProductProject::addFiles(const GeneratableProject &project,
                                        const GeneratableProductData &product)
{
    auto itemGroup = new MSBuildItemGroup(this);

    std::map<QString, MSBuildFileItem *> sourceFileNodes;
    std::map<QString, QStringList> sourceFileEnabledConfigurations;

    // Create a ClCompile item for each source file, keeping track of which configurations that
    // file's containing group is enabled in
    QMapIterator<QString, qbs::ProductData> productDataIt(product.data);
    while (productDataIt.hasNext()) {
        productDataIt.next();
        for (const auto &group : productDataIt.value().groups()) {
            for (const auto &sourceArtifact : group.allSourceArtifacts()) {
                const auto filePath = sourceArtifact.filePath();
                if (sourceFileNodes.find(filePath) == sourceFileNodes.end()) {
                    sourceFileNodes.insert({
                        filePath,
                        fileItemForFileTags(sourceArtifact.fileTags(), itemGroup)
                    });
                }
                auto fileItem = sourceFileNodes[filePath];
                QString path = project.baseBuildDirectory().relativeFilePath(filePath);
                // The path still might not be relative (for example if the file item is
                // located on a different drive)
                if (QFileInfo(path).isRelative())
                    path = QStringLiteral("$(ProjectDir)") + path;
                fileItem->setFilePath(path);
                if (group.isEnabled())
                    sourceFileEnabledConfigurations[filePath] << productDataIt.key();
            }
        }
    }

    // Add ExcludedFromBuild item metadata to each file for each configuration
    // where that file's containing group is disabled
    for (const auto &sourceFileNode : sourceFileNodes) {
        QMapIterator<QString, qbs::Project> projIt(project.projects);
        while (projIt.hasNext()) {
            projIt.next();
            if (!sourceFileEnabledConfigurations[sourceFileNode.first].contains(projIt.key())) {
                auto metadata = new MSBuildItemMetadata(
                            QStringLiteral("ExcludedFromBuild"),
                            QStringLiteral("true"),
                            sourceFileNode.second);
                metadata->setCondition(QStringLiteral("'$(Configuration)|$(Platform)'=='")
                    + MSBuildUtils::fullName(projIt.value())
                    + QStringLiteral("'"));
            }
        }
    }

    auto import = new MSBuildImport(this);
    import->setProject(QStringLiteral("$(VCTargetsPath)\\Microsoft.Cpp.targets"));
}
void MainApplication::loadProject(const BoostPath& ProjectFile)
{
    ProjectRefPtr LoadedProject = Project::load(ProjectFile);

    if(LoadedProject != NULL)
    {
        setProject(LoadedProject);
        updateRecentProject(ProjectFile);
    }
}
/**
	Constructeur
	@param project projet a visualiser
	@param parent Widget parent
*/
ProjectView::ProjectView(QETProject *project, QWidget *parent) :
	QWidget(parent),
	project_(0)
{
	initActions();
	initWidgets();
	initLayout();
	
	setProject(project);
}
ProjectContentComponent::~ProjectContentComponent()
{
    IntrojucerApp::getApp().openDocumentManager.removeListener (this);

    logo = nullptr;
    setProject (nullptr);
    contentView = nullptr;
    removeChildComponent (&bubbleMessage);
    jassert (getNumChildComponents() <= 1);
}
void TimeEntryDialog::setTimeSheet( const TimeSheet & ts )
{
	mTimeSheet = ts;
	mUser = mTimeSheet.user();
	setDateRange( ts.dateTime().date() );
	setProject( ts.project() );
	setAssetType( ts.assetType() );
	mHoursSpin->setValue( ts.scheduledHour() );
	mCommentEdit->setPlainText( ts.comment() );
	setElementList( ts.element() );
}
void TimeEntryDialog::setAssetType( const AssetType & at )
{
	if( at.isRecord() && at != mAssetType ) {
		mTypeCombo->setCurrent( at );
		mAssetType = at;
		mForceVirtualProject = mForcedProjectCategories.contains( at.name() );
		mProjectCombo->setEnabled( !mForceVirtualProject );
		if( mForceVirtualProject )
			setProject( mVirtualProject );
		updateAssets();
	}
}
void MainWindow::activeWindowStatusChanged()
{
    DocumentWindow::activeWindowStatusChanged();

    if (auto* pcc = getProjectContentComponent())
        pcc->updateMissingFileStatuses();

    ProjucerApplication::getApp().openDocumentManager.reloadModifiedFiles();

    if (auto* p = getProject())
    {
        if (p->hasProjectBeenModified())
        {
            Component::SafePointer<Component> safePointer (this);

            MessageManager::callAsync ([=] ()
            {
                if (safePointer == nullptr)
                    return; // bail out if the window has been deleted

                auto result = AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
                                                            TRANS ("The .jucer file has been modified since the last save."),
                                                            TRANS ("Do you want to keep the current project or re-load from disk?"),
                                                            TRANS ("Keep"),
                                                            TRANS ("Re-load from disk"));

                if (safePointer == nullptr)
                    return;

                if (result == 0)
                {
                    if (auto* project = getProject())
                    {
                        auto oldTemporaryDirectory = project->getTemporaryDirectory();

                        auto projectFile = project->getFile();
                        setProject (nullptr);
                        openFile (projectFile);

                        if (oldTemporaryDirectory != File())
                            if (auto* newProject = getProject())
                                newProject->setTemporaryDirectory (oldTemporaryDirectory);
                    }
                }
                else
                {
                    ProjucerApplication::getApp().getCommandManager().invokeDirectly (CommandIDs::saveProject, true);
                }
            });
        }
    }
}
ProjectContentComponent::~ProjectContentComponent()
{
    Desktop::getInstance().removeFocusChangeListener (this);
    killChildProcess();

    ProjucerApplication::getApp().openDocumentManager.removeListener (this);

    logo = nullptr;
    header = nullptr;
    setProject (nullptr);
    contentView = nullptr;
    fileNameLabel = nullptr;
    removeChildComponent (&bubbleMessage);
    jassert (getNumChildComponents() <= 1);
}
void ScheduleDialog::setElement( const Element & e, const AssetType & at )
{
	if( e.isRecord() ) {
		mDisableUpdates = true;
		setProject( e.project() );
		if( at.isRecord() )
			setAssetType( at );
		if( at != e.assetType() && mTypeFilterAssetsCheck->isChecked() )
			setUseAssetsTypeFilter( false );
		mAssetFilterEdit->setText( e.displayName(true) );
		mDisableUpdates = false;
		updateAssets();
		mAssetTree->setSelection( e );
	}
}
Exemple #16
0
GeneralDataGUI::GeneralDataGUI(Project *p, QWidget *parent) :
    QWidget(parent),
    m_d( new GeneralDataGUIPrivate() ){
    m_d->ui->setupUi(this);

    setProject(p);

    m_d->ui->unitMeasureView->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);

    connect( m_d->ui->unitMeasureAddPButton, &QPushButton::clicked, this, &GeneralDataGUI::insertUnitMeasure );
    connect( m_d->ui->unitMeasureDelPButton, &QPushButton::clicked, this, &GeneralDataGUI::removeUnitMeasure );

    connect( m_d->ui->addPriceFieldPushButton, &QPushButton::clicked, this, &GeneralDataGUI::insertPriceField );
    connect( m_d->ui->delPriceFieldPushButton, &QPushButton::clicked, this, &GeneralDataGUI::removePriceField );

    m_d->ui->priceFieldTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    m_d->ui->priceFieldTableView->setItemDelegate( m_d->fieldTableDelegate );
}
void TimeEntryDialog::setupSuggestedTimeSheet()
{
	VarList v;
	v += QDate::currentDate();
	v += User::currentUser().key();
	ScheduleList sl = Schedule::select( "date = ? and fkeyuser = ?", v );
	if( !sl.isEmpty() ) {
		Schedule s = sl[0];
		setElementList( s.element() );
	} else {
		TimeSheetList recent = TimeSheet::select( "fkeyemployee=? order by dateTime desc limit 1", VarList() += User::currentUser().key() );
		if( !recent.isEmpty() ) {
			TimeSheet ts = recent[0];
			setProject( ts.project() );
			setAssetType( ts.assetType() );
			setElementList( ts.element() );
		}
	}
}
bool MainWindow::openFile (const File& file)
{
    if (file.hasFileExtension (Project::projectFileExtension))
    {
        ScopedPointer <Project> newDoc (new Project (file));

        if (newDoc->loadFrom (file, true)
             && closeCurrentProject())
        {
            setProject (newDoc.release());
            return true;
        }
    }
    else if (file.exists())
    {
        return getProjectContentComponent()->showEditorForFile (file);
    }

    return false;
}
bool MainWindow::closeProject (Project* project)
{
    jassert (project == currentProject && project != nullptr);

    if (project == nullptr)
        return true;

    StoredSettings::getInstance()->getProps()
        .setValue (getProjectWindowPosName(), getWindowStateAsString());

    if (! OpenDocumentManager::getInstance()->closeAllDocumentsUsingProject (*project, true))
        return false;

    FileBasedDocument::SaveResult r = project->saveIfNeededAndUserAgrees();

    if (r == FileBasedDocument::savedOk)
    {
        setProject (nullptr);
        return true;
    }

    return false;
}
Int32 MainApplication::run(int argc, char **argv)
{
    //Get the date/time run
    _DateTimeRun = boost::posix_time::second_clock::local_time();

    //Get the path to the command
    BoostPath CommandPath(argv[0]);
    if(!CommandPath.is_complete() && !CommandPath.has_root_directory())
    {
        CommandPath = boost::filesystem::complete(CommandPath);
    }
    CommandPath.normalize();

    //Parse the Program arguments
    boost::program_options::variables_map OptionsVariableMap;
    try
    {
        boost::program_options::store(boost::program_options::command_line_parser(argc, argv).
                                      options(_OptionsDescription).
#ifdef __APPLE__
                                      extra_parser(procSerialNumParser).
#endif
                                      positional(_PositionalOptions).run(), OptionsVariableMap);

        boost::program_options::notify(OptionsVariableMap);
    }
    catch(boost::program_options::error& e)
    {
        std::cout << "Error parsing command line: " << e.what() << std::endl;
        printCommandLineHelp();
    }

    //Check for the help argument
    if(OptionsVariableMap.count("help"))
    {
        printCommandLineHelp();
        return 1;
    }
    
    //Setup the Logging
    LogLevel KELogLevel(LOG_NOTICE);
    if(OptionsVariableMap.count("log-level"))
    {
        KELogLevel = OptionsVariableMap["log-level"].as<LogLevel>();
    }

    _LogFilePath = getLoggingDir()
                 / BoostPath(boost::posix_time::to_iso_string(_DateTimeRun) + ".log");  //ISO date/time format
    if(OptionsVariableMap.count("log-file"))
    {
        _LogFilePath = BoostPath(OptionsVariableMap["log-file"].as<std::string>());
    }
    if(OptionsVariableMap.count("disable-log"))
    {
        _EnableLogging = false;
    }
    if(OptionsVariableMap.count("disable-file-log"))
    {
        _LogToFile = false;
    }

    initializeLogging(_LogFilePath);
    osgLogP->setLogLevel(KELogLevel, true);
    osgLogP->setHeaderElem((LOG_TYPE_HEADER | LOG_FUNCNAME_HEADER), true);

    //Check if the last run crashed
    if(didCrashLastExecution())
    {
        handleCrashLastExecution();
    }

    //Create a file to indicate if a crash occurs
    createCrashIndicationFile();

    // Set up Settings
    //Check for the settings file
    if(OptionsVariableMap.count("settings-file"))
    {
        setSettingsLoadFile(BoostPath(OptionsVariableMap["settings-file"].as<std::string>()));
    }
    else
    {
        //Use default location
        setSettingsLoadFile(getUserAppDataDir()
                          / BoostPath("KEDefaultSettings.xml"));
    }
    loadSettings(getSettingsLoadFile());

    //Cleanup the Logging Directory
    cleanupLoggingDir();

    //If the settings aren't being overriden by the command-line options
    //then set the logging with the settings values
    if(!OptionsVariableMap.count("log-level"))
    {
        osgLogP->setLogLevel(static_cast<LogLevel>(getSettings().get<UInt8>("logging.level")), true);
    }
    osgLogP->setHeaderElem(getSettings().get<UInt32>("logging.header_elements"), true);

    //Initialize OpenSG
    initOpenSG(argc,argv);

    //Log information about the Engine
    {
        PLOG << "Starting Kabala Engine:" << std::endl;
        OSG::indentLog(4,PLOG);
        PLOG << "Arguments: ";
        for(UInt32 i(0) ; i<argc ; ++i)
        {
            PLOG << argv[i] << " ";
        }
        PLOG << std::endl;

        OSG::indentLog(4,PLOG);
        PLOG << "System:" << std::endl;
        OSG::indentLog(8,PLOG);
        PLOG << "Operating System: " << getPlatformName() << std::endl;
        OSG::indentLog(8,PLOG);
        PLOG << "Processor: " << getPlatformProcessors() << std::endl;
        OSG::indentLog(8,PLOG);
        PLOG << "RAM: " << getPlatformRAM() << std::endl;
        OSG::indentLog(4,PLOG);
        PLOG << "Time: " << to_simple_string(_DateTimeRun) << std::endl;
        OSG::indentLog(4,PLOG);
        PLOG << "Version: " << getKabalaEngineVersion() << std::endl;
        OSG::indentLog(8,PLOG);
        PLOG << "Revision: " << getKabalaEngineBuildRepositoryRevision() << std::endl;
        OSG::indentLog(8,PLOG);
        PLOG << "Build Type: " << getKabalaEngineBuildType() << std::endl;
        OSG::indentLog(4,PLOG);
        PLOG << "Working Directory: " << boost::filesystem::current_path().string() << std::endl;
        OSG::indentLog(4,PLOG);
        PLOG << "Executable Directory: " << CommandPath.parent_path().string() << std::endl;
        OSG::indentLog(4,PLOG);
        PLOG << "Settings File: " << getSettingsLoadFile().string() << std::endl;

        OSG::indentLog(4,PLOG);
        PLOG << "Logging: " << (_EnableLogging ? "Enabled" : "Disabled" ) << std::endl;
        if(_EnableLogging)
        {
            OSG::indentLog(8,PLOG);
            PLOG << "Log File: " << (_LogToFile ? _LogFilePath.string() : "Disabled" ) << std::endl;
        }
    }

    //Check if the Data Directory exists
    if(!boost::filesystem::exists(getSettings().get<BoostPath>("basic.data.directory")))
    {
        BoostPath DataDirPath(getSettings().get<BoostPath>("basic.data.directory"));
        DataDirPath = boost::filesystem::complete(DataDirPath);
        DataDirPath.normalize();
        SWARNING << "Could not find Application Data directory: \""
                 << DataDirPath.string()
                 << "\" specified in the Settings file because the directory doesn't exist." << std::endl;

        //Try to find the data directory in a few locations
        std::vector<BoostPath> PathsToTry;

#ifdef __APPLE__
        PathsToTry.push_back(CommandPath.parent_path() /
                             BoostPath("../Resources") /
                             EngineAppDataDirectory);       //Path to try for OS X Bundles
        PathsToTry.push_back(CommandPath.parent_path() /
                             BoostPath("../Resources/share") /
                             EngineAppDataDirectory);       //Path to try for OS X Bundles
#endif

        PathsToTry.push_back(BoostPath("/usr/local/share") / EngineAppDataDirectory);
        PathsToTry.push_back(BoostPath("/usr/share") / EngineAppDataDirectory);
        PathsToTry.push_back(CommandPath.parent_path() / EngineAppDataDirectory);
        PathsToTry.push_back(CommandPath.parent_path() / BoostPath("..") / EngineAppDataDirectory);
        PathsToTry.push_back(CommandPath.parent_path() / BoostPath("../share") / EngineAppDataDirectory);

        for(UInt32 i(0) ; i<PathsToTry.size() ; ++i)
        {
            SNOTICE << "Looking for Data directory in: "
                << PathsToTry[i].string() << std::endl;
            if(boost::filesystem::exists(PathsToTry[i]))
            {
                PNOTICE << "FOUND" << std::endl;
                PathsToTry[i].normalize();
                getSettings().put("basic.data.directory",PathsToTry[i]);
                break;
            }
            else
            {
                PNOTICE << "NOT FOUND" << std::endl;
            }
        }
    }

    if(!boost::filesystem::exists(getSettings().get<BoostPath>("basic.data.directory")))
    {
        SWARNING << "Could not find Application Data directory: \""
                 << getSettings().get<BoostPath>("basic.data.directory").string()
                 << "\" because the directory doesn't exist." << std::endl;
    }
    else
    {
        SLOG << "Using Application Data directory: \""
                 << getSettings().get<BoostPath>("basic.data.directory").string()
                 << "\"" << std::endl;
    }

    // Set up Window
    WindowEventProducerUnrecPtr MainWindow(createNativeWindow());
    setMainWindow(MainWindow);
    setName(getMainWindow(),"__KABALA_ENGINE_WINDOW_EVENT_PRODUCER");

    //If Fullscreen option -> Fullscreen
    if(OptionsVariableMap.count("fullscreen"))
    {
        getMainWindow()->setFullscreen(true);
    }
    //If no-fullscreen     -> not Fullscreen
    else if(OptionsVariableMap.count("no-fullscreen"))
    {
        getMainWindow()->setFullscreen(false);
    }
    //else                 -> use the value in the settings
    else
    {
        getMainWindow()->setFullscreen(getSettings().get<bool>("basic.window.fullscreen"));
    }

    getMainWindow()->initWindow();

    _WindowClosingConnection = getMainWindow()->connectWindowClosing(boost::bind(&MainApplication::handleWindowClosing, this, _1));
    _WindowClosedConnection = getMainWindow()->connectWindowClosed(boost::bind(&MainApplication::handleWindowClosed, this, _1));

    // Initialize the LookAndFeelManager to enable default settings
    KELookAndFeel::the()->init();


    //Open Window
    Vec2f WindowSize(getSettings().get<Vec2f>("basic.window.size"));
    if(getSettings().get<Vec2f>("basic.window.size").x() <= 1.0f )
    {
        WindowSize[0] = getMainWindow()->getDesktopSize().x() * getSettings().get<Vec2f>("basic.window.size").x();
    }
    if(getSettings().get<Vec2f>("basic.window.size").y() <= 1.0f )
    {
        WindowSize[1] = getMainWindow()->getDesktopSize().y() * getSettings().get<Vec2f>("basic.window.size").y();
    }
    Pnt2f WindowPos(getSettings().get<Pnt2f>("basic.window.position"));
    if(getSettings().get<Pnt2f>("basic.window.position").x() < 0.0f )
    {
        WindowPos[0] = (getMainWindow()->getDesktopSize().x() - WindowSize.x()) * 0.5f;
    }
    if(getSettings().get<Pnt2f>("basic.window.position").y() < 0.0f )
    {
        WindowPos[1] = (getMainWindow()->getDesktopSize().y() - WindowSize.y()) * 0.5f;
    }

    getMainWindow()->openWindow(WindowPos,
                                WindowSize,
                                "Kabala Engine");

        
    //Store a pointer to the application thread
    //_ApplicationThread = dynamic_cast<OSG::Thread *>(OSG::ThreadManager::getAppThread());
    
    //Create the rendering thread
    //_RenderThread = OSG::dynamic_pointer_cast<OSG::Thread>(OSG::ThreadManager::the()->getThread("__KABALA_ENGINE_RENDER_THREAD", true));
    
    //Create the loading thread
    //_LoadingThread = OSG::dynamic_pointer_cast<OSG::Thread>(OSG::ThreadManager::the()->getThread("__KABALA_ENGINE_LOADING_THREAD", true));

    //Draw the loading thread
    activateLoadingScreen();

    //Load the Project file, if given
    if(OptionsVariableMap.count("project-file"))
    {
        loadProject(BoostPath(OptionsVariableMap["project-file"].as<std::string>()));
    }
    else if(getSettings().get<bool>("basic.load_most_recent_project"))
    {
        boost::optional<BoostPath> LastOpenedProjectFile = getSettings().get_optional<BoostPath>("basic.last_opened_project");
        if(LastOpenedProjectFile)
        {
            loadProject(LastOpenedProjectFile.get());
            commitChanges();
        }
    }

    if(getProject() == NULL)
    {
        //Project Failed to load, or file didn't exist
        ProjectRecPtr NewProject = createDefaultProject();
        setProject(NewProject);
    }

    //Detach the loading screen
    detachLoadingScreen();

#ifdef BUILD_WITH_WORLD_BUILDER
    if(OptionsVariableMap.count("builder"))
    {
        attachBuilder();
    }
    else 
#endif
        if(OptionsVariableMap.count("play"))
    {
        attachPlayer();
        if(OptionsVariableMap.count("debug"))
        {
            dynamic_cast<ApplicationPlayer*>(getPlayerMode())->enableDebug(true);
        }
    }
    else
    {
#ifdef BUILD_WITH_WORLD_BUILDER
        if(getSettings().get<std::string>("basic.initial_mode").compare(std::string("builder")) == 0)
        {
            attachBuilder();
        }
        else
#endif
            if(getSettings().get<std::string>("basic.initial_mode").compare(std::string("play")) == 0)
        {
            attachPlayer();
            if(OptionsVariableMap.count("debug") || getSettings().get<bool>("player.debugger.initially_active"))
            {
                dynamic_cast<ApplicationPlayer*>(getPlayerMode())->enableDebug(true);
            }
        }
        else
        {
            attachStartScreen();
        }
    }
    
    //Start the render thread on aspect 1
    //_RenderThread->runFunction(MainApplication::mainRenderLoop, 1, NULL);
    
    //Start the loading thread on aspect 2
    //_LoadingThread->runFunction(MainApplication::mainLoadingLoop, 2, NULL);

    //Main Loop
    getMainWindow()->mainLoop();

    //Exited Main Loop
    //Save Settings
    saveSettings(getSettingsLoadFile());
    
    SLOG << "Stopping Kabala Engine" << std::endl;
    OSG::indentLog(4,PLOG);
    PLOG << "Time: " << to_simple_string(boost::posix_time::second_clock::local_time()) << std::endl;

    //OSG exit
    OSG::osgExit();

    //Uninitialize logging
    uninitializeLogging();

    //Create a file to indicate if a crash occurs
    removeCrashIndicationFile();

    return 0;
}
MainWindow::MainWindow(QWidget *parent)
	: QMainWindow(parent)
	, ui(new Ui::MainWindow)
	, userSettings(QSettings::UserScope, "Jason Gedge", "StereoReconstruction")
	, trayIcon(nullptr)
    , recentFiles(userSettings.value("recentFileList").toStringList())
{
    ui->setupUi(this);

	//
	// Recent Files
	//
	QSignalMapper *recentFilesMapper = new QSignalMapper(this);
	connect(recentFilesMapper, SIGNAL(mapped(int)), SLOT(openRecentFile(int)));

	for(int index = 0; index < NUM_RECENT_FILES; ++index) {
		recentFileActions[index] = ui->menuOpen_Recent->addAction(
				QString("%1: <No File>").arg(index + 1),
				recentFilesMapper,
				SLOT(map()) );

		recentFileActions[index]->setVisible(false);
		recentFilesMapper->setMapping(recentFileActions[index], index);
	}
	{
		// Move separator + "clear recent files" to end
		QAction *act = ui->menuOpen_Recent->actions().first();
		ui->menuOpen_Recent->removeAction(act);
		ui->menuOpen_Recent->addAction(act);

		act = ui->menuOpen_Recent->actions().first();
		ui->menuOpen_Recent->removeAction(act);
		ui->menuOpen_Recent->addAction(act);
	}

	//
	//
	//
	trayIcon = new QSystemTrayIcon(this);

#ifndef HAS_IMAGE_CAPTURE
	ui->menuBar->removeAction(ui->menuCapture->menuAction());
#endif
#ifndef HAS_HDR
	ui->menuBar->removeAction(ui->menuHDR->menuAction());
#endif

	//
	//
	//
	projectExplorerDock = new QDockWidget(tr("Project Explorer"), this);
	projectExplorerDock->setObjectName(QString::fromUtf8("projectExplorerDock"));
	projectExplorerDock->setMinimumWidth(200);
	projectExplorerDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
	addDockWidget(Qt::LeftDockWidgetArea, projectExplorerDock);
	projectExplorerDock->hide();

	projectExplorer = new ProjectExplorer(this);
	projectExplorerDock->setWidget(projectExplorer);
	connect(projectExplorer, SIGNAL(customContextMenuRequested(QPoint)), SLOT(showProjectMenu(QPoint)));

	//
	//
	//
	imageSetTable = new ImageSetTable(this);
	imageSetTable->setEnabled(false);

	cameraInfoWidget = new CameraInfoWidget(this);
	cameraInfoWidget->setEnabled(false);

	inspectorDock = new QDockWidget(tr("Inspector"), this);
	inspectorDock->setObjectName(QString::fromUtf8("inspectorDock"));
	inspectorDock->setMinimumWidth(350);
	inspectorDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
	addDockWidget(Qt::RightDockWidgetArea, inspectorDock);
	inspectorDock->hide();

	inspector = new QStackedWidget(inspectorDock);
	inspector->addWidget(new QWidget(this));
	inspector->addWidget(cameraInfoWidget);
	inspector->addWidget(imageSetTable);
	inspectorDock->setWidget(inspector);

	//
	//
	//
	taskList = new QWidget(this);
	taskList->setAutoFillBackground(true);
	taskList->setBackgroundRole(QPalette::Light);
	taskList->setObjectName(QString::fromUtf8("taskList"));
	taskList->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
	taskList->setMinimumHeight(50); // XXX necessary?

	taskListLayout = new QVBoxLayout(taskList);
	taskListLayout->setMargin(0);
	taskListLayout->addStretch(1);

	taskListDock = new QDockWidget(tr("Task List"), this);
	taskListDock->setObjectName(QString::fromUtf8("taskListDock"));
	taskListDock->setWidget(taskList);
	taskListDock->setAllowedAreas(Qt::AllDockWidgetAreas);
	addDockWidget(Qt::BottomDockWidgetArea, taskListDock);
	taskListDock->hide();

	//
	// TODO move these to the ui files
	//
	connect(projectExplorer,
			SIGNAL(cameraSelected(CameraPtr)),
			SLOT(cameraSelected(CameraPtr)) );

	connect(projectExplorer,
			SIGNAL(imageSetSelected(ImageSetPtr)),
			SLOT(imageSetSelected(ImageSetPtr)) );

	connect(projectExplorerDock,
			SIGNAL(visibilityChanged(bool)),
			SLOT(on_actionShowHide_Project_Explorer_triggered(bool)) );

	connect(inspectorDock,
			SIGNAL(visibilityChanged(bool)),
			SLOT(on_actionShowHide_Inspector_triggered(bool)) );

	projectExplorer->connect(this,
			SIGNAL(projectLoaded(ProjectPtr)),
			SLOT(setProject(ProjectPtr)) );

	cameraInfoWidget->connect(this,
							  SIGNAL(projectLoaded(ProjectPtr)),
							  SLOT(setProject(ProjectPtr)) );

	cameraInfoWidget->connect(projectExplorer,
							  SIGNAL(cameraSelected(CameraPtr)),
							  SLOT(setCamera(CameraPtr)) );

	imageSetTable->connect(this,
						   SIGNAL(projectLoaded(ProjectPtr)),
						   SLOT(setProject(ProjectPtr)) );

	imageSetTable->connect(projectExplorer,
						   SIGNAL(imageSetSelected(ImageSetPtr)),
						   SLOT(setImageSet(ImageSetPtr)) );

	ui->stereoWidget->connect(this,
							  SIGNAL(projectLoaded(ProjectPtr)),
							  SLOT(setProject(ProjectPtr)) );

	//
	// Set up initial window state
	//
	restoreGeometry(userSettings.value("mainWindowGeometry").toByteArray());
	restoreState(userSettings.value("mainWindowState").toByteArray());
	updateRecentFiles();
	ui->actionView_Nothing->trigger();
	ui->actionNew->trigger();
}
void CommandList::setSession(Session *session)
{
	BaseWidget::setSession(session);
	setProject(session->getProjectName());
	connect(session, SIGNAL(projectChanged(QString)), this, SLOT(setProject(QString)));
}
QFCompleterProperties::~QFCompleterProperties()
{
    setProject(NULL);
}
void ResourceAppointmentsView::draw( Project &project )
{
    setProject( &project );
}
void RoseFileComboBox::setDisplayOnlyFilename(bool newValue)
{
    dispOnlyFilename=newValue;
    //update display
    setProject(project);
}