<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2013 Torus Knot Software Ltd
Also see acknowledgements in Readme.html

You may use this sample code for anything you like, it is not covered by the
same license as the rest of the engine.
-----------------------------------------------------------------------------
*/

#include "DeferredShading.h"

#include "OgreConfigFile.h"
#include "OgreStringConverter.h"
#include "OgreException.h"

#include "OgreRoot.h"
#include "OgreRenderSystem.h"

#include "OgreEntity.h"
#include "OgreSubEntity.h"
#include "OgreRoot.h"

#include "OgreCompositor.h"
#include "OgreCompositorManager.h"
#include "OgreCompositorChain.h"
#include "OgreCompositorInstance.h"

#include "OgreLogManager.h"

#include "DeferredLightCP.h"
#include "SSAOLogic.h"
#include "GBufferSchemeHandler.h"
#include "NullSchemeHandler.h"

#include "SharedData.h"

namespace Ogre
{
    template<> SharedData* Singleton<SharedData>::msSingleton = 0;
}

using namespace Ogre;

const Ogre::uint8 DeferredShadingSystem::PRE_GBUFFER_RENDER_QUEUE = Ogre::RENDER_QUEUE_1;
const Ogre::uint8 DeferredShadingSystem::POST_GBUFFER_RENDER_QUEUE = Ogre::RENDER_QUEUE_8;

DeferredShadingSystem::DeferredShadingSystem(
		Viewport *vp, SceneManager *sm,  Camera *cam
	):
	mViewport(vp), mSceneMgr(sm), mCamera(cam)
{
	sm->setShadowTechnique(SHADOWTYPE_TEXTURE_ADDITIVE);
	sm->setShadowTextureCasterMaterial("DeferredShading/Shadows/Caster");
	mSceneMgr->setShadowTextureCount(1);
	mSceneMgr->setShadowFarDistance(150);
	//Use a value of "2" to use a different depth buffer pool and avoid sharing this with the Backbuffer's
	mSceneMgr->setShadowTextureConfig( 0, 512, 512, PF_FLOAT16_R, 2 );
	mSceneMgr->setShadowDirectionalLightExtrusionDistance(75);
}

void DeferredShadingSystem::initialize()
{
	for(int i=0; i<DSM_COUNT; ++i)
		mInstance[i]=0;

	createResources();

	mActive = false;

	mSSAO = false;
	mCurrentMode = DSM_SHOWLIT;
	setActive(true);
}

DeferredShadingSystem::~DeferredShadingSystem()
{
	CompositorChain *chain = CompositorManager::getSingleton().getCompositorChain(mViewport);
	for(int i=0; i<DSM_COUNT; ++i)
		chain->_removeInstance(mInstance[i]);
	CompositorManager::getSingleton().removeCompositorChain(mViewport);

	Ogre::CompositorManager& compMgr = Ogre::CompositorManager::getSingleton();
	CompositorLogicMap::const_iterator itor = mCompositorLogics.begin();
	CompositorLogicMap::const_iterator end  = mCompositorLogics.end();
	while( itor != end )
	{
		compMgr.unregisterCompositorLogic( itor->first );
		delete itor->second;
		++itor;
	}
	mCompositorLogics.clear();
}

void DeferredShadingSystem::setMode(DSMode mode)
{
	assert( 0 <= mode && mode < DSM_COUNT);

	// prevent duplicate setups
	if (mCurrentMode == mode && mInstance[mode]->getEnabled()==mActive)
		return;

	for(int i=0; i<DSM_COUNT; ++i)
	{
		if(i == mode)
		{
			mInstance[i]->setEnabled(mActive);
		}
		else
		{
			mInstance[i]->setEnabled(false);
		}
	}

	mCurrentMode = mode;

	mSSAOInstance->setEnabled(mActive && mSSAO && mCurrentMode == DSM_SHOWLIT);
}

void DeferredShadingSystem::setSSAO(bool ssao)
{
	if (ssao != mSSAO)
	{
		mSSAO = ssao;
		if (mActive && mCurrentMode == DSM_SHOWLIT)
		{
			mSSAOInstance->setEnabled(ssao);
		}
	}
}

bool DeferredShadingSystem::getSSAO() const
{
	return mSSAO;
}
void DeferredShadingSystem::setActive(bool active)
{
	if (mActive != active)
	{
		mActive = active;
		mGBufferInstance->setEnabled(active);

		// mCurrentMode could have changed with a prior call to setMode, so iterate all
		setMode(mCurrentMode);
	}
}

DeferredShadingSystem::DSMode DeferredShadingSystem::getMode(void) const
{
	return mCurrentMode;
}

void DeferredShadingSystem::createResources(void)
{
	CompositorManager &compMan = CompositorManager::getSingleton();

	//Hook up the compositor logic and scheme handlers.
	//This can theoretically happen in a loaded plugin, but in this case the demo contains the code.
	static bool firstTime = true;
	if (firstTime)
	{
		MaterialManager::getSingleton().addListener(new GBufferSchemeHandler, "GBuffer");
		MaterialManager::getSingleton().addListener(new NullSchemeHandler, "NoGBuffer");

		compMan.registerCustomCompositionPass("DeferredLight", new DeferredLightCompositionPass);

		firstTime = false;
	}

	mCompositorLogics["SSAOLogic"] = new SSAOLogic;
	compMan.registerCompositorLogic("SSAOLogic", mCompositorLogics["SSAOLogic"]);

	// Create the main GBuffer compositor
	mGBufferInstance = compMan.addCompositor(mViewport, "DeferredShading/GBuffer");

	// Create filters
	mInstance[DSM_SHOWLIT] = compMan.addCompositor(mViewport, "DeferredShading/ShowLit");
	mInstance[DSM_SHOWNORMALS] = compMan.addCompositor(mViewport, "DeferredShading/ShowNormals");
	mInstance[DSM_SHOWDSP] = compMan.addCompositor(mViewport, "DeferredShading/ShowDepthSpecular");
	mInstance[DSM_SHOWCOLOUR] = compMan.addCompositor(mViewport, "DeferredShading/ShowColour");

	mSSAOInstance =  compMan.addCompositor(mViewport, "DeferredShading/SSAO");
}

void DeferredShadingSystem::logCurrentMode(void)
{
	if (mActive==false)
	{
		LogManager::getSingleton().logMessage("No Compositor Enabled!");
		return;
	}

	CompositorInstance* ci = mInstance[mCurrentMode];
	assert(ci->getEnabled()==true);

	LogManager::getSingleton().logMessage("Current Mode: ");
	LogManager::getSingleton().logMessage(ci->getCompositor()->getName());
}
<commit_msg>[OGRE-263] Fix a deferred shading sample crash - the '2' was supposed to be depth buffer pool id, not FSAA, this caused issues when FSAA unsupported<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2013 Torus Knot Software Ltd
Also see acknowledgements in Readme.html

You may use this sample code for anything you like, it is not covered by the
same license as the rest of the engine.
-----------------------------------------------------------------------------
*/

#include "DeferredShading.h"

#include "OgreConfigFile.h"
#include "OgreStringConverter.h"
#include "OgreException.h"

#include "OgreRoot.h"
#include "OgreRenderSystem.h"

#include "OgreEntity.h"
#include "OgreSubEntity.h"
#include "OgreRoot.h"

#include "OgreCompositor.h"
#include "OgreCompositorManager.h"
#include "OgreCompositorChain.h"
#include "OgreCompositorInstance.h"

#include "OgreLogManager.h"

#include "DeferredLightCP.h"
#include "SSAOLogic.h"
#include "GBufferSchemeHandler.h"
#include "NullSchemeHandler.h"

#include "SharedData.h"

namespace Ogre
{
    template<> SharedData* Singleton<SharedData>::msSingleton = 0;
}

using namespace Ogre;

const Ogre::uint8 DeferredShadingSystem::PRE_GBUFFER_RENDER_QUEUE = Ogre::RENDER_QUEUE_1;
const Ogre::uint8 DeferredShadingSystem::POST_GBUFFER_RENDER_QUEUE = Ogre::RENDER_QUEUE_8;

DeferredShadingSystem::DeferredShadingSystem(
		Viewport *vp, SceneManager *sm,  Camera *cam
	):
	mViewport(vp), mSceneMgr(sm), mCamera(cam)
{
	sm->setShadowTechnique(SHADOWTYPE_TEXTURE_ADDITIVE);
	sm->setShadowTextureCasterMaterial("DeferredShading/Shadows/Caster");
	mSceneMgr->setShadowTextureCount(1);
	mSceneMgr->setShadowFarDistance(150);
	//Use a value of "2" to use a different depth buffer pool and avoid sharing this with the Backbuffer's
	mSceneMgr->setShadowTextureConfig( 0, 512, 512, PF_FLOAT16_R, 0, 2 );
	mSceneMgr->setShadowDirectionalLightExtrusionDistance(75);
}

void DeferredShadingSystem::initialize()
{
	for(int i=0; i<DSM_COUNT; ++i)
		mInstance[i]=0;

	createResources();

	mActive = false;

	mSSAO = false;
	mCurrentMode = DSM_SHOWLIT;
	setActive(true);
}

DeferredShadingSystem::~DeferredShadingSystem()
{
	CompositorChain *chain = CompositorManager::getSingleton().getCompositorChain(mViewport);
	for(int i=0; i<DSM_COUNT; ++i)
		chain->_removeInstance(mInstance[i]);
	CompositorManager::getSingleton().removeCompositorChain(mViewport);

	Ogre::CompositorManager& compMgr = Ogre::CompositorManager::getSingleton();
	CompositorLogicMap::const_iterator itor = mCompositorLogics.begin();
	CompositorLogicMap::const_iterator end  = mCompositorLogics.end();
	while( itor != end )
	{
		compMgr.unregisterCompositorLogic( itor->first );
		delete itor->second;
		++itor;
	}
	mCompositorLogics.clear();
}

void DeferredShadingSystem::setMode(DSMode mode)
{
	assert( 0 <= mode && mode < DSM_COUNT);

	// prevent duplicate setups
	if (mCurrentMode == mode && mInstance[mode]->getEnabled()==mActive)
		return;

	for(int i=0; i<DSM_COUNT; ++i)
	{
		if(i == mode)
		{
			mInstance[i]->setEnabled(mActive);
		}
		else
		{
			mInstance[i]->setEnabled(false);
		}
	}

	mCurrentMode = mode;

	mSSAOInstance->setEnabled(mActive && mSSAO && mCurrentMode == DSM_SHOWLIT);
}

void DeferredShadingSystem::setSSAO(bool ssao)
{
	if (ssao != mSSAO)
	{
		mSSAO = ssao;
		if (mActive && mCurrentMode == DSM_SHOWLIT)
		{
			mSSAOInstance->setEnabled(ssao);
		}
	}
}

bool DeferredShadingSystem::getSSAO() const
{
	return mSSAO;
}
void DeferredShadingSystem::setActive(bool active)
{
	if (mActive != active)
	{
		mActive = active;
		mGBufferInstance->setEnabled(active);

		// mCurrentMode could have changed with a prior call to setMode, so iterate all
		setMode(mCurrentMode);
	}
}

DeferredShadingSystem::DSMode DeferredShadingSystem::getMode(void) const
{
	return mCurrentMode;
}

void DeferredShadingSystem::createResources(void)
{
	CompositorManager &compMan = CompositorManager::getSingleton();

	//Hook up the compositor logic and scheme handlers.
	//This can theoretically happen in a loaded plugin, but in this case the demo contains the code.
	static bool firstTime = true;
	if (firstTime)
	{
		MaterialManager::getSingleton().addListener(new GBufferSchemeHandler, "GBuffer");
		MaterialManager::getSingleton().addListener(new NullSchemeHandler, "NoGBuffer");

		compMan.registerCustomCompositionPass("DeferredLight", new DeferredLightCompositionPass);

		firstTime = false;
	}

	mCompositorLogics["SSAOLogic"] = new SSAOLogic;
	compMan.registerCompositorLogic("SSAOLogic", mCompositorLogics["SSAOLogic"]);

	// Create the main GBuffer compositor
	mGBufferInstance = compMan.addCompositor(mViewport, "DeferredShading/GBuffer");

	// Create filters
	mInstance[DSM_SHOWLIT] = compMan.addCompositor(mViewport, "DeferredShading/ShowLit");
	mInstance[DSM_SHOWNORMALS] = compMan.addCompositor(mViewport, "DeferredShading/ShowNormals");
	mInstance[DSM_SHOWDSP] = compMan.addCompositor(mViewport, "DeferredShading/ShowDepthSpecular");
	mInstance[DSM_SHOWCOLOUR] = compMan.addCompositor(mViewport, "DeferredShading/ShowColour");

	mSSAOInstance =  compMan.addCompositor(mViewport, "DeferredShading/SSAO");
}

void DeferredShadingSystem::logCurrentMode(void)
{
	if (mActive==false)
	{
		LogManager::getSingleton().logMessage("No Compositor Enabled!");
		return;
	}

	CompositorInstance* ci = mInstance[mCurrentMode];
	assert(ci->getEnabled()==true);

	LogManager::getSingleton().logMessage("Current Mode: ");
	LogManager::getSingleton().logMessage(ci->getCompositor()->getName());
}
<|endoftext|>


<commit_before>/*
 * W.J. van der Laan 2011
 */
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"

#include "headers.h"
#include "init.h"
#include "util.h"

#include <QApplication>
#include <QMessageBox>
#include <QThread>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>

// Need a global reference for the notifications to find the GUI
BitcoinGUI *guiref;
QSplashScreen *splashref;

int MyMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y)
{
    // Message from main thread
    if(guiref)
    {
        guiref->error(QString::fromStdString(caption),
                      QString::fromStdString(message));
    }
    else
    {
        QMessageBox::critical(0, QString::fromStdString(caption),
            QString::fromStdString(message),
            QMessageBox::Ok, QMessageBox::Ok);
    }
    return 4;
}

int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y)
{
    bool modal = style & wxMODAL;

    if (modal)
        while (!guiref)
            Sleep(1000);

    // Message from network thread
    if(guiref)
    {
        QMetaObject::invokeMethod(guiref, "error", Qt::QueuedConnection,
                                   Q_ARG(QString, QString::fromStdString(caption)),
                                   Q_ARG(QString, QString::fromStdString(message)),
                                   Q_ARG(bool, modal));
    }
    else
    {
        printf("%s: %s\n", caption.c_str(), message.c_str());
        fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
    }
    return 4;
}

bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption, wxWindow* parent)
{
    if(!guiref)
        return false;
    if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
        return true;
    bool payFee = false;

    // Call slot on GUI thread.
    // If called from another thread, use a blocking QueuedConnection.
    Qt::ConnectionType connectionType = Qt::DirectConnection;
    if(QThread::currentThread() != QCoreApplication::instance()->thread())
    {
        connectionType = Qt::BlockingQueuedConnection;
    }

    QMetaObject::invokeMethod(guiref, "askFee", connectionType,
                               Q_ARG(qint64, nFeeRequired),
                               Q_ARG(bool*, &payFee));

    return payFee;
}

void CalledSetStatusBar(const std::string& strText, int nField)
{
    // Only used for built-in mining, which is disabled, simple ignore
}

void UIThreadCall(boost::function0<void> fn)
{
    // Only used for built-in mining, which is disabled, simple ignore
}

void MainFrameRepaint()
{
    if(guiref)
        QMetaObject::invokeMethod(guiref, "refreshStatusBar", Qt::QueuedConnection);
}

void InitMessage(const std::string &message)
{
    if(splashref)
    {
        splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
        QApplication::instance()->processEvents();
    }
}

/*
   Translate string to current locale using Qt.
 */
std::string _(const char* psz)
{
    return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}

int main(int argc, char *argv[])
{
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());

    Q_INIT_RESOURCE(bitcoin);
    QApplication app(argc, argv);

    // Load language files for system locale:
    // - First load the translator for the base language, without territory
    // - Then load the more specific locale translator
    QString lang_territory = QLocale::system().name(); // "en_US"
    QString lang = lang_territory;
    lang.truncate(lang_territory.lastIndexOf('_')); // "en"
    QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;

    qtTranslatorBase.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang);
    if (!qtTranslatorBase.isEmpty())
        app.installTranslator(&qtTranslatorBase);

    qtTranslator.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang_territory);
    if (!qtTranslator.isEmpty())
        app.installTranslator(&qtTranslator);

    translatorBase.load(":/translations/"+lang);
    if (!translatorBase.isEmpty())
        app.installTranslator(&translatorBase);

    translator.load(":/translations/"+lang_territory);
    if (!translator.isEmpty())
        app.installTranslator(&translator);

    app.setApplicationName(QApplication::translate("main", "Bitcoin-Qt"));

    QSplashScreen splash(QPixmap(":/images/splash"), 0);
    if (!GetBoolArg("-min"))
    {
        splash.show();
        splash.setAutoFillBackground(true);
        splashref = &splash;
    }

    app.processEvents();

    app.setQuitOnLastWindowClosed(false);

    try
    {
        if(AppInit2(argc, argv))
        {
            {
                // Put this in a block, so that BitcoinGUI is cleaned up properly before
                // calling Shutdown().
                BitcoinGUI window;
                if (splashref)
                    splash.finish(&window);
                OptionsModel optionsModel(pwalletMain);
                ClientModel clientModel(&optionsModel);
                WalletModel walletModel(pwalletMain, &optionsModel);

                guiref = &window;
                window.setClientModel(&clientModel);
                window.setWalletModel(&walletModel);

                window.show();

                app.exec();

                guiref = 0;
            }
            Shutdown(NULL);
        }
        else
        {
            return 1;
        }
    } catch (std::exception& e) {
        PrintException(&e, "Runaway exception");
    } catch (...) {
        PrintException(NULL, "Runaway exception");
    }
    return 0;
}
<commit_msg>Show a message box when runaway exception happens<commit_after>/*
 * W.J. van der Laan 2011
 */
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"

#include "headers.h"
#include "init.h"
#include "util.h"

#include <QApplication>
#include <QMessageBox>
#include <QThread>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>

// Need a global reference for the notifications to find the GUI
BitcoinGUI *guiref;
QSplashScreen *splashref;

int MyMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y)
{
    // Message from main thread
    if(guiref)
    {
        guiref->error(QString::fromStdString(caption),
                      QString::fromStdString(message));
    }
    else
    {
        QMessageBox::critical(0, QString::fromStdString(caption),
            QString::fromStdString(message),
            QMessageBox::Ok, QMessageBox::Ok);
    }
    return 4;
}

int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y)
{
    bool modal = style & wxMODAL;

    if (modal)
        while (!guiref)
            Sleep(1000);

    // Message from network thread
    if(guiref)
    {
        QMetaObject::invokeMethod(guiref, "error", Qt::QueuedConnection,
                                   Q_ARG(QString, QString::fromStdString(caption)),
                                   Q_ARG(QString, QString::fromStdString(message)),
                                   Q_ARG(bool, modal));
    }
    else
    {
        printf("%s: %s\n", caption.c_str(), message.c_str());
        fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
    }
    return 4;
}

bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption, wxWindow* parent)
{
    if(!guiref)
        return false;
    if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
        return true;
    bool payFee = false;

    // Call slot on GUI thread.
    // If called from another thread, use a blocking QueuedConnection.
    Qt::ConnectionType connectionType = Qt::DirectConnection;
    if(QThread::currentThread() != QCoreApplication::instance()->thread())
    {
        connectionType = Qt::BlockingQueuedConnection;
    }

    QMetaObject::invokeMethod(guiref, "askFee", connectionType,
                               Q_ARG(qint64, nFeeRequired),
                               Q_ARG(bool*, &payFee));

    return payFee;
}

void CalledSetStatusBar(const std::string& strText, int nField)
{
    // Only used for built-in mining, which is disabled, simple ignore
}

void UIThreadCall(boost::function0<void> fn)
{
    // Only used for built-in mining, which is disabled, simple ignore
}

void MainFrameRepaint()
{
    if(guiref)
        QMetaObject::invokeMethod(guiref, "refreshStatusBar", Qt::QueuedConnection);
}

void InitMessage(const std::string &message)
{
    if(splashref)
    {
        splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
        QApplication::instance()->processEvents();
    }
}

/*
   Translate string to current locale using Qt.
 */
std::string _(const char* psz)
{
    return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}

/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
 */
static void handleRunawayException(std::exception *e)
{
    PrintExceptionContinue(e, "Runaway exception");
    QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occured. Bitcoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
    exit(1);
}

int main(int argc, char *argv[])
{
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());

    Q_INIT_RESOURCE(bitcoin);
    QApplication app(argc, argv);

    // Load language files for system locale:
    // - First load the translator for the base language, without territory
    // - Then load the more specific locale translator
    QString lang_territory = QLocale::system().name(); // "en_US"
    QString lang = lang_territory;
    lang.truncate(lang_territory.lastIndexOf('_')); // "en"
    QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;

    qtTranslatorBase.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang);
    if (!qtTranslatorBase.isEmpty())
        app.installTranslator(&qtTranslatorBase);

    qtTranslator.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang_territory);
    if (!qtTranslator.isEmpty())
        app.installTranslator(&qtTranslator);

    translatorBase.load(":/translations/"+lang);
    if (!translatorBase.isEmpty())
        app.installTranslator(&translatorBase);

    translator.load(":/translations/"+lang_territory);
    if (!translator.isEmpty())
        app.installTranslator(&translator);

    app.setApplicationName(QApplication::translate("main", "Bitcoin-Qt"));

    QSplashScreen splash(QPixmap(":/images/splash"), 0);
    if (!GetBoolArg("-min"))
    {
        splash.show();
        splash.setAutoFillBackground(true);
        splashref = &splash;
    }

    app.processEvents();

    app.setQuitOnLastWindowClosed(false);

    try
    {
        if(AppInit2(argc, argv))
        {
            {
                // Put this in a block, so that BitcoinGUI is cleaned up properly before
                // calling Shutdown().
                BitcoinGUI window;
                if (splashref)
                    splash.finish(&window);
                OptionsModel optionsModel(pwalletMain);
                ClientModel clientModel(&optionsModel);
                WalletModel walletModel(pwalletMain, &optionsModel);

                guiref = &window;
                window.setClientModel(&clientModel);
                window.setWalletModel(&walletModel);

                window.show();

                app.exec();

                guiref = 0;
            }
            Shutdown(NULL);
        }
        else
        {
            return 1;
        }
    } catch (std::exception& e) {
        handleRunawayException(&e);
    } catch (...) {
        handleRunawayException(NULL);
    }
    return 0;
}
<|endoftext|>


<commit_before>
#include <Alert.h>
#include <Button.h>
#include <CheckBox.h>
#include <Font.h>
#include <MenuField.h>
#include <MenuItem.h>
#include <Message.h>
#include <PopUpMenu.h>
#include <StringView.h>
#include <TextControl.h>
#include <TextView.h>

#include "globals.h"
#include "dialeditpbook.h"
#include "gsm.h"

#include <stdio.h>

const uint32 NC			= 'DP00';
const uint32 MENU_SLOT	= 'DP01';
const uint32 MENU_FIELD	= 'DP02';
const uint32 BUT_REVERT = 'DP03';
const uint32 BUT_SAVE	= 'DP04';

dialEditPB::dialEditPB(const char *sl, GSM *g, struct pbNum *p = NULL) : BWindow(
	BRect(350,250,650,250+85),
	_("Phonebook entry"),
	B_TITLED_WINDOW, 0) {

	gsm = g;

	slotWrite = NULL;
	if (p)
		printf("edit in slot [%s]\n",sl);
	else
		printf("new in slot [%s]\n",sl);

	view = new BView(this->Bounds(), "editPBView", B_FOLLOW_ALL_SIDES, 0);
	view->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
	this->AddChild(view);

	float left = view->Bounds().left+10;
	float right = view->Bounds().right-10;
//	float half = left+(view->Bounds().Width()-20)/2-10;
	float quarters3 = left+(view->Bounds().Width()-20)*3/4-10;

	slotMenu = new BPopUpMenu(_("[select]"));
	BMessage *msg;
	BMenuItem *bi;

	int l = gsm->listMemSlotPB->CountItems();
	mSlots = new BMenuItem*[l+1];
	struct pbSlot *slot;
	for (int i=0;i<l;i++) {
		slot = (struct pbSlot*)gsm->listMemSlotPB->ItemAt(i);
		if ((slot->writable) && (slot->sname != "MT")) {
			msg = new BMessage(MENU_SLOT);
			msg->AddPointer("_slot",slot);
			slotMenu->AddItem(bi = new BMenuItem(slot->name.String(), msg));
			if (slot->sname == sl) {
				iniSlotNum = i;
				iniSlot = slot;
				slotWrite = slot;
				bi->SetMarked(true);
			}
			mSlots[i] = bi;
		}
	}

	// XXX at this point slotWrite can't be NULL! assert or do sth about it
	if (p) {
		num = p;
	} else {
		// create an empty pbNum
		num = new pbNum;
		num->id = -1;
		num->kind = GSM::PK_MOBILE;
		num->primary = false;
		// create attribute list
		num->attr = new BList;
		int j = slotWrite->fields->CountItems();
		struct pbField *pf;
		union pbVal *v;
		for (int i=0; i<j; i++) {
			pf = (struct pbField*)slotWrite->fields->ItemAt(i);
			v = new pbVal;
			switch (pf->type) {
				case GSM::PF_PHONE:
				case GSM::PF_PHONEEMAIL:
				case GSM::PF_TEXT:
					v->text = new BString("");
					break;
				case GSM::PF_BOOL:
					v->b = false;
					break;
				case GSM::PF_COMBO:
					v->v = -1;
					break;
			}
			num->attr->AddItem(v);
		}
	}

	BMenuField *mf;
	view->AddChild(mf = new BMenuField(BRect(15,15,quarters3,40),"slotMenuf",_("Slot:"),slotMenu));
	mf->SetDivider(be_plain_font->StringWidth(mf->Label())+5);

	view->AddChild(idText = new BStringView(BRect(quarters3+5,15,right,30),"idText","ID:"));

	BString tmp;
	BRect r = view->Bounds();
	r.left = left;
	r.right = right;
	r.top = 55;
	r.bottom = r.top + 30;

	// process slot fields
	int j = slotWrite->fields->CountItems();
	struct pbField *pf;
	BString id;
	BView *c;
	attr = new BList;
	union pbVal *pv;
	for (int i=0; i<j; i++) {
		// provide placeholder for menu value
		attr->AddItem(pv = new pbVal);
		pf = (struct pbField*)slotWrite->fields->ItemAt(i);
		id = "pf"; id << i;
		c = NULL;
		switch (pf->type) {
			case GSM::PF_PHONE:
			case GSM::PF_PHONEEMAIL:
				c = new BTextControl(BRect(r),id.String(),pf->name.String(),NULL,new BMessage(NC));
				break;
			case GSM::PF_TEXT:
				c = new BTextControl(BRect(r),id.String(),pf->name.String(),NULL,new BMessage(NC));
				break;
			case GSM::PF_BOOL:
				c = new BCheckBox(BRect(r),id.String(),pf->name.String(),new BMessage(NC));
				break;
			case GSM::PF_COMBO:
				{
					BPopUpMenu *m = new BPopUpMenu(_("[select]"));
					int l = pf->cb->CountItems();
					struct pbCombo *pc;
					for (int k=0; k<l; k++) {
						pc = (struct pbCombo*)pf->cb->ItemAt(k);
						msg = new BMessage(MENU_FIELD);
						msg->AddInt32("_id",i);
						msg->AddInt32("_value",pc->v);
						m->AddItem(new BMenuItem(pc->text.String(), msg));
					}
					c = new BMenuField(r, id.String(), pf->name.String(), m);
					// remember initial state
					pv->v = ((union pbVal*)num->attr->ItemAt(i))->v;
				}
				break;
		}
		if (c) {
			this->ResizeBy(0,30);
			view->AddChild(c);
			r.OffsetBy(0,30);
		}
	}

	BFont font(be_plain_font);
	this->ResizeBy(0,font.Size()*2+5);

	r = view->Bounds();
	r.InsetBy(20,20);
	r.top = r.bottom - font.Size()*2;
	tmp = _("Revert");
	r.right = r.left + font.StringWidth(tmp.String())+40;
	view->AddChild(new BButton(r, "butRevert", tmp.String(), new BMessage(BUT_REVERT), B_FOLLOW_LEFT|B_FOLLOW_BOTTOM));

	r = view->Bounds();
	r.InsetBy(20,20);
	r.top = r.bottom - font.Size()*2;
	tmp = _("Save");
	r.left = r.right - (font.StringWidth(tmp.String())+40);
	view->AddChild(new BButton(r, "butSave", tmp.String(), new BMessage(BUT_SAVE), B_FOLLOW_RIGHT|B_FOLLOW_BOTTOM));

	revertData();

	Show();
}

void dialEditPB::revertData(void) {
	// restore slot
	mSlots[iniSlotNum]->SetMarked(true);
	slotWrite = iniSlot;
	// restore data
	id = num->id;
	updateIdText();
	// extended attributes
	int j = slotWrite->fields->CountItems();
	struct pbField *pf;
	union pbVal *v;
	BView *c;
	BString id;
	for (int i=0; i<j; i++) {
		pf = (struct pbField*)slotWrite->fields->ItemAt(i);
		v = (union pbVal*)num->attr->ItemAt(i);
		id = "pf"; id << i;
		c = view->FindView(id.String());
		switch (pf->type) {
			case GSM::PF_PHONEEMAIL:
			case GSM::PF_PHONE:
			case GSM::PF_TEXT:
				((BTextControl*)c)->SetText(v->text->String());
				break;
			case GSM::PF_BOOL:
				((BCheckBox*)c)->SetValue(v->b ? B_CONTROL_ON : B_CONTROL_OFF);
				break;
			case GSM::PF_COMBO:
				{	BMenu *m = ((BMenuField*)c)->Menu();
					BMenuItem *it;
					int32 value;
					int k = m->CountItems();
					for (int l=0; l<k; l++) {
						it = m->ItemAt(l);
						it->Message()->FindInt32("_value",&value);
						if (value == v->v) {
							it->SetMarked(true);
							break;
						} else
							it->SetMarked(false);	// XXX doesn't quite work as deselector
					}
					((union pbVal*)attr->ItemAt(i))->v = v->v;
				}
				break;
		}
	}
}

void dialEditPB::validateData(void) {
	// go through all phone/p+e/text attributes, validate them and truncate
}

void dialEditPB::updateIdText(void) {
	BString tmp;
	if (id > 0) {
		tmp = _("ID:"); tmp += " "; tmp << id;
	} else {
		tmp = _("New entry");
	}
	idText->SetText(tmp.String());
}

void dialEditPB::switchToSlot(struct pbSlot *slot) {
	id = -1;
printf("new slot:[%s]\n",slot->sname.String());
	slotWrite = slot;
printf("min:%i,max:%i\n",slotWrite->min,slotWrite->max);
	if (slotWrite == iniSlot)
		id = num->id;
	updateIdText();
	// XXX check slot caps and limits
}

bool dialEditPB::saveData(void) {
	validateData();
	struct pbNum n;
	n.id = id;
	n.slot = slotWrite->sname;
	// go through all attributes and copy their values
	n.attr = new BList;	// XXX memleak - this is never freed
	union pbVal *nv;
	struct pbField *pf;
	BString id;
	BView *c;
	int j = slotWrite->fields->CountItems();
	for (int i=0; i<j; i++) {
		nv = new pbVal;
		pf = (struct pbField*)slotWrite->fields->ItemAt(i);
		// if 'combo' - read from own attr copy, otherwise from widget
		id = "pf"; id << i;
		c = view->FindView(id.String());
		switch (pf->type) {
			case GSM::PF_PHONEEMAIL:
			case GSM::PF_PHONE:
			case GSM::PF_TEXT:
				nv->text = new BString(((BTextControl*)c)->Text());
				break;
			case GSM::PF_BOOL:
				nv->b = (((BCheckBox*)c)->Value() == B_CONTROL_ON);
				break;
			case GSM::PF_COMBO:
				nv->v = ((union pbVal*)(attr->ItemAt(i)))->v;
				break;
		}
		n.attr->AddItem(nv);
	}
	// XXX validation - don't allow empty number/name??
	//
	if (gsm->storePBItem(&n) != 0) {
// XXX quite user friendly :/
		BAlert *a = new BAlert(APP_NAME, _("There was an error."),_("Ok"), NULL, NULL, B_WIDTH_AS_USUAL, B_WARNING_ALERT);
		a->Go();
		return false;
	}
	return true;
}

void dialEditPB::MessageReceived(BMessage *Message) {
	switch (Message->what) {
		case NC:
			validateData();
			break;
		case BUT_REVERT:
			revertData();
			break;
		case BUT_SAVE:
			if (saveData())
				Quit();
			break;
		case MENU_SLOT:
			{	void *ptr;
				if (Message->FindPointer("_slot",&ptr) == B_OK)
					switchToSlot((struct pbSlot*)ptr);
				break;
			}
		case MENU_FIELD:
			{	int32 id, value;
				Message->FindInt32("_id",&id);
				Message->FindInt32("_value",&value);
				((union pbVal*)attr->ItemAt(id))->v = value;
				break;
			}
		default:
			break;
	}
}
<commit_msg>- implemented truncating for validation (still no content checks)<commit_after>
#include <Alert.h>
#include <Button.h>
#include <CheckBox.h>
#include <Font.h>
#include <MenuField.h>
#include <MenuItem.h>
#include <Message.h>
#include <PopUpMenu.h>
#include <StringView.h>
#include <TextControl.h>
#include <TextView.h>

#include "globals.h"
#include "dialeditpbook.h"
#include "gsm.h"

#include <stdio.h>

const uint32 NC			= 'DP00';
const uint32 MENU_SLOT	= 'DP01';
const uint32 MENU_FIELD	= 'DP02';
const uint32 BUT_REVERT = 'DP03';
const uint32 BUT_SAVE	= 'DP04';

dialEditPB::dialEditPB(const char *sl, GSM *g, struct pbNum *p = NULL) : BWindow(
	BRect(350,250,650,250+85),
	_("Phonebook entry"),
	B_TITLED_WINDOW, 0) {

	gsm = g;

	slotWrite = NULL;
	if (p)
		printf("edit in slot [%s]\n",sl);
	else
		printf("new in slot [%s]\n",sl);

	view = new BView(this->Bounds(), "editPBView", B_FOLLOW_ALL_SIDES, 0);
	view->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
	this->AddChild(view);

	float left = view->Bounds().left+10;
	float right = view->Bounds().right-10;
//	float half = left+(view->Bounds().Width()-20)/2-10;
	float quarters3 = left+(view->Bounds().Width()-20)*3/4-10;

	slotMenu = new BPopUpMenu(_("[select]"));
	BMessage *msg;
	BMenuItem *bi;

	int l = gsm->listMemSlotPB->CountItems();
	mSlots = new BMenuItem*[l+1];
	struct pbSlot *slot;
	for (int i=0;i<l;i++) {
		slot = (struct pbSlot*)gsm->listMemSlotPB->ItemAt(i);
		if ((slot->writable) && (slot->sname != "MT")) {
			msg = new BMessage(MENU_SLOT);
			msg->AddPointer("_slot",slot);
			slotMenu->AddItem(bi = new BMenuItem(slot->name.String(), msg));
			if (slot->sname == sl) {
				iniSlotNum = i;
				iniSlot = slot;
				slotWrite = slot;
				bi->SetMarked(true);
			}
			mSlots[i] = bi;
		}
	}

	// XXX at this point slotWrite can't be NULL! assert or do sth about it
	if (p) {
		num = p;
	} else {
		// create an empty pbNum
		num = new pbNum;
		num->id = -1;
		num->kind = GSM::PK_MOBILE;
		num->primary = false;
		// create attribute list
		num->attr = new BList;
		int j = slotWrite->fields->CountItems();
		struct pbField *pf;
		union pbVal *v;
		for (int i=0; i<j; i++) {
			pf = (struct pbField*)slotWrite->fields->ItemAt(i);
			v = new pbVal;
			switch (pf->type) {
				case GSM::PF_PHONE:
				case GSM::PF_PHONEEMAIL:
				case GSM::PF_TEXT:
					v->text = new BString("");
					break;
				case GSM::PF_BOOL:
					v->b = false;
					break;
				case GSM::PF_COMBO:
					v->v = -1;
					break;
			}
			num->attr->AddItem(v);
		}
	}

	BMenuField *mf;
	view->AddChild(mf = new BMenuField(BRect(15,15,quarters3,40),"slotMenuf",_("Slot:"),slotMenu));
	mf->SetDivider(be_plain_font->StringWidth(mf->Label())+5);

	view->AddChild(idText = new BStringView(BRect(quarters3+5,15,right,30),"idText","ID:"));

	BString tmp;
	BRect r = view->Bounds();
	r.left = left;
	r.right = right;
	r.top = 55;
	r.bottom = r.top + 30;

	// process slot fields
	struct pbField *pf;
	BString id;
	BView *c;
	attr = new BList;
	union pbVal *pv;
	int j = slotWrite->fields->CountItems();
	for (int i=0; i<j; i++) {
		// provide placeholder for menu value
		attr->AddItem(pv = new pbVal);
		pf = (struct pbField*)slotWrite->fields->ItemAt(i);
		id = "pf"; id << i;
		c = NULL;
		switch (pf->type) {
			case GSM::PF_PHONE:
			case GSM::PF_PHONEEMAIL:
				c = new BTextControl(BRect(r),id.String(),pf->name.String(),NULL,new BMessage(NC));
				break;
			case GSM::PF_TEXT:
				c = new BTextControl(BRect(r),id.String(),pf->name.String(),NULL,new BMessage(NC));
				break;
			case GSM::PF_BOOL:
				c = new BCheckBox(BRect(r),id.String(),pf->name.String(),new BMessage(NC));
				break;
			case GSM::PF_COMBO:
				{
					BPopUpMenu *m = new BPopUpMenu(_("[select]"));
					int l = pf->cb->CountItems();
					struct pbCombo *pc;
					for (int k=0; k<l; k++) {
						pc = (struct pbCombo*)pf->cb->ItemAt(k);
						msg = new BMessage(MENU_FIELD);
						msg->AddInt32("_id",i);
						msg->AddInt32("_value",pc->v);
						m->AddItem(new BMenuItem(pc->text.String(), msg));
					}
					c = new BMenuField(r, id.String(), pf->name.String(), m);
					// remember initial state
					pv->v = ((union pbVal*)num->attr->ItemAt(i))->v;
				}
				break;
		}
		if (c) {
			this->ResizeBy(0,30);
			view->AddChild(c);
			r.OffsetBy(0,30);
		}
	}

	BFont font(be_plain_font);
	this->ResizeBy(0,font.Size()*2+5);

	r = view->Bounds();
	r.InsetBy(20,20);
	r.top = r.bottom - font.Size()*2;
	tmp = _("Revert");
	r.right = r.left + font.StringWidth(tmp.String())+40;
	view->AddChild(new BButton(r, "butRevert", tmp.String(), new BMessage(BUT_REVERT), B_FOLLOW_LEFT|B_FOLLOW_BOTTOM));

	r = view->Bounds();
	r.InsetBy(20,20);
	r.top = r.bottom - font.Size()*2;
	tmp = _("Save");
	r.left = r.right - (font.StringWidth(tmp.String())+40);
	view->AddChild(new BButton(r, "butSave", tmp.String(), new BMessage(BUT_SAVE), B_FOLLOW_RIGHT|B_FOLLOW_BOTTOM));

	revertData();

	Show();
}

void dialEditPB::revertData(void) {
	// restore slot
	mSlots[iniSlotNum]->SetMarked(true);
	slotWrite = iniSlot;
	// restore data
	id = num->id;
	updateIdText();
	// extended attributes
	struct pbField *pf;
	union pbVal *v;
	BView *c;
	BString id;
	int j = slotWrite->fields->CountItems();
	for (int i=0; i<j; i++) {
		pf = (struct pbField*)slotWrite->fields->ItemAt(i);
		v = (union pbVal*)num->attr->ItemAt(i);
		id = "pf"; id << i;
		c = view->FindView(id.String());
		switch (pf->type) {
			case GSM::PF_PHONEEMAIL:
			case GSM::PF_PHONE:
			case GSM::PF_TEXT:
				((BTextControl*)c)->SetText(v->text->String());
				break;
			case GSM::PF_BOOL:
				((BCheckBox*)c)->SetValue(v->b ? B_CONTROL_ON : B_CONTROL_OFF);
				break;
			case GSM::PF_COMBO:
				{	BMenu *m = ((BMenuField*)c)->Menu();
					BMenuItem *it;
					int32 value;
					int k = m->CountItems();
					for (int l=0; l<k; l++) {
						it = m->ItemAt(l);
						it->Message()->FindInt32("_value",&value);
						if (value == v->v) {
							it->SetMarked(true);
							break;
						} else
							it->SetMarked(false);	// XXX doesn't quite work as deselector
					}
					((union pbVal*)attr->ItemAt(i))->v = v->v;
				}
				break;
		}
	}
}

void dialEditPB::validateData(void) {
	struct pbField *pf;
	BString id, tmp;
	BView *c;
	int j = slotWrite->fields->CountItems();
	for (int i=0; i<j; i++) {
		pf = (struct pbField*)slotWrite->fields->ItemAt(i);
		id = "pf"; id << i;
		c = view->FindView(id.String());
		switch (pf->type) {
			case GSM::PF_PHONEEMAIL:
			case GSM::PF_PHONE:
			case GSM::PF_TEXT:
				tmp = ((BTextControl*)c)->Text();
				// XXX validate contents (phnumbers vs email vs text)
				tmp.Truncate(pf->max);
				((BTextControl*)c)->SetText(tmp.String());
				break;
			default:
				break;
		}
	}
}

void dialEditPB::updateIdText(void) {
	BString tmp;
	if (id > 0) {
		tmp = _("ID:"); tmp += " "; tmp << id;
	} else {
		tmp = _("New entry");
	}
	idText->SetText(tmp.String());
}

void dialEditPB::switchToSlot(struct pbSlot *slot) {
	id = -1;
printf("new slot:[%s]\n",slot->sname.String());
	slotWrite = slot;
printf("min:%i,max:%i\n",slotWrite->min,slotWrite->max);
	if (slotWrite == iniSlot)
		id = num->id;
	updateIdText();
	// XXX check slot caps and limits
}

bool dialEditPB::saveData(void) {
	validateData();
	struct pbNum n;
	n.id = id;
	n.slot = slotWrite->sname;
	// go through all attributes and copy their values
	n.attr = new BList;	// XXX memleak - this is never freed
	union pbVal *nv;
	struct pbField *pf;
	BString id;
	BView *c;
	int j = slotWrite->fields->CountItems();
	for (int i=0; i<j; i++) {
		nv = new pbVal;
		pf = (struct pbField*)slotWrite->fields->ItemAt(i);
		// if 'combo' - read from own attr copy, otherwise from widget
		id = "pf"; id << i;
		c = view->FindView(id.String());
		switch (pf->type) {
			case GSM::PF_PHONEEMAIL:
			case GSM::PF_PHONE:
			case GSM::PF_TEXT:
				nv->text = new BString(((BTextControl*)c)->Text());
				break;
			case GSM::PF_BOOL:
				nv->b = (((BCheckBox*)c)->Value() == B_CONTROL_ON);
				break;
			case GSM::PF_COMBO:
				nv->v = ((union pbVal*)(attr->ItemAt(i)))->v;
				break;
		}
		n.attr->AddItem(nv);
	}
	// XXX validation - don't allow empty number/name??
	//
	if (gsm->storePBItem(&n) != 0) {
// XXX quite user friendly :/
		BAlert *a = new BAlert(APP_NAME, _("There was an error."),_("Ok"), NULL, NULL, B_WIDTH_AS_USUAL, B_WARNING_ALERT);
		a->Go();
		return false;
	}
	return true;
}

void dialEditPB::MessageReceived(BMessage *Message) {
	switch (Message->what) {
		case NC:
			validateData();
			break;
		case BUT_REVERT:
			revertData();
			break;
		case BUT_SAVE:
			if (saveData())
				Quit();
			break;
		case MENU_SLOT:
			{	void *ptr;
				if (Message->FindPointer("_slot",&ptr) == B_OK)
					switchToSlot((struct pbSlot*)ptr);
				break;
			}
		case MENU_FIELD:
			{	int32 id, value;
				Message->FindInt32("_id",&id);
				Message->FindInt32("_value",&value);
				((union pbVal*)attr->ItemAt(id))->v = value;
				break;
			}
		default:
			break;
	}
}
<|endoftext|>


<commit_before>#include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include "init.h"

#include <QString>
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#include <QUrl>
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>

#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#include "shlobj.h"
#include "shellapi.h"
#endif

namespace GUIUtil {

QString dateTimeStr(const QDateTime &date)
{
    return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}

QString dateTimeStr(qint64 nTime)
{
    return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}

QFont bitcoinAddressFont()
{
    QFont font("Monospace");
    font.setStyleHint(QFont::TypeWriter);
    return font;
}

void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
    widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
    widget->setValidator(new BitcoinAddressValidator(parent));
    widget->setFont(bitcoinAddressFont());
}

void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
    QDoubleValidator *amountValidator = new QDoubleValidator(parent);
    amountValidator->setDecimals(8);
    amountValidator->setBottom(0.0);
    widget->setValidator(amountValidator);
    widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}

bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
    // NovaCoin: check prefix
    if(uri.scheme() != QString("Sterlingcoin"))
        return false;

    SendCoinsRecipient rv;
    rv.address = uri.path();
    rv.amount = 0;
    QList<QPair<QString, QString> > items = uri.queryItems();
    for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
    {
        bool fShouldReturnFalse = false;
        if (i->first.startsWith("req-"))
        {
            i->first.remove(0, 4);
            fShouldReturnFalse = true;
        }

        if (i->first == "label")
        {
            rv.label = i->second;
            fShouldReturnFalse = false;
        }
        else if (i->first == "amount")
        {
            if(!i->second.isEmpty())
            {
                if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
                {
                    return false;
                }
            }
            fShouldReturnFalse = false;
        }

        if (fShouldReturnFalse)
            return false;
    }
    if(out)
    {
        *out = rv;
    }
    return true;
}

bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
    // Convert Sterlingcoin:// to Sterlingcoin:
    //
    //    Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
    //    which will lower-case it (and thus invalidate the address).
    if(uri.startsWith("sterlingcoin://"))
    {
        uri.replace(0, 12, "sterlingcoin:");
    }
    QUrl uriInstance(uri);
    return parseBitcoinURI(uriInstance, out);
}

QString HtmlEscape(const QString& str, bool fMultiLine)
{
    QString escaped = Qt::escape(str);
    if(fMultiLine)
    {
        escaped = escaped.replace("\n", "
\n");
    }
    return escaped;
}

QString HtmlEscape(const std::string& str, bool fMultiLine)
{
    return HtmlEscape(QString::fromStdString(str), fMultiLine);
}

void copyEntryData(QAbstractItemView *view, int column, int role)
{
    if(!view || !view->selectionModel())
        return;
    QModelIndexList selection = view->selectionModel()->selectedRows(column);

    if(!selection.isEmpty())
    {
        // Copy first item
        QApplication::clipboard()->setText(selection.at(0).data(role).toString());
    }
}

QString getSaveFileName(QWidget *parent, const QString &caption,
                                 const QString &dir,
                                 const QString &filter,
                                 QString *selectedSuffixOut)
{
    QString selectedFilter;
    QString myDir;
    if(dir.isEmpty()) // Default to user documents location
    {
        myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
    }
    else
    {
        myDir = dir;
    }
    QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);

    /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
    QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
    QString selectedSuffix;
    if(filter_re.exactMatch(selectedFilter))
    {
        selectedSuffix = filter_re.cap(1);
    }

    /* Add suffix if needed */
    QFileInfo info(result);
    if(!result.isEmpty())
    {
        if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
        {
            /* No suffix specified, add selected suffix */
            if(!result.endsWith("."))
                result.append(".");
            result.append(selectedSuffix);
        }
    }

    /* Return selected suffix if asked to */
    if(selectedSuffixOut)
    {
        *selectedSuffixOut = selectedSuffix;
    }
    return result;
}

Qt::ConnectionType blockingGUIThreadConnection()
{
    if(QThread::currentThread() != QCoreApplication::instance()->thread())
    {
        return Qt::BlockingQueuedConnection;
    }
    else
    {
        return Qt::DirectConnection;
    }
}

bool checkPoint(const QPoint &p, const QWidget *w)
{
    QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
    if (!atW) return false;
    return atW->topLevelWidget() == w;
}

bool isObscured(QWidget *w)
{
    return !(checkPoint(QPoint(0, 0), w)
        && checkPoint(QPoint(w->width() - 1, 0), w)
        && checkPoint(QPoint(0, w->height() - 1), w)
        && checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
        && checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}

void openDebugLogfile()
{
    boost::filesystem::path pathDebug = GetDataDir() / "debug.log";

    /* Open debug.log with the associated application */
    if (boost::filesystem::exists(pathDebug))
        QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
}

ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
    QObject(parent), size_threshold(size_threshold)
{

}

bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
    if(evt->type() == QEvent::ToolTipChange)
    {
        QWidget *widget = static_cast<QWidget*>(obj);
        QString tooltip = widget->toolTip();
        if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt>") && !Qt::mightBeRichText(tooltip))
        {
            // Prefix <qt/> to make sure Qt detects this as rich text
            // Escape the current message as HTML and replace \n by

            tooltip = "<qt>" + HtmlEscape(tooltip, true) + "<qt/>";
            widget->setToolTip(tooltip);
            return true;
        }
    }
    return QObject::eventFilter(obj, evt);
}

#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
    return GetSpecialFolderPath(CSIDL_STARTUP) / "sterlingcoin.lnk";
}

bool GetStartOnSystemStartup()
{
    // check for Bitcoin.lnk
    return boost::filesystem::exists(StartupShortcutPath());
}

bool SetStartOnSystemStartup(bool fAutoStart)
{
    // If the shortcut exists already, remove it for updating
    boost::filesystem::remove(StartupShortcutPath());

    if (fAutoStart)
    {
        CoInitialize(NULL);

        // Get a pointer to the IShellLink interface.
        IShellLink* psl = NULL;
        HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
                                CLSCTX_INPROC_SERVER, IID_IShellLink,
                                reinterpret_cast<void**>(&psl));

        if (SUCCEEDED(hres))
        {
            // Get the current executable path
            TCHAR pszExePath[MAX_PATH];
            GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));

            TCHAR pszArgs[5] = TEXT("-min");

            // Set the path to the shortcut target
            psl->SetPath(pszExePath);
            PathRemoveFileSpec(pszExePath);
            psl->SetWorkingDirectory(pszExePath);
            psl->SetShowCmd(SW_SHOWMINNOACTIVE);
            psl->SetArguments(pszArgs);

            // Query IShellLink for the IPersistFile interface for
            // saving the shortcut in persistent storage.
            IPersistFile* ppf = NULL;
            hres = psl->QueryInterface(IID_IPersistFile,
                                       reinterpret_cast<void**>(&ppf));
            if (SUCCEEDED(hres))
            {
                WCHAR pwsz[MAX_PATH];
                // Ensure that the string is ANSI.
                MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
                // Save the link by calling IPersistFile::Save.
                hres = ppf->Save(pwsz, TRUE);
                ppf->Release();
                psl->Release();
                CoUninitialize();
                return true;
            }
            psl->Release();
        }
        CoUninitialize();
        return false;
    }
    return true;
}

#elif defined(LINUX)

// Follow the Desktop Application Autostart Spec:
//  http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html

boost::filesystem::path static GetAutostartDir()
{
    namespace fs = boost::filesystem;

    char* pszConfigHome = getenv("XDG_CONFIG_HOME");
    if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
    char* pszHome = getenv("HOME");
    if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
    return fs::path();
}

boost::filesystem::path static GetAutostartFilePath()
{
    return GetAutostartDir() / "sterlingcoin.desktop";
}

bool GetStartOnSystemStartup()
{
    boost::filesystem::ifstream optionFile(GetAutostartFilePath());
    if (!optionFile.good())
        return false;
    // Scan through file for "Hidden=true":
    std::string line;
    while (!optionFile.eof())
    {
        getline(optionFile, line);
        if (line.find("Hidden") != std::string::npos &&
            line.find("true") != std::string::npos)
            return false;
    }
    optionFile.close();

    return true;
}

bool SetStartOnSystemStartup(bool fAutoStart)
{
    if (!fAutoStart)
        boost::filesystem::remove(GetAutostartFilePath());
    else
    {
        char pszExePath[MAX_PATH+1];
        memset(pszExePath, 0, sizeof(pszExePath));
        if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
            return false;

        boost::filesystem::create_directories(GetAutostartDir());

        boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
        if (!optionFile.good())
            return false;
        // Write a bitcoin.desktop file to the autostart directory:
        optionFile << "[Desktop Entry]\n";
        optionFile << "Type=Application\n";
        optionFile << "Name=sterlingcoin\n";
        optionFile << "Exec=" << pszExePath << " -min\n";
        optionFile << "Terminal=false\n";
        optionFile << "Hidden=false\n";
        optionFile.close();
    }
    return true;
}
#else

// TODO: OSX startup stuff; see:
// https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html

bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }

#endif

HelpMessageBox::HelpMessageBox(QWidget *parent) :
    QMessageBox(parent)
{
    header = tr("Sterlingcoin-Qt") + " " + tr("version") + " " +
        QString::fromStdString(FormatFullVersion()) + "\n\n" +
        tr("Usage:") + "\n" +
        "  Sterlingcoin-qt [" + tr("command-line options") + "]                     " + "\n";

    coreOptions = QString::fromStdString(HelpMessage());

    uiOptions = tr("UI options") + ":\n" +
        "  -lang=<lang>           " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
        "  -min                   " + tr("Start minimized") + "\n" +
        "  -splash                " + tr("Show splash screen on startup (default: 1)") + "\n";

    setWindowTitle(tr("Sterlingcoin-Qt"));
    setTextFormat(Qt::PlainText);
    // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
    setText(header + QString(QChar(0x2003)).repeated(50));
    setDetailedText(coreOptions + "\n" + uiOptions);
}

void HelpMessageBox::printToConsole()
{
    // On other operating systems, the expected action is to print the message to the console.
    QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
    fprintf(stdout, "%s", strUsage.toStdString().c_str());
}

void HelpMessageBox::showOrPrint()
{
#if defined(WIN32)
        // On Windows, show a message box, as there is no stderr/stdout in windowed applications
        exec();
#else
        // On other operating systems, print help text to console
        printToConsole();
#endif
}

} // namespace GUIUtil

<commit_msg>URI Value Update<commit_after>#include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include "init.h"

#include <QString>
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#include <QUrl>
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>

#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#include "shlobj.h"
#include "shellapi.h"
#endif

namespace GUIUtil {

QString dateTimeStr(const QDateTime &date)
{
    return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}

QString dateTimeStr(qint64 nTime)
{
    return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}

QFont bitcoinAddressFont()
{
    QFont font("Monospace");
    font.setStyleHint(QFont::TypeWriter);
    return font;
}

void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
    widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
    widget->setValidator(new BitcoinAddressValidator(parent));
    widget->setFont(bitcoinAddressFont());
}

void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
    QDoubleValidator *amountValidator = new QDoubleValidator(parent);
    amountValidator->setDecimals(8);
    amountValidator->setBottom(0.0);
    widget->setValidator(amountValidator);
    widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}

bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
    // NovaCoin: check prefix
    if(uri.scheme() != QString("sterlingcoin"))
        return false;

    SendCoinsRecipient rv;
    rv.address = uri.path();
    rv.amount = 0;
    QList<QPair<QString, QString> > items = uri.queryItems();
    for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
    {
        bool fShouldReturnFalse = false;
        if (i->first.startsWith("req-"))
        {
            i->first.remove(0, 4);
            fShouldReturnFalse = true;
        }

        if (i->first == "label")
        {
            rv.label = i->second;
            fShouldReturnFalse = false;
        }
        else if (i->first == "amount")
        {
            if(!i->second.isEmpty())
            {
                if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
                {
                    return false;
                }
            }
            fShouldReturnFalse = false;
        }

        if (fShouldReturnFalse)
            return false;
    }
    if(out)
    {
        *out = rv;
    }
    return true;
}

bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
    // Convert Sterlingcoin:// to Sterlingcoin:
    //
    //    Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
    //    which will lower-case it (and thus invalidate the address).
    if(uri.startsWith("sterlingcoin://"))
    {
        uri.replace(0, 12, "sterlingcoin:");
    }
    QUrl uriInstance(uri);
    return parseBitcoinURI(uriInstance, out);
}

QString HtmlEscape(const QString& str, bool fMultiLine)
{
    QString escaped = Qt::escape(str);
    if(fMultiLine)
    {
        escaped = escaped.replace("\n", "
\n");
    }
    return escaped;
}

QString HtmlEscape(const std::string& str, bool fMultiLine)
{
    return HtmlEscape(QString::fromStdString(str), fMultiLine);
}

void copyEntryData(QAbstractItemView *view, int column, int role)
{
    if(!view || !view->selectionModel())
        return;
    QModelIndexList selection = view->selectionModel()->selectedRows(column);

    if(!selection.isEmpty())
    {
        // Copy first item
        QApplication::clipboard()->setText(selection.at(0).data(role).toString());
    }
}

QString getSaveFileName(QWidget *parent, const QString &caption,
                                 const QString &dir,
                                 const QString &filter,
                                 QString *selectedSuffixOut)
{
    QString selectedFilter;
    QString myDir;
    if(dir.isEmpty()) // Default to user documents location
    {
        myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
    }
    else
    {
        myDir = dir;
    }
    QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);

    /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
    QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
    QString selectedSuffix;
    if(filter_re.exactMatch(selectedFilter))
    {
        selectedSuffix = filter_re.cap(1);
    }

    /* Add suffix if needed */
    QFileInfo info(result);
    if(!result.isEmpty())
    {
        if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
        {
            /* No suffix specified, add selected suffix */
            if(!result.endsWith("."))
                result.append(".");
            result.append(selectedSuffix);
        }
    }

    /* Return selected suffix if asked to */
    if(selectedSuffixOut)
    {
        *selectedSuffixOut = selectedSuffix;
    }
    return result;
}

Qt::ConnectionType blockingGUIThreadConnection()
{
    if(QThread::currentThread() != QCoreApplication::instance()->thread())
    {
        return Qt::BlockingQueuedConnection;
    }
    else
    {
        return Qt::DirectConnection;
    }
}

bool checkPoint(const QPoint &p, const QWidget *w)
{
    QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
    if (!atW) return false;
    return atW->topLevelWidget() == w;
}

bool isObscured(QWidget *w)
{
    return !(checkPoint(QPoint(0, 0), w)
        && checkPoint(QPoint(w->width() - 1, 0), w)
        && checkPoint(QPoint(0, w->height() - 1), w)
        && checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
        && checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}

void openDebugLogfile()
{
    boost::filesystem::path pathDebug = GetDataDir() / "debug.log";

    /* Open debug.log with the associated application */
    if (boost::filesystem::exists(pathDebug))
        QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
}

ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
    QObject(parent), size_threshold(size_threshold)
{

}

bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
    if(evt->type() == QEvent::ToolTipChange)
    {
        QWidget *widget = static_cast<QWidget*>(obj);
        QString tooltip = widget->toolTip();
        if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt>") && !Qt::mightBeRichText(tooltip))
        {
            // Prefix <qt/> to make sure Qt detects this as rich text
            // Escape the current message as HTML and replace \n by

            tooltip = "<qt>" + HtmlEscape(tooltip, true) + "<qt/>";
            widget->setToolTip(tooltip);
            return true;
        }
    }
    return QObject::eventFilter(obj, evt);
}

#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
    return GetSpecialFolderPath(CSIDL_STARTUP) / "sterlingcoin.lnk";
}

bool GetStartOnSystemStartup()
{
    // check for Bitcoin.lnk
    return boost::filesystem::exists(StartupShortcutPath());
}

bool SetStartOnSystemStartup(bool fAutoStart)
{
    // If the shortcut exists already, remove it for updating
    boost::filesystem::remove(StartupShortcutPath());

    if (fAutoStart)
    {
        CoInitialize(NULL);

        // Get a pointer to the IShellLink interface.
        IShellLink* psl = NULL;
        HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
                                CLSCTX_INPROC_SERVER, IID_IShellLink,
                                reinterpret_cast<void**>(&psl));

        if (SUCCEEDED(hres))
        {
            // Get the current executable path
            TCHAR pszExePath[MAX_PATH];
            GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));

            TCHAR pszArgs[5] = TEXT("-min");

            // Set the path to the shortcut target
            psl->SetPath(pszExePath);
            PathRemoveFileSpec(pszExePath);
            psl->SetWorkingDirectory(pszExePath);
            psl->SetShowCmd(SW_SHOWMINNOACTIVE);
            psl->SetArguments(pszArgs);

            // Query IShellLink for the IPersistFile interface for
            // saving the shortcut in persistent storage.
            IPersistFile* ppf = NULL;
            hres = psl->QueryInterface(IID_IPersistFile,
                                       reinterpret_cast<void**>(&ppf));
            if (SUCCEEDED(hres))
            {
                WCHAR pwsz[MAX_PATH];
                // Ensure that the string is ANSI.
                MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
                // Save the link by calling IPersistFile::Save.
                hres = ppf->Save(pwsz, TRUE);
                ppf->Release();
                psl->Release();
                CoUninitialize();
                return true;
            }
            psl->Release();
        }
        CoUninitialize();
        return false;
    }
    return true;
}

#elif defined(LINUX)

// Follow the Desktop Application Autostart Spec:
//  http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html

boost::filesystem::path static GetAutostartDir()
{
    namespace fs = boost::filesystem;

    char* pszConfigHome = getenv("XDG_CONFIG_HOME");
    if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
    char* pszHome = getenv("HOME");
    if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
    return fs::path();
}

boost::filesystem::path static GetAutostartFilePath()
{
    return GetAutostartDir() / "sterlingcoin.desktop";
}

bool GetStartOnSystemStartup()
{
    boost::filesystem::ifstream optionFile(GetAutostartFilePath());
    if (!optionFile.good())
        return false;
    // Scan through file for "Hidden=true":
    std::string line;
    while (!optionFile.eof())
    {
        getline(optionFile, line);
        if (line.find("Hidden") != std::string::npos &&
            line.find("true") != std::string::npos)
            return false;
    }
    optionFile.close();

    return true;
}

bool SetStartOnSystemStartup(bool fAutoStart)
{
    if (!fAutoStart)
        boost::filesystem::remove(GetAutostartFilePath());
    else
    {
        char pszExePath[MAX_PATH+1];
        memset(pszExePath, 0, sizeof(pszExePath));
        if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
            return false;

        boost::filesystem::create_directories(GetAutostartDir());

        boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
        if (!optionFile.good())
            return false;
        // Write a bitcoin.desktop file to the autostart directory:
        optionFile << "[Desktop Entry]\n";
        optionFile << "Type=Application\n";
        optionFile << "Name=sterlingcoin\n";
        optionFile << "Exec=" << pszExePath << " -min\n";
        optionFile << "Terminal=false\n";
        optionFile << "Hidden=false\n";
        optionFile.close();
    }
    return true;
}
#else

// TODO: OSX startup stuff; see:
// https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html

bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }

#endif

HelpMessageBox::HelpMessageBox(QWidget *parent) :
    QMessageBox(parent)
{
    header = tr("Sterlingcoin-Qt") + " " + tr("version") + " " +
        QString::fromStdString(FormatFullVersion()) + "\n\n" +
        tr("Usage:") + "\n" +
        "  Sterlingcoin-qt [" + tr("command-line options") + "]                     " + "\n";

    coreOptions = QString::fromStdString(HelpMessage());

    uiOptions = tr("UI options") + ":\n" +
        "  -lang=<lang>           " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
        "  -min                   " + tr("Start minimized") + "\n" +
        "  -splash                " + tr("Show splash screen on startup (default: 1)") + "\n";

    setWindowTitle(tr("Sterlingcoin-Qt"));
    setTextFormat(Qt::PlainText);
    // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
    setText(header + QString(QChar(0x2003)).repeated(50));
    setDetailedText(coreOptions + "\n" + uiOptions);
}

void HelpMessageBox::printToConsole()
{
    // On other operating systems, the expected action is to print the message to the console.
    QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
    fprintf(stdout, "%s", strUsage.toStdString().c_str());
}

void HelpMessageBox::showOrPrint()
{
#if defined(WIN32)
        // On Windows, show a message box, as there is no stderr/stdout in windowed applications
        exec();
#else
        // On other operating systems, print help text to console
        printToConsole();
#endif
}

} // namespace GUIUtil

<|endoftext|>


<commit_before>// File_ChannelGrouping - Regrouping PCM streams
// Copyright (C) 2011-2011 MediaArea.net SARL, Info@MediaArea.net
//
// This library is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// Compilation conditions
#include "MediaInfo/Setup.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_AES3_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Audio/File_ChannelGrouping.h"
#if defined(MEDIAINFO_AES3_YES)
    #include "MediaInfo/Audio/File_Aes3.h"
#endif
#if MEDIAINFO_EVENTS
    #include "MediaInfo/MediaInfo_Events.h"
#endif //MEDIAINFO_EVENTS
#include "MediaInfo/MediaInfo_Config_MediaInfo.h"
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

File_ChannelGrouping::File_ChannelGrouping()
{
    //Configuration
    #if MEDIAINFO_EVENTS
        ParserIDs[0]=MediaInfo_Parser_ChannelGrouping;
    #endif //MEDIAINFO_EVENTS
    #if MEDIAINFO_DEMUX
        Demux_Level=2; //Container
    #endif //MEDIAINFO_DEMUX
    #if MEDIAINFO_TRACE
        Trace_Layers_Update(0); //Container1
    #endif //MEDIAINFO_TRACE

    //In
    ByteDepth=0;
    Common=NULL;
    Channel_Pos=0;
    Channel_Total=1;
}

File_ChannelGrouping::~File_ChannelGrouping()
{
    if (Channel_Pos==0)
        delete Common; //Common=NULL;
}

//***************************************************************************
// Streams management
//***************************************************************************

//---------------------------------------------------------------------------
void File_ChannelGrouping::Streams_Fill()
{
    Fill(Stream_General, 0, General_Format, "ChannelGrouping");

    if (Common->Channel_Master!=Channel_Pos)
        return;
    Fill(Common->Parser);
    Merge(*Common->Parser);
}

//---------------------------------------------------------------------------
void File_ChannelGrouping::Streams_Finish()
{
    if (Common->Channel_Master!=Channel_Pos)
        return;
    Finish(Common->Parser);
    //Merge(*Common->Parser);
}

//***************************************************************************
// Buffer - Global
//***************************************************************************

//---------------------------------------------------------------------------
void File_ChannelGrouping::Read_Buffer_Init()
{
    if (Common==NULL)
    {
        Common=new common;
        Common->Parser=new File_Aes3;
        ((File_Aes3*)Common->Parser)->ByteSize=ByteDepth*2;
        Common->Channels.resize(Channel_Total);
        for (size_t Pos=0; Pos<Common->Channels.size(); Pos++)
            Common->Channels[Pos]=new common::channel;
        Open_Buffer_Init(Common->Parser);
    }
    if (Channel_Pos)
        StreamIDs[StreamIDs_Size-2]=StreamID;
}

//---------------------------------------------------------------------------
void File_ChannelGrouping::Read_Buffer_Continue()
{
    if (Buffer_Size<ByteDepth)
        return; //Waiting for enough data

    //Copying to Channel buffer
    if (Common->Channels[Channel_Pos]->Buffer_Size+Buffer_Size>Common->Channels[Channel_Pos]->Buffer_Size_Max)
        Common->Channels[Channel_Pos]->resize(Common->Channels[Channel_Pos]->Buffer_Size+Buffer_Size);
    memcpy(Common->Channels[Channel_Pos]->Buffer+Common->Channels[Channel_Pos]->Buffer_Size, Buffer, Buffer_Size);
    Common->Channels[Channel_Pos]->Buffer_Size+=Buffer_Size;
    Buffer_Offset=Buffer_Size;
    Common->Channel_Current++;
    if (Common->Channel_Current>=Channel_Total)
        Common->Channel_Current=0;

    //Copying to merged channel
    size_t Minimum=(size_t)-1;
    for (size_t Pos=0; Pos<Common->Channels.size(); Pos++)
        if (Minimum>Common->Channels[Pos]->Buffer_Size-Common->Channels[Pos]->Buffer_Offset)
            Minimum=Common->Channels[Pos]->Buffer_Size-Common->Channels[Pos]->Buffer_Offset;
    while (Minimum>=ByteDepth)
    {
        for (size_t Pos=0; Pos<Common->Channels.size(); Pos++)
        {
            if (Common->MergedChannel.Buffer_Size+Minimum>Common->MergedChannel.Buffer_Size_Max)
                Common->MergedChannel.resize(Common->MergedChannel.Buffer_Size+Minimum);
            memcpy(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Size, Common->Channels[Pos]->Buffer+Common->Channels[Pos]->Buffer_Offset, ByteDepth);
            Common->Channels[Pos]->Buffer_Offset+=ByteDepth;
            Common->MergedChannel.Buffer_Size+=ByteDepth;
        }
        Minimum-=ByteDepth;
    }

    if (Common->MergedChannel.Buffer_Size-Common->MergedChannel.Buffer_Offset==0)
        return;

    //Buffer handling
    Ztring Format;
    /*
    if (StreamIDs_Size)
        Format=Config->ID_Format_Get(Ztring::ToZtring(StreamIDs[0]));
    if (Config->Demux_Unpacketize_Get() && (Format==_T("AES3") || Format==_T("Dolby E")))
    {
        while (Common->MergedChannel.Buffer_Offset+16<=Common->MergedChannel.Buffer_Size)
        {
            size_t Buffer_Offset_Temp=Common->MergedChannel.Buffer_Offset;
            if (Synchronize_AES3())
            {
                if (Buffer_Offset_Temp!=Common->MergedChannel.Buffer_Offset)
                    Open_Buffer_Continue(Common->Parser, Common->MergedChannel.Buffer+Buffer_Offset_Temp, Common->MergedChannel.Buffer_Offset-Buffer_Offset_Temp);

                size_t Buffer_Offset_Begin=Common->MergedChannel.Buffer_Offset;
                Common->MergedChannel.Buffer_Offset+=ByteDepth*2;
                if (Synchronize_AES3())
                {
                    size_t Buffer_Offset_End=Common->MergedChannel.Buffer_Offset;
                    Common->MergedChannel.Buffer_Offset=Buffer_Offset_Temp;

                    Demux(Common->MergedChannel.Buffer+Buffer_Offset_Begin, Buffer_Offset_End-Buffer_Offset_Begin, ContentType_MainStream);

                    Open_Buffer_Continue(Common->Parser, Common->MergedChannel.Buffer+Buffer_Offset_Begin, Buffer_Offset_End-Buffer_Offset_Begin);
                    Common->MergedChannel.Buffer_Offset=Buffer_Offset_End;
                }
                else
                {
                    Common->MergedChannel.Buffer_Offset=Buffer_Offset_Temp;
                    break;
                }
            }
            else
            {
                Common->MergedChannel.Buffer_Offset=Buffer_Offset_Temp;
                break;
            }
        }
    }
    else
    */
    {
        Demux(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset, Common->MergedChannel.Buffer_Size-Common->MergedChannel.Buffer_Offset, ContentType_MainStream);

        Open_Buffer_Continue(Common->Parser, Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset, Common->MergedChannel.Buffer_Size-Common->MergedChannel.Buffer_Offset);
        Common->MergedChannel.Buffer_Offset=Common->MergedChannel.Buffer_Size;
    }

    if (!Status[IsAccepted] && Common->Parser->Status[IsAccepted])
    {
        if (Common->Channel_Master==(size_t)-1)
            Common->Channel_Master=Channel_Pos;
        Accept();
    }
    if (!Status[IsAccepted] && Buffer_TotalBytes>=0x8000)
        Reject();
    if (Common->Parser->Status[IsFinished])
        Finish();

    //Optimize buffer
    for (size_t Pos=0; Pos<Common->Channels.size(); Pos++)
        Common->Channels[Pos]->optimize();
    Common->MergedChannel.optimize();
}

//***************************************************************************
// Buffer - Synchro
//***************************************************************************

//---------------------------------------------------------------------------
bool File_ChannelGrouping::Synchronize_AES3()
{
    //Synchronizing
    while (Common->MergedChannel.Buffer_Offset+16<=Common->MergedChannel.Buffer_Size)
    {
        if (CC4(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0xF8724E1F) //SMPTE 337M 16-bit, BE
        {
            break; //while()
        }
        if (CC4(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x72F81F4E) //SMPTE 337M 16-bit, LE
        {
            break; //while()
        }
        if (CC5(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x6F87254E1FLL) //SMPTE 337M 20-bit, BE
        {
            break; //while()
        }
        if (CC6(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x96F872A54E1FLL) //SMPTE 337M 24-bit, BE
        {
            break; //while()
        }
        if (CC6(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x72F8961F4E5ALL) //SMPTE 337M 24-bit, LE
        {
            break; //while()
        }
        if (CC6(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x00F872004E1FLL) //16-bit in 24-bit, BE
        {
            break; //while()
        }
        if (CC6(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x0072F8001F4ELL) //16-bit in 24-bit, LE
        {
            break; //while()
        }
        if (CC6(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x6F872054E1F0LL) //20-bit in 24-bit, BE
        {
            break; //while()
        }
        if (CC6(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x20876FF0E154LL) //20-bit in 24-bit, LE
        {
            break; //while()
        }
        if (CC8(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x0000F87200004E1FLL) //16-bit in 32-bit, BE
        {
            break; //while()
        }
        if (CC8(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x000072F800001F4ELL) //16-bit in 32-bit, LE
        {
            break; //while()
        }
        if (CC8(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x006F87200054E1F0LL) //20-bit in 32-bit, BE
        {
            break; //while()
        }
        if (CC8(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x0020876F00F0E154LL) //20-bit in 32-bit, LE
        {
            break; //while()
        }
        if (CC8(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x0096F8720A54E1FLL) //24-bit in 32-bit, BE
        {
            break; //while()
        }
        if (CC8(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x0072F896001F4EA5LL) //24-bit in 32-bit, LE
        {
            break; //while()
        }

        if (ByteDepth!=(size_t)-1)
            Common->MergedChannel.Buffer_Offset+=ByteDepth*2;
        else
            Common->MergedChannel.Buffer_Offset++;
    }

    //Parsing last bytes if needed
    if (Common->MergedChannel.Buffer_Offset+16>Common->MergedChannel.Buffer_Size)
    {
        return false;
    }

    //Synched
    return true;
}

//***************************************************************************
// C++
//***************************************************************************

} //NameSpace

#endif //MEDIAINFO_AES3_YES
<commit_msg>x Compiling error if event management is disabled<commit_after>// File_ChannelGrouping - Regrouping PCM streams
// Copyright (C) 2011-2011 MediaArea.net SARL, Info@MediaArea.net
//
// This library is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// Compilation conditions
#include "MediaInfo/Setup.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_AES3_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Audio/File_ChannelGrouping.h"
#if defined(MEDIAINFO_AES3_YES)
    #include "MediaInfo/Audio/File_Aes3.h"
#endif
#if MEDIAINFO_EVENTS
    #include "MediaInfo/MediaInfo_Events.h"
#endif //MEDIAINFO_EVENTS
#include "MediaInfo/MediaInfo_Config_MediaInfo.h"
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

File_ChannelGrouping::File_ChannelGrouping()
{
    //Configuration
    #if MEDIAINFO_EVENTS
        ParserIDs[0]=MediaInfo_Parser_ChannelGrouping;
    #endif //MEDIAINFO_EVENTS
    #if MEDIAINFO_DEMUX
        Demux_Level=2; //Container
    #endif //MEDIAINFO_DEMUX
    #if MEDIAINFO_TRACE
        Trace_Layers_Update(0); //Container1
    #endif //MEDIAINFO_TRACE

    //In
    ByteDepth=0;
    Common=NULL;
    Channel_Pos=0;
    Channel_Total=1;
}

File_ChannelGrouping::~File_ChannelGrouping()
{
    if (Channel_Pos==0)
        delete Common; //Common=NULL;
}

//***************************************************************************
// Streams management
//***************************************************************************

//---------------------------------------------------------------------------
void File_ChannelGrouping::Streams_Fill()
{
    Fill(Stream_General, 0, General_Format, "ChannelGrouping");

    if (Common->Channel_Master!=Channel_Pos)
        return;
    Fill(Common->Parser);
    Merge(*Common->Parser);
}

//---------------------------------------------------------------------------
void File_ChannelGrouping::Streams_Finish()
{
    if (Common->Channel_Master!=Channel_Pos)
        return;
    Finish(Common->Parser);
    //Merge(*Common->Parser);
}

//***************************************************************************
// Buffer - Global
//***************************************************************************

//---------------------------------------------------------------------------
void File_ChannelGrouping::Read_Buffer_Init()
{
    if (Common==NULL)
    {
        Common=new common;
        Common->Parser=new File_Aes3;
        ((File_Aes3*)Common->Parser)->ByteSize=ByteDepth*2;
        Common->Channels.resize(Channel_Total);
        for (size_t Pos=0; Pos<Common->Channels.size(); Pos++)
            Common->Channels[Pos]=new common::channel;
        Open_Buffer_Init(Common->Parser);
    }

    #if MEDIAINFO_EVENTS
        if (Channel_Pos)
            StreamIDs[StreamIDs_Size-2]=StreamID;
    #endif //MEDIAINFO_EVENTS
}

//---------------------------------------------------------------------------
void File_ChannelGrouping::Read_Buffer_Continue()
{
    if (Buffer_Size<ByteDepth)
        return; //Waiting for enough data

    //Copying to Channel buffer
    if (Common->Channels[Channel_Pos]->Buffer_Size+Buffer_Size>Common->Channels[Channel_Pos]->Buffer_Size_Max)
        Common->Channels[Channel_Pos]->resize(Common->Channels[Channel_Pos]->Buffer_Size+Buffer_Size);
    memcpy(Common->Channels[Channel_Pos]->Buffer+Common->Channels[Channel_Pos]->Buffer_Size, Buffer, Buffer_Size);
    Common->Channels[Channel_Pos]->Buffer_Size+=Buffer_Size;
    Buffer_Offset=Buffer_Size;
    Common->Channel_Current++;
    if (Common->Channel_Current>=Channel_Total)
        Common->Channel_Current=0;

    //Copying to merged channel
    size_t Minimum=(size_t)-1;
    for (size_t Pos=0; Pos<Common->Channels.size(); Pos++)
        if (Minimum>Common->Channels[Pos]->Buffer_Size-Common->Channels[Pos]->Buffer_Offset)
            Minimum=Common->Channels[Pos]->Buffer_Size-Common->Channels[Pos]->Buffer_Offset;
    while (Minimum>=ByteDepth)
    {
        for (size_t Pos=0; Pos<Common->Channels.size(); Pos++)
        {
            if (Common->MergedChannel.Buffer_Size+Minimum>Common->MergedChannel.Buffer_Size_Max)
                Common->MergedChannel.resize(Common->MergedChannel.Buffer_Size+Minimum);
            memcpy(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Size, Common->Channels[Pos]->Buffer+Common->Channels[Pos]->Buffer_Offset, ByteDepth);
            Common->Channels[Pos]->Buffer_Offset+=ByteDepth;
            Common->MergedChannel.Buffer_Size+=ByteDepth;
        }
        Minimum-=ByteDepth;
    }

    if (Common->MergedChannel.Buffer_Size-Common->MergedChannel.Buffer_Offset==0)
        return;

    //Buffer handling
    Ztring Format;
    /*
    if (StreamIDs_Size)
        Format=Config->ID_Format_Get(Ztring::ToZtring(StreamIDs[0]));
    if (Config->Demux_Unpacketize_Get() && (Format==_T("AES3") || Format==_T("Dolby E")))
    {
        while (Common->MergedChannel.Buffer_Offset+16<=Common->MergedChannel.Buffer_Size)
        {
            size_t Buffer_Offset_Temp=Common->MergedChannel.Buffer_Offset;
            if (Synchronize_AES3())
            {
                if (Buffer_Offset_Temp!=Common->MergedChannel.Buffer_Offset)
                    Open_Buffer_Continue(Common->Parser, Common->MergedChannel.Buffer+Buffer_Offset_Temp, Common->MergedChannel.Buffer_Offset-Buffer_Offset_Temp);

                size_t Buffer_Offset_Begin=Common->MergedChannel.Buffer_Offset;
                Common->MergedChannel.Buffer_Offset+=ByteDepth*2;
                if (Synchronize_AES3())
                {
                    size_t Buffer_Offset_End=Common->MergedChannel.Buffer_Offset;
                    Common->MergedChannel.Buffer_Offset=Buffer_Offset_Temp;

                    Demux(Common->MergedChannel.Buffer+Buffer_Offset_Begin, Buffer_Offset_End-Buffer_Offset_Begin, ContentType_MainStream);

                    Open_Buffer_Continue(Common->Parser, Common->MergedChannel.Buffer+Buffer_Offset_Begin, Buffer_Offset_End-Buffer_Offset_Begin);
                    Common->MergedChannel.Buffer_Offset=Buffer_Offset_End;
                }
                else
                {
                    Common->MergedChannel.Buffer_Offset=Buffer_Offset_Temp;
                    break;
                }
            }
            else
            {
                Common->MergedChannel.Buffer_Offset=Buffer_Offset_Temp;
                break;
            }
        }
    }
    else
    */
    {
        Demux(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset, Common->MergedChannel.Buffer_Size-Common->MergedChannel.Buffer_Offset, ContentType_MainStream);

        Open_Buffer_Continue(Common->Parser, Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset, Common->MergedChannel.Buffer_Size-Common->MergedChannel.Buffer_Offset);
        Common->MergedChannel.Buffer_Offset=Common->MergedChannel.Buffer_Size;
    }

    if (!Status[IsAccepted] && Common->Parser->Status[IsAccepted])
    {
        if (Common->Channel_Master==(size_t)-1)
            Common->Channel_Master=Channel_Pos;
        Accept();
    }
    if (!Status[IsAccepted] && Buffer_TotalBytes>=0x8000)
        Reject();
    if (Common->Parser->Status[IsFinished])
        Finish();

    //Optimize buffer
    for (size_t Pos=0; Pos<Common->Channels.size(); Pos++)
        Common->Channels[Pos]->optimize();
    Common->MergedChannel.optimize();
}

//***************************************************************************
// Buffer - Synchro
//***************************************************************************

//---------------------------------------------------------------------------
bool File_ChannelGrouping::Synchronize_AES3()
{
    //Synchronizing
    while (Common->MergedChannel.Buffer_Offset+16<=Common->MergedChannel.Buffer_Size)
    {
        if (CC4(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0xF8724E1F) //SMPTE 337M 16-bit, BE
        {
            break; //while()
        }
        if (CC4(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x72F81F4E) //SMPTE 337M 16-bit, LE
        {
            break; //while()
        }
        if (CC5(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x6F87254E1FLL) //SMPTE 337M 20-bit, BE
        {
            break; //while()
        }
        if (CC6(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x96F872A54E1FLL) //SMPTE 337M 24-bit, BE
        {
            break; //while()
        }
        if (CC6(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x72F8961F4E5ALL) //SMPTE 337M 24-bit, LE
        {
            break; //while()
        }
        if (CC6(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x00F872004E1FLL) //16-bit in 24-bit, BE
        {
            break; //while()
        }
        if (CC6(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x0072F8001F4ELL) //16-bit in 24-bit, LE
        {
            break; //while()
        }
        if (CC6(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x6F872054E1F0LL) //20-bit in 24-bit, BE
        {
            break; //while()
        }
        if (CC6(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x20876FF0E154LL) //20-bit in 24-bit, LE
        {
            break; //while()
        }
        if (CC8(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x0000F87200004E1FLL) //16-bit in 32-bit, BE
        {
            break; //while()
        }
        if (CC8(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x000072F800001F4ELL) //16-bit in 32-bit, LE
        {
            break; //while()
        }
        if (CC8(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x006F87200054E1F0LL) //20-bit in 32-bit, BE
        {
            break; //while()
        }
        if (CC8(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x0020876F00F0E154LL) //20-bit in 32-bit, LE
        {
            break; //while()
        }
        if (CC8(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x0096F8720A54E1FLL) //24-bit in 32-bit, BE
        {
            break; //while()
        }
        if (CC8(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset)==0x0072F896001F4EA5LL) //24-bit in 32-bit, LE
        {
            break; //while()
        }

        if (ByteDepth!=(size_t)-1)
            Common->MergedChannel.Buffer_Offset+=ByteDepth*2;
        else
            Common->MergedChannel.Buffer_Offset++;
    }

    //Parsing last bytes if needed
    if (Common->MergedChannel.Buffer_Offset+16>Common->MergedChannel.Buffer_Size)
    {
        return false;
    }

    //Synched
    return true;
}

//***************************************************************************
// C++
//***************************************************************************

} //NameSpace

#endif //MEDIAINFO_AES3_YES
<|endoftext|>