{
    printf("begin thread %p\n", (void*)CPLGetPID());
    CPLSetThreadLocalConfigOption("GDAL_RB_FLUSHBLOCK_SLEEP_AFTER_DROP_LOCK", "0.6");
    GDALFlushCacheBlock();
    CPLSetThreadLocalConfigOption("GDAL_RB_FLUSHBLOCK_SLEEP_AFTER_DROP_LOCK", "0");
    printf("end of thread\n\n");
}

/******************************************************************************
 * $Id$
 *
 * Project:  GDAL Core
 * Purpose:  Test block cache under multi-threading
 * Author:   Even Rouault, <even dot rouault at spatialys dot com>
 *
 ******************************************************************************
 *
 ****************************************************************************/

#include "cpl_conv.h"
#include "cpl_multiproc.h"
#include "cpl_string.h"
#include "gdal_priv.h"
#include "gdal.h"

#include "test_data.h"

template<typename T> void check(const T& x, const char* msg)
{
    if( !x )
    {
        fprintf(stderr, "CHECK(%s) failed\n", msg);
        exit(1);
    }
}

#define STRINGIFY(x) #x
#define CHECK(x) check((x), STRINGIFY(x))

static void thread_func(void* /* unused */)
{
    printf("begin thread %p\n", (void*)CPLGetPID());
    CPLSetThreadLocalConfigOption("GDAL_RB_INTERNALIZE_SLEEP_AFTER_DROP_LOCK", "0.6");
    GDALDatasetH hDS = GDALOpen(GCORE_DATA_DIR "byte.tif", GA_ReadOnly);
    char buf[20*20];
    CPL_IGNORE_RET_VAL(GDALRasterIO(GDALGetRasterBand(hDS, 1), GF_Read, 0, 0, 20, 20, buf, 20, 20, GDT_Byte, 0, 0));
    CPLSetThreadLocalConfigOption("GDAL_RB_INTERNALIZE_SLEEP_AFTER_DROP_LOCK", "0");
    GDALClose(hDS);
    printf("end of thread\n\n");
}

static void thread_func2(void* /* unused */)

static void thread_func3(void* /* unused */)
{
    printf("begin thread %p\n", (void*)CPLGetPID());
    CPLSleep(0.3);
    printf("begin GDALFlushCacheBlock\n");
    GDALFlushCacheBlock();
    printf("end of thread\n\n");
}

static void thread_func4(void* /* unused */)
{
    printf("begin thread %p\n", (void*)CPLGetPID());
    CPLSetThreadLocalConfigOption("GDAL_RB_FLUSHBLOCK_SLEEP_AFTER_RB_LOCK", "0.6");
    GDALFlushCacheBlock();
    CPLSetThreadLocalConfigOption("GDAL_RB_FLUSHBLOCK_SLEEP_AFTER_RB_LOCK", "0");
    printf("end of thread\n\n");
}

int main(int argc, char* argv[])
{
    CPLJoinableThread* hThread;

    printf("main thread %p\n", (void*)CPLGetPID());

    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );

    CPLSetConfigOption("GDAL_CACHEMAX", "0");
    CPLSetConfigOption("GDAL_DEBUG_BLOCK_CACHE", "ON");
    GDALAllRegister();

    GDALDatasetH hDS = GDALOpen(GCORE_DATA_DIR "byte.tif", GA_ReadOnly);

    char buf[20*20];
    printf("cache fill\n");
    CPL_IGNORE_RET_VAL(GDALRasterIO(GDALGetRasterBand(hDS, 1), GF_Read, 0, 0, 20, 20, buf, 20, 20, GDT_Byte, 0, 0));
    printf("end of cache fill\n");
    printf("buf[0]=%d\n\n", (int)buf[0]);

    hThread = CPLCreateJoinableThread(thread_func, nullptr);
    CPLSleep(0.3);

    printf("re read block\n");
    CPL_IGNORE_RET_VAL(GDALRasterIO(GDALGetRasterBand(hDS, 1), GF_Read, 0, 0, 20, 20, buf, 20, 20, GDT_Byte, 0, 0));
    printf("end of re read block\n");
    printf("buf[0]=%d\n", (int)buf[0]);
    CPLJoinThread(hThread);

    hThread = CPLCreateJoinableThread(thread_func2, nullptr);
    CPLSleep(0.3);

    printf("re read block\n");
    CPL_IGNORE_RET_VAL(GDALRasterIO(GDALGetRasterBand(hDS, 1), GF_Read, 0, 0, 20, 20, buf, 20, 20, GDT_Byte, 0, 0));
    printf("end of re read block\n");
    printf("buf[0]=%d\n", (int)buf[0]);
    CPLJoinThread(hThread);

    hThread = CPLCreateJoinableThread(thread_func3, nullptr);

    printf("re read block\n");
    CPLSetThreadLocalConfigOption("GDAL_RB_TRYGET_SLEEP_AFTER_TAKE_LOCK", "0.6");
    CPL_IGNORE_RET_VAL(GDALRasterIO(GDALGetRasterBand(hDS, 1), GF_Read, 0, 0, 20, 20, buf, 20, 20, GDT_Byte, 0, 0));
    CPLSetThreadLocalConfigOption("GDAL_RB_TRYGET_SLEEP_AFTER_TAKE_LOCK", "0");
    printf("end of re read block\n");
    printf("buf[0]=%d\n", (int)buf[0]);
    CPLJoinThread(hThread);

    hThread = CPLCreateJoinableThread(thread_func2, nullptr);
    CPLSleep(0.3);
    printf("before GDALFlushRasterCache\n");
    GDALFlushRasterCache(GDALGetRasterBand(hDS, 1));
    printf("after GDALFlushRasterCache\n");

    CPLJoinThread(hThread);
    CHECK( GDALGetCacheUsed64() == 0 );

    CPL_IGNORE_RET_VAL(GDALRasterIO(GDALGetRasterBand(hDS, 1), GF_Read, 0, 0, 20, 20, buf, 20, 20, GDT_Byte, 0, 0));
    hThread = CPLCreateJoinableThread(thread_func2, nullptr);
    CPLSleep(0.3);
    GDALClose(hDS);
    CPLJoinThread(hThread);

    hDS = GDALOpen(GCORE_DATA_DIR "byte.tif", GA_ReadOnly);
    CPL_IGNORE_RET_VAL(GDALRasterIO(GDALGetRasterBand(hDS, 1), GF_Read, 0, 0, 20, 20, buf, 20, 20, GDT_Byte, 0, 0));
    hThread = CPLCreateJoinableThread(thread_func4, nullptr);
    CPLSleep(0.3);
    GDALClose(hDS);
    CPLJoinThread(hThread);

    GDALDestroyDriverManager();
    CSLDestroy( argv );

    return 0;
}


/******************************************************************************
 * $Id$
 *
 * Project:  GDAL Core
 * Purpose:  Test block cache under multi-threading
 * Author:   Even Rouault, <even dot rouault at spatialys dot com>
 *
 ******************************************************************************
 *
 ****************************************************************************/

#include "cpl_conv.h"
#include "cpl_multiproc.h"
#include "cpl_string.h"
#include "gdal_priv.h"
#include "gdal.h"

#include "test_data.h"

template<typename T> void check(const T& x, const char* msg)
{
    if( !x )
    {
        fprintf(stderr, "CHECK(%s) failed\n", msg);
        exit(1);
    }
}

#define STRINGIFY(x) #x
#define CHECK(x) check((x), STRINGIFY(x))

static void thread_func(void* /* unused */)
{
    printf("begin thread %p\n", (void*)CPLGetPID());
    CPLSetThreadLocalConfigOption("GDAL_RB_INTERNALIZE_SLEEP_AFTER_DROP_LOCK", "0.6");
    GDALDatasetH hDS = GDALOpen(GCORE_DATA_DIR "byte.tif", GA_ReadOnly);
    char buf[20*20];
    CPL_IGNORE_RET_VAL(GDALRasterIO(GDALGetRasterBand(hDS, 1), GF_Read, 0, 0, 20, 20, buf, 20, 20, GDT_Byte, 0, 0));
    CPLSetThreadLocalConfigOption("GDAL_RB_INTERNALIZE_SLEEP_AFTER_DROP_LOCK", "0");
    GDALClose(hDS);
    printf("end of thread\n\n");
}

static void thread_func2(void* /* unused */)
{
    printf("begin thread %p\n", (void*)CPLGetPID());
    CPLSetThreadLocalConfigOption("GDAL_RB_FLUSHBLOCK_SLEEP_AFTER_DROP_LOCK", "0.6");
    GDALFlushCacheBlock();
    CPLSetThreadLocalConfigOption("GDAL_RB_FLUSHBLOCK_SLEEP_AFTER_DROP_LOCK", "0");
    printf("end of thread\n\n");
}

static void thread_func3(void* /* unused */)
{
    printf("begin thread %p\n", (void*)CPLGetPID());
    CPLSleep(0.3);
    printf("begin GDALFlushCacheBlock\n");
    GDALFlushCacheBlock();
    printf("end of thread\n\n");
}

static void thread_func4(void* /* unused */)
{
    printf("begin thread %p\n", (void*)CPLGetPID());
    CPLSetThreadLocalConfigOption("GDAL_RB_FLUSHBLOCK_SLEEP_AFTER_RB_LOCK", "0.6");
    GDALFlushCacheBlock();
    CPLSetThreadLocalConfigOption("GDAL_RB_FLUSHBLOCK_SLEEP_AFTER_RB_LOCK", "0");
    printf("end of thread\n\n");
}

int main(int argc, char* argv[])
{
    CPLJoinableThread* hThread;

    printf("main thread %p\n", (void*)CPLGetPID());

    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );

    CPLSetConfigOption("GDAL_CACHEMAX", "0");
    CPLSetConfigOption("GDAL_DEBUG_BLOCK_CACHE", "ON");
    GDALAllRegister();

    GDALDatasetH hDS =

    char buf[20*20];
    printf("cache fill\n");
    CPL_IGNORE_RET_VAL(GDALRasterIO(GDALGetRasterBand(hDS, 1), GF_Read, 0, 0, 20, 20, buf, 20, 20, GDT_Byte, 0, 0));
    printf("end of cache fill\n");
    printf("buf[0]=%d\n\n", (int)buf[0]);

    hThread = CPLCreateJoinableThread(thread_func, nullptr);
    CPLSleep(0.3);

    printf("re read block\n");
    CPL_IGNORE_RET_VAL(GDALRasterIO(GDALGetRasterBand(hDS, 1), GF_Read, 0, 0, 20, 20, buf, 20, 20, GDT_Byte, 0, 0));
    printf("end of re read block\n");
    printf("buf[0]=%d\n", (int)buf[0]);
    CPLJoinThread(hThread);

    hThread = CPLCreateJoinableThread(thread_func2, nullptr);
    CPLSleep(0.3);

    printf("re read block\n");
    CPL_IGNORE_RET_VAL(GDALRasterIO(GDALGetRasterBand(hDS, 1), GF_Read, 0, 0, 20, 20, buf, 20, 20, GDT_Byte, 0, 0));
    printf("end of re read block\n");
    printf("buf[0]=%d\n", (int)buf[0]);
    CPLJoinThread(hThread);

    hThread = CPLCreateJoinableThread(thread_func3, nullptr);

    printf("re read block\n");
    CPLSetThreadLocalConfigOption("GDAL_RB_TRYGET_SLEEP_AFTER_TAKE_LOCK", "0.6");
    CPL_IGNORE_RET_VAL(GDALRasterIO(GDALGetRasterBand(hDS, 1), GF_Read, 0, 0, 20, 20, buf, 20, 20, GDT_Byte, 0, 0));
    CPLSetThreadLocalConfigOption("GDAL_RB_TRYGET_SLEEP_AFTER_TAKE_LOCK", "0");
    printf("end of re read block\n");
    printf("buf[0]=%d\n", (int)buf[0]);
    CPLJoinThread(hThread);

    hThread = CPLCreateJoinableThread(thread_func2, nullptr);
    CPLSleep(0.3);
    printf("before GDALFlushRasterCache\n");
    GDALFlushRasterCache(GDALGetRasterBand(hDS, 1));
    printf("after GDALFlushRasterCache\n");

    CPLJoinThread(hThread);
    CHECK( GDALGetCacheUsed64() == 0 );

    CPL_IGNORE_RET_VAL(GDALRasterIO(GDALGetRasterBand(hDS, 1), GF_Read, 0, 0, 20, 20, buf, 20, 20, GDT_Byte, 0, 0));
    hThread = CPLCreateJoinableThread(thread_func2, nullptr);
    CPLSleep(0.3);
    GDALClose(hDS);
    CPLJoinThread(hThread);

    hDS = GDALOpen(GCORE_DATA_DIR "byte.tif", GA_ReadOnly);
    CPL_IGNORE_RET_VAL(GDALRasterIO(GDALGetRasterBand(hDS, 1), GF_Read, 0, 0, 20, 20, buf, 20, 20, GDT_Byte, 0, 0));
    hThread = CPLCreateJoinableThread(thread_func4, nullptr);
    CPLSleep(0.3);
    GDALClose(hDS);
    CPLJoinThread(hThread);

    GDALDestroyDriverManager();
    CSLDestroy( argv );

    return 0;
}


#include <iostream>
#include <osgDB/ReadFile>
#include <osgGA/StateSetManipulator>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgWidget/WindowManager>
#include <osgWidget/ViewerEventHandlers>
#include <osgWidget/Box>

const unsigned int MASK_2D = 0xF0000000;
const unsigned int MASK_3D = 0x0F000000;

// Here we create (and later demonstrate) the use of a simple function callback.
bool windowClicked(osgWidget::Event& ev) {
    std::cout << "windowClicked: " << ev.getWindow()->getName() << std::endl;

    if(ev.getData()) {
        std::string* s = static_cast<std::string*>(ev.getData());

        std::cout << "This is data attached to the event: " << *s << std::endl;
    }

    return true;
}

bool windowScrolled(osgWidget::Event& ev) {
    osgWidget::warn()
        << "scrolling up? " << ev.getWindowManager()->isMouseScrollingUp()
        << std::endl
    ;

    return true;
}

// Here we dcreate a new class and show how to use a method callback (which differs from
// a function callback in that we are required to also pass the "this" argument).
struct Object {
    bool windowClicked(osgWidget::Event& ev) {
        std::cout << "Object::windowClicked " << ev.getWindow()->getName() << std::endl;

        return true;
    }
};

// This is the more "traditional" method of creating a callback.
struct CallbackObject: public osgWidget::Callback {
    CallbackObject(osgWidget::EventType evType):
    osgWidget::Callback(evType) {
    }

    virtual bool operator()(osgWidget::Event& /*ev*/) {
        std::cout << "here" << std::endl;

        return false;
    }
};

{
    osgViewer::Viewer viewer;

    // Let's get busy! The WindowManager class is actually an osg::Switch,
    // so you can add it to (ideally) an orthographic camera and have it behave as
    // expected. Note that you create a WindowManager with a NodeMask--it is very important
    // that this be unique for picking to work properly. This also makes it possible to have
    // multiple WindowManagers each operating on their own, unique set of Window objects.
    // The final bool argument is a group of flags that introduce optional functionality
    // for the WindowManager. In our case we include the flags USE_PYTHON and USE_LUA,
    // to demonstrate (and test) their usage. Finally, we pass the temporary WM_NO_BETA_WARN
    // argument, which prevents creating the orange warning window. :) It will be shown
    // in other examples...
    osgWidget::WindowManager* wm = new osgWidget::WindowManager(
        &viewer,
        1280.0f,
        1024.0f,
        MASK_2D,
        osgWidget::WindowManager::WM_USE_LUA |
        osgWidget::WindowManager::WM_USE_PYTHON |
        osgWidget::WindowManager::WM_PICK_DEBUG
    );

    // An actual osgWidget::Window is pure virtual, so we've got to use the osgWidget::Box
    // implementation for now. At a later time, support for Tables and other kinds of
    // advanced layout Window types will be added.
    osgWidget::Window* box = new osgWidget::Box("box", osgWidget::Box::HORIZONTAL);

    // Now we actually attach our two types of callbacks to the box instance. The first
    // uses the simple function signature, the second uses a bound method, passing "this"
    // as the second argument to the Callback constructor.
    // Object obj;

    static std::string data = "lol ur face!";

    /*
    box->addCallback(new osgWidget::Callback(&windowClicked, osgWidget::EVENT_MOUSE_PUSH, &data));
    box->addCallback(new osgWidget::Callback(&windowScrolled, osgWidget::EVENT_MOUSE_SCROLL));
    box->addCallback(osgWidget::Callback(
        &Object::windowClicked,
        &obj,
        osgWidget::EVENT_MOUSE_PUSH
    ));
    */

    box->addCallback(new CallbackObject(osgWidget::EVENT_MOUSE_PUSH));

    // Create some of our "testing" Widgets; included are two Widget subclasses I made
    // during testing which I've kept around for testing purposes. You'll notice
    // that you cannot move the box using the NullWidget, and that the NotifyWidget
    // is a bit verbose. :)
    osgWidget::Widget* widget1 = new osgWidget::NotifyWidget("widget1", 300.0f, 100.0f);
    osgWidget::Widget* widget2 = new osgWidget::NullWidget("widget2", 400.0f, 75.0f);
    osgWidget::Widget* widget3 = new osgWidget::Widget("widget3", 100.0f, 100.0f);
    // Set the colors of widget1 and widget3 to green.
    widget1->setColor(0.0f, 1.0f, 0.0f, 1.0f);
    widget1->setCanFill(true);
    widget3->setColor(0.0f, 1.0f, 0.0f, 1.0f);

    widget1->setImage(osgDB::readRefImageFile("Images/Saturn.TGA"), true);

    // Set the color of widget2, to differentiate it and make it sassy. This is
    // like a poor man's gradient!
    widget2->setColor(0.9f, 0.0f, 0.0f, 0.9f, osgWidget::Widget::LOWER_LEFT);
    widget2->setColor(0.9f, 0.0f, 0.0f, 0.9f, osgWidget::Widget::LOWER_RIGHT);
    widget2->setColor(0.0f, 0.0f, 0.9f, 0.9f, osgWidget::Widget::UPPER_RIGHT);
    widget2->setColor(0.0f, 0.0f, 0.9f, 0.9f, osgWidget::Widget::UPPER_LEFT);

    // Now add our newly created widgets to our box.
    box->addWidget(widget1);
    box->addWidget(widget2);
    box->addWidget(widget3);

    // For maximum efficiency, Windows don't automatically reallocate their geometry
    // and internal positioning every time a widget is added. Thus, we either have to
    // call the WindowManger::resizeAllWindows method or manually call
    // Window::resize when we're ready.
    box->resize();

    // Now, lets clone our existing box and create a new copy of of it, also adding that
    // to the WindowManager. This demonstrates the usages of OSG's ->clone() support,
    // though that is abstracted by our META_UIObject macro.
    osgWidget::Window* boxCopy = osg::clone(box, "newBox", osg::CopyOp::DEEP_COPY_ALL);

    // Move our copy to make it visible.
    boxCopy->setOrigin(0.0f, 125.0f);

    boxCopy->getByName("widget1")->setColor(0.5f, 0.0f, 1.0f, 1.0f);
    boxCopy->getByName("widget3")->setColor(0.5f, 0.0f, 1.0f, 1.0f);

    // Add the successfully created Box (if we get this far) into the WindowManager, so
    // that they can receive events.
    wm->addChild(box);
    wm->addChild(boxCopy);

    // Now, ask our new box to be 100% the width of the WindowManager.
    boxCopy->resizePercent(100.0f, 0.0f);

    // Here we demonstrate the use of osgWidget/io_utils. This is really only useful for
    // debugging at the moment.

    // Setup our OSG objects for our scene; note the use of the utility function
    // createOrthoCamera, which is just a helper for setting up a proper viewing area.
    // An alternative (and a MUCH easier alternative at that!) is to
    // simply use the createParentOrthoCamera method of the WindowManager class,
    // which will wrap the calls to createOrthoCamera and addChild for us! Check out
    // some of the other examples to see this in action...
    osg::ref_ptr<osg::Group>  group  = new osg::Group();
    osg::ref_ptr<osg::Camera> camera = osgWidget::createOrthoCamera(1280.0f, 1024.0f);
    osg::ref_ptr<osg::Node>   model  = osgDB::readRefNodeFile("cow.osgt");

    // Add our event handler; is this better as a MatrixManipulator? Add a few other
    // helpful ViewerEventHandlers.
    viewer.addEventHandler(new osgWidget::MouseHandler(wm));
    viewer.addEventHandler(new osgWidget::KeyboardHandler(wm));
    viewer.addEventHandler(new osgWidget::ResizeHandler(wm, camera.get()));
    viewer.addEventHandler(new osgWidget::CameraSwitchHandler(wm, camera.get()));
    viewer.addEventHandler(new osgViewer::StatsHandler());
    viewer.addEventHandler(new osgViewer::WindowSizeHandler());
    viewer.addEventHandler(new osgGA::StateSetManipulator(
        viewer.getCamera()->getOrCreateStateSet()
    ));

    // Set our first non-UI node to be something other than the mask we created our
    // WindowManager with to avoid picking.
    // TODO: Do I need to create a mechanism for doing this automatically, or should
    // that be the responsibility of the users of osgWidget?
    model->setNodeMask(MASK_3D);

    // Add the WindowManager instance to the 2D camera. This isn't strictly necessary,
    // and you can get some cool results putting the WindowManager directly into a
    // 3D scene. This is not necessary if you use WindowManager::createParentOrthoCamera.
    camera->addChild(wm);

    // Add our camera and a testing 3D model to the scene.
    group->addChild(camera);
    group->addChild(model);

    // Here we show how to both run simple strings of code AND run entire files. These
    // assume that you're running the osgwidgetwindow example from the build directory,
    // otherwise you'll need to adjust the file path below in the call to runFile().
    wm->getLuaEngine()->eval("window = osgwidget.newWindow()");
    wm->getLuaEngine()->runFile("osgWidget/osgwidgetwindow.lua");

    wm->getPythonEngine()->eval("import osgwidget");
    wm->getPythonEngine()->runFile("osgWidget/osgwidgetwindow.py");

    viewer.setUpViewInWindow(0, 0, 1280, 1024);
    viewer.setSceneData(group);

    /*
    osgViewer::Viewer::Cameras cameras;
    viewer.getCameras(cameras);
    osg::Camera* c = cameras[0];
    osg::Matrix s = osg::Matrix::scale(1.0f, -1.0f, 1.0f);
    c->setProjectionMatrix(s * c->getProjectionMatrix());
    */

    return viewer.run();
}


{
        std::cout << "here" << std::endl;

        return false;
    }

#include <iostream>
#include <osgDB/ReadFile>
#include <osgGA/StateSetManipulator>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgWidget/WindowManager>
#include <osgWidget/ViewerEventHandlers>
#include <osgWidget/Box>

const unsigned int MASK_2D = 0xF0000000;
const unsigned int MASK_3D = 0x0F000000;

// Here we create (and later demonstrate) the use of a simple function callback.
bool windowClicked(osgWidget::Event& ev) {
    std::cout << "windowClicked: " << ev.getWindow()->getName() << std::endl;

    if(ev.getData()) {
        std::string* s = static_cast<std::string*>(ev.getData());

        std::cout << "This is data attached to the event: " << *s << std::endl;
    }

    return true;
}

bool windowScrolled(osgWidget::Event& ev) {
    osgWidget::warn()
        << "scrolling up? " << ev.getWindowManager()->isMouseScrollingUp()
        << std::endl
    ;

    return true;
}

// Here we dcreate a new class and show how to use a method callback (which differs from
// a function callback in that we are required to also pass the "this" argument).
struct Object {
    bool windowClicked(osgWidget::Event& ev) {
        std::cout << "Object::windowClicked " << ev.getWindow()->getName() << std::endl;

        return true;
    }
};

// This is the more "traditional" method of creating a callback.
struct CallbackObject: public osgWidget::Callback {
    CallbackObject(osgWidget::EventType evType):
    osgWidget::Callback(evType) {
    }

    virtual bool operator()(osgWidget::Event& /*ev*/)

};

int main(int, char**)
{
    osgViewer::Viewer viewer;

    // Let's get busy! The WindowManager class is actually an osg::Switch,
    // so you can add it to (ideally) an orthographic camera and have it behave as
    // expected. Note that you create a WindowManager with a NodeMask--it is very important
    // that this be unique for picking to work properly. This also makes it possible to have
    // multiple WindowManagers each operating on their own, unique set of Window objects.
    // The final bool argument is a group of flags that introduce optional functionality
    // for the WindowManager. In our case we include the flags USE_PYTHON and USE_LUA,
    // to demonstrate (and test) their usage. Finally, we pass the temporary WM_NO_BETA_WARN
    // argument, which prevents creating the orange warning window. :) It will be shown
    // in other examples...
    osgWidget::WindowManager* wm = new osgWidget::WindowManager(
        &viewer,
        1280.0f,
        1024.0f,
        MASK_2D,
        osgWidget::WindowManager::WM_USE_LUA |
        osgWidget::WindowManager::WM_USE_PYTHON |
        osgWidget::WindowManager::WM_PICK_DEBUG
    );

    // An actual osgWidget::Window is pure virtual, so we've got to use the osgWidget::Box
    // implementation for now. At a later time, support for Tables and other kinds of
    // advanced layout Window types will be added.
    osgWidget::Window* box = new osgWidget::Box("box", osgWidget::Box::HORIZONTAL);

    // Now we actually attach our two types of callbacks to the box instance. The first
    // uses the simple function signature, the second uses a bound method, passing "this"
    // as the second argument to the Callback constructor.
    // Object obj;

    static std::string data = "lol ur face!";

    /*
    box->addCallback(new osgWidget::Callback(&windowClicked, osgWidget::EVENT_MOUSE_PUSH, &data));
    box->addCallback(new osgWidget::Callback(&windowScrolled, osgWidget::EVENT_MOUSE_SCROLL));
    box->addCallback(osgWidget::Callback(
        &Object::windowClicked,
        &obj,
        osgWidget::EVENT_MOUSE_PUSH
    ));
    */

    box->addCallback(new CallbackObject(osgWidget::EVENT_MOUSE_PUSH));

    // Create some of our "testing" Widgets; included are two Widget subclasses I made
    // during testing which I've kept around for testing purposes. You'll notice
    // that you cannot move the box using the NullWidget, and that the NotifyWidget
    // is a bit verbose. :)
    osgWidget::Widget* widget1 = new osgWidget::NotifyWidget("widget1", 300.0f, 100.0f);
    osgWidget::Widget* widget2 = new osgWidget::NullWidget("widget2", 400.0f, 75.0f);
    osgWidget::Widget* widget3 = new osgWidget::Widget("widget3", 100.0f, 100.0f);
    // Set the colors of widget1 and widget3 to green.
    widget1->setColor(0.0f, 1.0f, 0.0f, 1.0f);
    widget1->setCanFill(true);
    widget3->setColor(0.0f, 1.0f, 0.0f, 1.0f);

    widget1->setImage(osgDB::readRefImageFile("Images/Saturn.TGA"), true);

    // Set the color of widget2, to differentiate it and make it sassy. This is
    // like a poor man's gradient!
    widget2->setColor(0.9f, 0.0f, 0.0f, 0.9f, osgWidget::Widget::LOWER_LEFT);
    widget2->setColor(0.9f, 0.0f, 0.0f, 0.9f, osgWidget::Widget::LOWER_RIGHT);
    widget2->setColor(0.0f, 0.0f, 0.9f, 0.9f, osgWidget::Widget::UPPER_RIGHT);
    widget2->setColor(0.0f, 0.0f, 0.9f, 0.9f, osgWidget::Widget::UPPER_LEFT);

    // Now add our newly created widgets to our box.
    box->addWidget(widget1);
    box->addWidget(widget2);
    box->addWidget(widget3);

    // For maximum efficiency, Windows don't automatically reallocate their geometry
    // and internal positioning every time a widget is added. Thus, we either have to
    // call the WindowManger::resizeAllWindows method or manually call
    // Window::resize when we're ready.
    box->resize();

    // Now, lets clone our existing box and create a new copy of of it, also adding that
    // to the WindowManager. This demonstrates the usages of OSG's ->clone() support,
    // though that is abstracted by our META_UIObject macro.
    osgWidget::Window* boxCopy = osg::clone(box, "newBox", osg::CopyOp::DEEP_COPY_ALL);

    // Move our copy to make it visible.
    boxCopy->setOrigin(0.0f, 125.0f);

    boxCopy->getByName("widget1")->setColor(0.5f, 0.0f, 1.0f, 1.0f);
    boxCopy->getByName("widget3")->setColor(0.5f, 0.0f, 1.0f, 1.0f);

    // Add the successfully created Box (if we get this far) into the WindowManager, so
    // that they can receive events.
    wm->addChild(box);
    wm->addChild(boxCopy);

    // Now, ask our new box to be 100% the width of the WindowManager.
    boxCopy->resizePercent(100.0f, 0.0f);

    // Here we demonstrate the use of osgWidget/io_utils. This is really only useful for
    // debugging at the moment.

    // Setup our OSG objects for our scene; note the use of the utility function
    // createOrthoCamera, which is just a helper for setting up a proper viewing area.
    // An alternative (and a MUCH easier alternative at that!) is to
    // simply use the createParentOrthoCamera method of the WindowManager class,
    // which will wrap the calls to createOrthoCamera and addChild for us! Check out
    // some of the other examples to see this in action...
    osg::ref_ptr<osg::Group>  group  = new osg::Group();
    osg::ref_ptr<osg::Camera> camera = osgWidget::createOrthoCamera(1280.0f, 1024.0f);
    osg::ref_ptr<osg::Node>   model  = osgDB::readRefNodeFile("cow.osgt");

    // Add our event handler; is this better as a MatrixManipulator? Add a few other
    // helpful ViewerEventHandlers.
    viewer.addEventHandler(new osgWidget::MouseHandler(wm));
    viewer.addEventHandler(new osgWidget::KeyboardHandler(wm));
    viewer.addEventHandler(new osgWidget::ResizeHandler(wm, camera.get()));
    viewer.addEventHandler(new osgWidget::CameraSwitchHandler(wm, camera.get()));
    viewer.addEventHandler(new osgViewer::StatsHandler());
    viewer.addEventHandler(new osgViewer::WindowSizeHandler());
    viewer.addEventHandler(new osgGA::StateSetManipulator(
        viewer.getCamera()->getOrCreateStateSet()
    ));

    // Set our first non-UI node to be something other than the mask we created our
    // WindowManager with to avoid picking.
    // TODO: Do I need to create a mechanism for doing this automatically, or should
    // that be the responsibility of the users of osgWidget?
    model->setNodeMask(MASK_3D);

    // Add the WindowManager instance to the 2D camera. This isn't strictly necessary,
    // and you can get some cool results putting the WindowManager directly into a
    // 3D scene. This is not necessary if you use WindowManager::createParentOrthoCamera.
    camera->addChild(wm);

    // Add our camera and a testing 3D model to the scene.
    group->addChild(camera);
    group->addChild(model);

    // Here we show how to both run simple strings of code AND run entire files. These
    // assume that you're running the osgwidgetwindow example from the build directory,
    // otherwise you'll need to adjust the file path below in the call to runFile().
    wm->getLuaEngine()->eval("window = osgwidget.newWindow()");
    wm->getLuaEngine()->runFile("osgWidget/osgwidgetwindow.lua");

    wm->getPythonEngine()->eval("import osgwidget");
    wm->getPythonEngine()->runFile("osgWidget/osgwidgetwindow.py");

    viewer.setUpViewInWindow(0, 0, 1280, 1024);
    viewer.setSceneData(group);

    /*
    osgViewer::Viewer::Cameras cameras;
    viewer.getCameras(cameras);
    osg::Camera* c = cameras[0];
    osg::Matrix s = osg::Matrix::scale(1.0f, -1.0f, 1.0f);
    c->setProjectionMatrix(s * c->getProjectionMatrix());
    */

    return viewer.run();
}


#include <iostream>
#include <osgDB/ReadFile>
#include <osgGA/StateSetManipulator>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgWidget/WindowManager>
#include <osgWidget/ViewerEventHandlers>
#include <osgWidget/Box>

const unsigned int MASK_2D = 0xF0000000;
const unsigned int MASK_3D = 0x0F000000;

// Here we create (and later demonstrate) the use of a simple function callback.
bool windowClicked(osgWidget::Event& ev) {
    std::cout << "windowClicked: " << ev.getWindow()->getName() << std::endl;

    if(ev.getData()) {
        std::string* s = static_cast<std::string*>(ev.getData());

        std::cout << "This is data attached to the event: " << *s << std::endl;
    }

    return true;
}

bool windowScrolled(osgWidget::Event& ev) {
    osgWidget::warn()
        << "scrolling up? " << ev.getWindowManager()->isMouseScrollingUp()
        << std::endl
    ;

    return true;
}

// Here we dcreate a new class and show how to use a method callback (which differs from
// a function callback in that we are required to also pass the "this" argument).
struct Object {
    bool windowClicked(osgWidget::Event& ev) {
        std::cout << "Object::windowClicked " << ev.getWindow()->getName() << std::endl;

        return true;
    }
};

// This is the more "traditional" method of creating a callback.
struct CallbackObject: public osgWidget::Callback {
    CallbackObject(osgWidget::EventType evType):
    osgWidget::Callback(evType) {
    }

    virtual bool operator()(osgWidget::Event& /*ev*/) {
        std::cout << "here" << std::endl;

        return false;
    }
};

int main(int, char**)
{
    osgViewer::Viewer viewer;

    // Let's get busy! The WindowManager class is actually an osg::Switch,
    // so you can add it to (ideally) an orthographic camera and have it behave as
    // expected. Note that you create a WindowManager with a NodeMask--it is very important
    // that this be unique for picking to work properly. This also makes it possible to have
    // multiple WindowManagers each operating on their own, unique set of Window objects.
    // The final bool argument is a group of flags that introduce optional functionality
    // for the WindowManager. In our case we include the flags USE_PYTHON and USE_LUA,
    // to demonstrate (and test) their usage. Finally, we pass the temporary WM_NO_BETA_WARN
    // argument, which prevents creating the orange warning window. :) It will be shown
    // in other examples...
    osgWidget::WindowManager* wm = new osgWidget::WindowManager(
        &viewer,
        1280.0f,
        1024.0f,
        MASK_2D,
        osgWidget::WindowManager::WM_USE_LUA |
        osgWidget::WindowManager::WM_USE_PYTHON |
        osgWidget::WindowManager::WM_PICK_DEBUG
    );

    // An actual osgWidget::Window is pure virtual, so we've got to use the osgWidget::Box
    // implementation for now. At a later time, support for Tables and other kinds of
    // advanced layout Window types will be added.
    osgWidget::Window* box = new osgWidget::Box("box", osgWidget::Box::HORIZONTAL);

    // Now we actually attach our two types of callbacks to the box instance. The first
    // uses the simple function signature, the second uses a bound method, passing "this"
    // as the second argument to the Callback constructor.
    // Object obj;

    static std::string data = "lol ur face!";

    /*
    box->addCallback(new osgWidget::Callback(&windowClicked, osgWidget::EVENT_MOUSE_PUSH, &data));
    box->addCallback(new osgWidget::Callback(&windowScrolled, osgWidget::EVENT_MOUSE_SCROLL));
    box->addCallback(osgWidget::Callback(
        &Object::windowClicked,
        &obj,
        osgWidget::EVENT_MOUSE_PUSH
    ));
    */

    box->addCallback(new CallbackObject(osgWidget::EVENT_MOUSE_PUSH));

    // Create some of our "testing" Widgets; included are two Widget subclasses I made
    // during testing which I've kept around for testing purposes. You'll notice
    // that you cannot move the box using the NullWidget, and that the NotifyWidget
    // is a bit verbose. :)
    osgWidget::Widget* widget1 = new osgWidget::NotifyWidget("widget1", 300.0f, 100.0f);
    osgWidget::Widget* widget2 = new osgWidget::NullWidget("widget2", 400.0f, 75.0f);
    osgWidget::Widget* widget3 = new osgWidget::Widget("widget3", 100.0f, 100.0f);
    // Set the colors of widget1 and widget3 to green.
    widget1->setColor(0.0f, 1.0f, 0.0f, 1.0f);
    widget1->setCanFill(true);
    widget3->setColor(0.0f, 1.0f, 0.0f, 1.0f);

    widget1->setImage(osgDB::readRefImageFile("Images/Saturn.TGA"), true);

    // Set the color of widget2, to differentiate it and make it sassy. This is
    // like a poor man's gradient!
    widget2->setColor(0.9f, 0.0f, 0.0f, 0.9f, osgWidget::Widget::LOWER_LEFT);
    widget2->setColor(0.9f, 0.0f, 0.0f, 0.9f, osgWidget::Widget::LOWER_RIGHT);
    widget2->setColor(0.0f, 0.0f, 0.9f, 0.9f, osgWidget::Widget::UPPER_RIGHT);
    widget2->setColor(0.0f, 0.0f, 0.9f, 0.9f, osgWidget::Widget::UPPER_LEFT);

    // Now add our newly created widgets to our box.
    box->addWidget(widget1);
    box->addWidget(widget2);
    box->addWidget(widget3);

    // For maximum efficiency, Windows don't automatically reallocate their geometry
    // and internal positioning every time a widget is added. Thus, we either have to
    // call the WindowManger::resizeAllWindows method or manually call
    // Window::resize when we're ready.
    box->resize();

    // Now, lets clone our existing box and create a new copy of of it, also adding that
    // to the WindowManager. This demonstrates the usages of OSG's ->clone() support,
    // though that is abstracted by our META_UIObject macro.
    osgWidget::Window* boxCopy = osg::clone(box, "newBox", osg::CopyOp::DEEP_COPY_ALL);

    // Move our copy to make it visible.
    boxCopy->setOrigin(0.0f, 125.0f);

    boxCopy->getByName("widget1")->setColor(0.5f, 0.0f, 1.0f, 1.0f);
    boxCopy->getByName("widget3")->setColor(0.5f, 0.0f, 1.0f, 1.0f);

    // Add the successfully created Box (if we get this far) into the WindowManager, so
    // that they can receive events.
    wm->addChild(box);
    wm->addChild(boxCopy);

    // Now, ask our new box to be 100% the width of the WindowManager.
    boxCopy->resizePercent(100.0f, 0.0f);

    // Here we demonstrate the use of osgWidget/io_utils. This is really only useful for
    // debugging at the moment.

    // Setup our OSG objects for our scene; note the use of the utility function
    // createOrthoCamera, which is just a helper for setting up a proper viewing area.
    // An alternative (and a MUCH easier alternative at that!) is to
    // simply use the createParentOrthoCamera method of the WindowManager class,
    // which will wrap the calls to createOrthoCamera and addChild for us! Check out
    // some of the other examples to see this in action...
    osg::ref_ptr<osg::Group>  group  = new osg::Group();
    osg::ref_ptr<osg::Camera> camera = osgWidget::createOrthoCamera(1280.0f, 1024.0f);
    osg::ref_ptr<osg::Node>   model  = osgDB::readRefNodeFile("cow.osgt");

    // Add our event handler; is this better as a MatrixManipulator? Add a few other
    // helpful ViewerEventHandlers.
    viewer.addEventHandler(new osgWidget::MouseHandler(wm));
    viewer.addEventHandler(new osgWidget::KeyboardHandler(wm));
    viewer.addEventHandler(new osgWidget::ResizeHandler(wm, camera.get()));
    viewer.addEventHandler(new osgWidget::CameraSwitchHandler(wm, camera.get()));
    viewer.addEventHandler(new osgViewer::StatsHandler());
    viewer.addEventHandler(new osgViewer::WindowSizeHandler());
    viewer.addEventHandler(new osgGA::StateSetManipulator(
        viewer.getCamera()->getOrCreateStateSet()
    ));

    // Set our first non-UI node to be something other than the mask we created our
    // WindowManager with to avoid picking.
    // TODO: Do I need to create a mechanism for doing this automatically, or should
    // that be the responsibility of the users of osgWidget?
    model->setNodeMask(MASK_3D);

    // Add the WindowManager instance to the 2D camera. This isn't strictly necessary,
    // and you can get some cool results putting the WindowManager directly into a
    // 3D scene. This is not necessary if you use WindowManager::createParentOrthoCamera.
    camera->addChil

    // Add our camera and a testing 3D model to the scene.
    group->addChild(camera);
    group->addChild(model);

    // Here we show how to both run simple strings of code AND run entire files. These
    // assume that you're running the osgwidgetwindow example from the build directory,
    // otherwise you'll need to adjust the file path below in the call to runFile().
    wm->getLuaEngine()->eval("window = osgwidget.newWindow()");
    wm->getLuaEngine()->runFile("osgWidget/osgwidgetwindow.lua");

    wm->getPythonEngine()->eval("import osgwidget");
    wm->getPythonEngine()->runFile("osgWidget/osgwidgetwindow.py");

    viewer.setUpViewInWindow(0, 0, 1280, 1024);
    viewer.setSceneData(group);

    /*
    osgViewer::Viewer::Cameras cameras;
    viewer.getCameras(cameras);
    osg::Camera* c = cameras[0];
    osg::Matrix s = osg::Matrix::scale(1.0f, -1.0f, 1.0f);
    c->setProjectionMatrix(s * c->getProjectionMatrix());
    */

    return viewer.run();
}


bool windowClicked(osgWidget::Event& ev) {
    std::cout << "windowClicked: " << ev.getWindow()->getName() << std::endl;

    if(ev.getData()) {
        std::string* s = static_cast<std::string*>(ev.getData());

        std::cout << "This is data attached to the event: " << *s << std::endl;
    }

    return true;
}

#include <iostream>
#include <osgDB/ReadFile>
#include <osgGA/StateSetManipulator>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgWidget/WindowManager>
#include <osgWidget/ViewerEventHandlers>
#include <osgWidget/Box>

const unsigned int MASK_2D = 0xF0000000;
const unsigned int MASK_3D = 0x0F000000;

// Here we create (and later demonstrate) the use of a simple function callback.

bool windowScrolled(osgWidget::Event& ev) {
    osgWidget::warn()
        << "scrolling up? " << ev.getWindowManager()->isMouseScrollingUp()
        << std::endl
    ;

    return true;
}

// Here we dcreate a new class and show how to use a method callback (which differs from
// a function callback in that we are required to also pass the "this" argument).
struct Object {
    bool windowClicked(osgWidget::Event& ev) {
        std::cout << "Object::windowClicked " << ev.getWindow()->getName() << std::endl;

        return true;
    }
};

// This is the more "traditional" method of creating a callback.
struct CallbackObject: public osgWidget::Callback {
    CallbackObject(osgWidget::EventType evType):
    osgWidget::Callback(evType) {
    }

    virtual bool operator()(osgWidget::Event& /*ev*/) {
        std::cout << "here" << std::endl;

        return false;
    }
};

int main(int, char**)
{
    osgViewer::Viewer viewer;

    // Let's get busy! The WindowManager class is actually an osg::Switch,
    // so you can add it to (ideally) an orthographic camera and have it behave as
    // expected. Note that you create a WindowManager with a NodeMask--it is very important
    // that this be unique for picking to work properly. This also makes it possible to have
    // multiple WindowManagers each operating on their own, unique set of Window objects.
    // The final bool argument is a group of flags that introduce optional functionality
    // for the WindowManager. In our case we include the flags USE_PYTHON and USE_LUA,
    // to demonstrate (and test) their usage. Finally, we pass the temporary WM_NO_BETA_WARN
    // argument, which prevents creating the orange warning window. :) It will be shown
    // in other examples...
    osgWidget::WindowManager* wm = new osgWidget::WindowManager(
        &viewer,
        1280.0f,
        1024.0f,
        MASK_2D,
        osgWidget::WindowManager::WM_USE_LUA |
        osgWidget::WindowManager::WM_USE_PYTHON |
        osgWidget::WindowManager::WM_PICK_DEBUG
    );

    // An actual osgWidget::Window is pure virtual, so we've got to use the osgWidget::Box
    // implementation for now. At a later time, support for Tables and other kinds of
    // advanced layout Window types will be added.
    osgWidget::Window* box = new osgWidget::Box("box", osgWidget::Box::HORIZONTAL);

    // Now we actually attach our two types of callbacks to the box instance. The first
    // uses the simple function signature, the second uses a bound method, passing "this"
    // as the second argument to the Callback constructor.
    // Object obj;

    static std::string data = "lol ur face!";

    /*
    box->addCallback(new osgWidget::Callback(&windowClicked, osgWidget::EVENT_MOUSE_PUSH, &data));
    box->addCallback(new osgWidget::Callback(&windowScrolled, osgWidget::EVENT_MOUSE_SCROLL));
    box->addCallback(osgWidget::Callback(
        &Object::windowClicked,
        &obj,
        osgWidget::EVENT_MOUSE_PUSH
    ));
    */

    box->addCallback(new CallbackObject(osgWidget::EVENT_MOUSE_PUSH));

    // Create some of our "testing" Widgets; included are two Widget subclasses I made
    // during testing which I've kept around for testing purposes. You'll notice
    // that you cannot move the box using the NullWidget, and that the NotifyWidget
    // is a bit verbose. :)
    osgWidget::Widget* widget1 = new osgWidget::NotifyWidget("widget1", 300.0f, 100.0f);
    osgWidget::Widget* widget2 = new osgWidget::NullWidget("widget2", 400.0f, 75.0f);
    osgWidget::Widget* widget3 = new osgWidget::Widget("widget3", 100.0f, 100.0f);
    // Set the colors of widget1 and widget3 to green.
    widget1->setColor(0.0f, 1.0f, 0.0f, 1.0f);
    widget1->setCanFill(true);
    widget3->setColor(0.0f, 1.0f, 0.0f, 1.0f);

    widget1->setImage(osgDB::readRefImageFile("Images/Saturn.TGA"), true);

    // Set the color of widget2, to differentiate it and make it sassy. This is
    // like a poor man's gradient!
    widget2->setColor(0.9f, 0.0f, 0.0f, 0.9f, osgWidget::Widget::LOWER_LEFT);
    widget2->setColor(0.9f, 0.0f, 0.0f, 0.9f, osgWidget::Widget::LOWER_RIGHT);
    widget2->setColor(0.0f, 0.0f, 0.9f, 0.9f, osgWidget::Widget::UPPER_RIGHT);
    widget2->setColor(0.0f, 0.0f, 0.9f, 0.9f, osgWidget::Widget::UPPER_LEFT);

    // Now add our newly created widgets to our box.
    box->addWidget(widget1);
    box->addWidget(widget2);
    box->addWidget(widget3);

    // For maximum efficiency, Windows don't automatically reallocate their geometry
    // and internal positioning every time a widget is added. Thus, we either have to
    // call the WindowManger::resizeAllWindows method or manually call
    // Window::resize when we're ready.
    box->resize();

    // Now, lets clone our existing box and create a new copy of of it, also adding that
    // to the WindowManager. This demonstrates the usages of OSG's ->clone() support,
    // though that is abstracted by our META_UIObject macro.
    osgWidget::Window* boxCopy = osg::clone(box, "newBox", osg::CopyOp::DEEP_COPY_ALL);

    // Move our copy to make it visible.
    boxCopy->setOrigin(0.0f, 125.0f);

    boxCopy->getByName("widget1")->setColor(0.5f, 0.0f, 1.0f, 1.0f);
    boxCopy->getByName("widget3")->setColor(0.5f, 0.0f, 1.0f, 1.0f);

    // Add the successfully created Box (if we get this far) into the WindowManager, so
    // that they can receive events.
    wm->addChild(box);
    wm->addChild(boxCopy);

    // Now, ask our new box to be 100% the width of the WindowManager.
    boxCopy->resizePercent(100.0f, 0.0f);

    // Here we demonstrate the use of osgWidget/io_utils. This is really only useful for
    // debugging at the moment.

    // Setup our OSG objects for our scene; note the use of the utility function
    // createOrthoCamera, which is just a helper for setting up a proper viewing area.
    // An alternative (and a MUCH easier alternative at that!) is to
    // simply use the createParentOrthoCamera method of the WindowManager class,
    // which will wrap the calls to createOrthoCamera and addChild for us! Check out
    // some of the other examples to see this in action...
    osg::ref_ptr<osg::Group>  group  = new osg::Group();
    osg::ref_ptr<osg::Camera> camera = osgWidget::createOrthoCamera(1280.0f, 1024.0f);
    osg::ref_ptr<osg::Node>   model  = osgDB::readRefNodeFile("cow.osgt");

    // Add our event handler; is this better as a MatrixManipulator? Add a few other
    // helpful ViewerEventHandlers.
    viewer.addEventHandler(new osgWidget::MouseHandler(wm));
    viewer.addEventHandler(new osgWidget::KeyboardHandler(wm));
    viewer.addEventHandler(new osgWidget::ResizeHandler(wm, camera.get()));
    viewer.addEventHandler(new osgWidget::CameraSwitchHandler(wm, camera.get()));
    viewer.addEventHandler(new osgViewer::StatsHandler());
    viewer.addEventHandler(new osgViewer::WindowSizeHandler());
    viewer.addEventHandler(new osgGA::StateSetManipulator(
        viewer.getCamera()->getOrCreateStateSet()
    ));

    // Set our first non-UI node to be something other than the mask we created our
    // WindowManager with to avoid picking.
    // TODO: Do I need to create a mechanism for doing this automatically, or should
    // that be the responsibility of the users of osgWidget?
    model->setNodeMask(MASK_3D);

    // Add the WindowManager instance to the 2D camera. This isn't strictly necessary,
    // and you can get some cool results putting the WindowManager directly into a
    // 3D scene. This is not necessary if you use WindowManager::createParentOrthoCamera.
    camera->addChild(wm);

    // Add our camera and a testing 3D model to the scene.
    group->addChild(camera);
    group->addChild(model);

    // Here we show how to both run simple strings of code AND run entire files. These
    // assume that you're running the osgwidgetwindow example from the build directory,
    // otherwise you'll need to adjust the file path below in the call to runFile().
    wm->getLuaEngine()->eval("window = osgwidget.newWindow()");
    wm->getLuaEngine()->runFile("osgWidget/osgwidgetwindow.lua");

    wm->getPythonEngine()->eval("import osgwidget");
    wm->getPythonEngine()->runFile("osgWidget/osgwidgetwindow.py");

    viewer.setUpViewInWindow(0, 0, 1280, 1024);
    viewer.setSceneData(group);

    /*
    osgViewer::Viewer::Cameras cameras;
    viewer.getCameras(cameras);
    osg::Camera* c = cameras[0];
    osg::Matrix s = osg::Matrix::scale(1.0f, -1.0f, 1.0f);
    c->setProjectionMatrix(s * c->getProjectionMatrix());
    */

    return viewer.run();
}


InputTypeSubmit::InputTypeSubmit(ElementFormControlInput* element) : InputType(element)

/*
 * This source file is part of RmlUi, the HTML/CSS Interface Middleware
 *
 * For the latest information, see http://example.com
 *
 *
 *
 */

#include "InputTypeSubmit.h"
#include "../../../Include/RmlUi/Core/Elements/ElementForm.h"
#include "../../../Include/RmlUi/Core/Elements/ElementFormControlInput.h"

namespace Rml {

{
}

InputTypeSubmit::~InputTypeSubmit()
{
}

// Submit buttons are never submitted; they submit themselves if appropriate.
bool InputTypeSubmit::IsSubmitted()
{
	return false;
}

// Checks for necessary functional changes in the control as a result of the event.
void InputTypeSubmit::ProcessDefaultAction(Event& event)
{
	if (event == EventId::Click &&
		!element->IsDisabled())
	{
		Element* parent = element->GetParentNode();
		while (parent)
		{
			ElementForm* form = rmlui_dynamic_cast< ElementForm* >(parent);
			if (form != nullptr)
			{
				form->Submit(element->GetAttribute< String >("name", ""), element->GetAttribute< String >("value", ""));
				return;
			}
			else
			{
				parent = parent->GetParentNode();
			}
		}
	}
}

// Sizes the dimensions to the element's inherent size.
bool InputTypeSubmit::GetIntrinsicDimensions(Vector2f& RMLUI_UNUSED_PARAMETER(dimensions))
{
	RMLUI_UNUSED(dimensions);

	return false;
}

} // namespace Rml


/*
 * This source file is part of RmlUi, the HTML/CSS Interface Middleware
 *
 * For the latest information, see http://example.com
 *
 *
 *
 */

#include "InputTypeSubmit.h"
#include "../../../Include/RmlUi/Core/Elements/ElementForm.h"
#include "../../../Include/RmlUi/Core/Elements/ElementFormControlInput.h"

namespace Rml {

InputTypeSubmit::InputTypeSubmit(ElementFormControlInput* element) : InputType(element)

InputTypeSubmit::~InputTypeSubmit()
{
}

// Submit buttons are never submitted; they submit themselves if appropriate.
bool InputTypeSubmit::IsSubmitted()
{
	return false;
}

// Checks for necessary functional changes in the control as a result of the event.
void InputTypeSubmit::ProcessDefaultAction(Event& event)
{
	if (event == EventId::Click &&
		!element->IsDisabled())
	{
		Element* parent = element->GetParentNode();
		while (parent)
		{
			ElementForm* form = rmlui_dynamic_cast< ElementForm* >(parent);
			if (form != nullptr)
			{
				form->Submit(element->GetAttribute< String >("name", ""), element->GetAttribute< String >("value", ""));
				return;
			}
			else
			{
				parent = parent->GetParentNode();
			}
		}
	}
}

// Sizes the dimensions to the element's inherent size.
bool InputTypeSubmit::GetIntrinsicDimensions(Vector2f& RMLUI_UNUSED_PARAMETER(dimensions))
{
	RMLUI_UNUSED(dimensions);

	return false;
}

} // namespace Rml


/*
 * This source file is part of RmlUi, the HTML/CSS Interface Middleware
 *
 * For the latest information, see http://example.com
 *
 *
 *
 */

#include "InputTypeSubmit.h"
#include "../../../Include/RmlUi/Core/Elements/ElementForm.h"
#include "../../../Include/RmlUi/Core/Elements/ElementFormControlInput.h"

namespace Rml {

InputTypeSubmit::InputTypeSubmit(ElementFormControlInput* element) : InputType(element)
{
}

InputTypeSubmit::~InputTypeSubmit()
{
}

// Submit buttons are never submitted; they submit themselves if appropriate.
bool InputTypeSubmit::IsSubmitted()
{

}

// Checks for necessary functional changes in the control as a result of the event.
void InputTypeSubmit::ProcessDefaultAction(Event& event)
{
	if (event == EventId::Click &&
		!element->IsDisabled())
	{
		Element* parent = element->GetParentNode();
		while (parent)
		{
			ElementForm* form = rmlui_dynamic_cast< ElementForm* >(parent);
			if (form != nullptr)
			{
				form->Submit(element->GetAttribute< String >("name", ""), element->GetAttribute< String >("value", ""));
				return;
			}
			else
			{
				parent = parent->GetParentNode();
			}
		}
	}
}

// Sizes the dimensions to the element's inherent size.
bool InputTypeSubmit::GetIntrinsicDimensions(Vector2f& RMLUI_UNUSED_PARAMETER(dimensions))
{
	RMLUI_UNUSED(dimensions);

	return false;
}

} // namespace Rml


bool InputTypeSubmit::GetIntrinsicDimensions(Vector2f& RMLUI_UNUSED_PARAMETER(dimensions))
{
	RMLUI_UNUSED(dimensions);

	return false;
}

/*
 * This source file is part of RmlUi, the HTML/CSS Interface Middleware
 *
 * For the latest information, see http://example.com
 *
 *
 *
 */

#include "InputTypeSubmit.h"
#include "../../../Include/RmlUi/Core/Elements/ElementForm.h"
#include "../../../Include/RmlUi/Core/Elements/ElementFormControlInput.h"

namespace Rml {

InputTypeSubmit::InputTypeSubmit(ElementFormControlInput* element) : InputType(element)
{
}

InputTypeSubmit::~InputTypeSubmit()
{
}

// Submit buttons are never submitted; they submit themselves if appropriate.
bool InputTypeSubmit::IsSubmitted()
{
	return false;
}

// Checks for necessary functional changes in the control as a result of the event.
void InputTypeSubmit::ProcessDefaultAction(Event& event)
{
	if (event == EventId::Click &&
		!element->IsDisabled())
	{
		Element* parent = element->GetParentNode();
		while (parent)
		{
			ElementForm* form = rmlui_dynamic_cast< ElementForm* >(parent);
			if (form != nullptr)
			{
				form->Submit(element->GetAttribute< String >("name", ""), element->GetAttribute< String >("value", ""));
				return;
			}
			else
			{
				parent = parent->GetParentNode();
			}
		}
	}
}

// Sizes the dimensions to the element's inherent size.


while (parent)
		{
			ElementForm* form = rmlui_dynamic_cast< ElementForm* >(parent);
			if (form != nullptr)
			{
				form->Submit(element->GetAttribute< String >("name", ""), element->GetAttribute< String >("value", ""));
				return;
			}
			else
			{
				parent = parent->GetParentNode();
			}
		}

/*
 * This source file is part of RmlUi, the HTML/CSS Interface Middleware
 *
 * For the latest information, see http://example.com
 *
 *
 *
 */

#include "InputTypeSubmit.h"
#include "../../../Include/RmlUi/Core/Elements/ElementForm.h"
#include "../../../Include/RmlUi/Core/Elements/ElementFormControlInput.h"

namespace Rml {

InputTypeSubmit::InputTypeSubmit(ElementFormControlInput* element) : InputType(element)
{
}

InputTypeSubmit::~InputTypeSubmit()
{
}

// Submit buttons are never submitted; they submit themselves if appropriate.
bool InputTypeSubmit::IsSubmitted()
{
	return false;
}

// Checks for necessary functional changes in the control as a result of the event.
void InputTypeSubmit::ProcessDefaultAction(Event& event)
{
	if (event == EventId::Click &&
		!element->IsDisabled())
	{
		Element* parent = element->GetParentNode();

	}
}

// Sizes the dimensions to the element's inherent size.
bool InputTypeSubmit::GetIntrinsicDimensions(Vector2f& RMLUI_UNUSED_PARAMETER(dimensions))
{
	RMLUI_UNUSED(dimensions);

	return false;
}

} // namespace Rml


void SpeedsFile::Save(const std::string& speedBinPath, SpeedsFile& speedFile)

#include "SpeedsFile.h"

using namespace LibOpenNFS::NFS3;

bool SpeedsFile::Load(const std::string& speedBinPath, SpeedsFile& speedFile)
{
    LOG(INFO) << "Loading FRD File located at " << speedBinPath;
    std::ifstream speedBin(speedBinPath, std::ios::in | std::ios::binary);

    bool loadStatus = speedFile._SerializeIn(speedBin);
    speedBin.close();

    return loadStatus;
}

{
    LOG(INFO) << "Saving SPEED BIN File to " << speedBinPath;
    std::ofstream speedBin(speedBinPath, std::ios::out | std::ios::binary);
    speedFile._SerializeOut(speedBin);
}

bool SpeedsFile::_SerializeIn(std::ifstream& ifstream)
{
    // Tactical grab of the file size
    ifstream.ignore(std::numeric_limits<std::streamsize>::max());
    m_uFileSize = ifstream.gcount();
    ifstream.clear();
    ifstream.seekg(0, std::ios_base::beg);

    speeds.resize(m_uFileSize);
    SAFE_READ(ifstream, speeds.data(), m_uFileSize);

    return true;
}

void SpeedsFile::_SerializeOut(std::ofstream& ofstream)
{
    ofstream.write((char*) speeds.data(), m_uFileSize);
    ofstream.close();
}

void SpeedsFile::SaveCSV(const std::string& speedsCsvPath, SpeedsFile& speedFile)
{
    LOG(INFO) << "Saving SPEED BIN File to CSV: " << speedsCsvPath;
    std::ofstream speedCsv(speedsCsvPath, std::ios::out | std::ios::binary);

    for (auto& speed : speedFile.speeds)
    {
        speedCsv << static_cast<uint16_t>(speed) << "," << std::endl;
    }

    speedCsv.close();
}


{
    ofstream.write((char*) speeds.data(), m_uFileSize);
    ofstream.close();
}

#include "SpeedsFile.h"

using namespace LibOpenNFS::NFS3;

bool SpeedsFile::Load(const std::string& speedBinPath, SpeedsFile& speedFile)
{
    LOG(INFO) << "Loading FRD File located at " << speedBinPath;
    std::ifstream speedBin(speedBinPath, std::ios::in | std::ios::binary);

    bool loadStatus = speedFile._SerializeIn(speedBin);
    speedBin.close();

    return loadStatus;
}

void SpeedsFile::Save(const std::string& speedBinPath, SpeedsFile& speedFile)
{
    LOG(INFO) << "Saving SPEED BIN File to " << speedBinPath;
    std::ofstream speedBin(speedBinPath, std::ios::out | std::ios::binary);
    speedFile._SerializeOut(speedBin);
}

bool SpeedsFile::_SerializeIn(std::ifstream& ifstream)
{
    // Tactical grab of the file size
    ifstream.ignore(std::numeric_limits<std::streamsize>::max());
    m_uFileSize = ifstream.gcount();
    ifstream.clear();
    ifstream.seekg(0, std::ios_base::beg);

    speeds.resize(m_uFileSize);
    SAFE_READ(ifstream, speeds.data(), m_uFileSize);

    return true;
}

void SpeedsFile::_SerializeOut(std::ofstream& ofstream)

void SpeedsFile::SaveCSV(const std::string& speedsCsvPath, SpeedsFile& speedFile)
{
    LOG(INFO) << "Saving SPEED BIN File to CSV: " << speedsCsvPath;
    std::ofstream speedCsv(speedsCsvPath, std::ios::out | std::ios::binary);

    for (auto& speed : speedFile.speeds)
    {
        speedCsv << static_cast<uint16_t>(speed) << "," << std::endl;
    }

    speedCsv.close();
}


edsCsvPath, std::ios::out | std::ios::binary);

#include "SpeedsFile.h"

using namespace LibOpenNFS::NFS3;

bool SpeedsFile::Load(const std::string& speedBinPath, SpeedsFile& speedFile)
{
    LOG(INFO) << "Loading FRD File located at " << speedBinPath;
    std::ifstream speedBin(speedBinPath, std::ios::in | std::ios::binary);

    bool loadStatus = speedFile._SerializeIn(speedBin);
    speedBin.close();

    return loadStatus;
}

void SpeedsFile::Save(const std::string& speedBinPath, SpeedsFile& speedFile)
{
    LOG(INFO) << "Saving SPEED BIN File to " << speedBinPath;
    std::ofstream speedBin(speedBinPath, std::ios::out | std::ios::binary);
    speedFile._SerializeOut(speedBin);
}

bool SpeedsFile::_SerializeIn(std::ifstream& ifstream)
{
    // Tactical grab of the file size
    ifstream.ignore(std::numeric_limits<std::streamsize>::max());
    m_uFileSize = ifstream.gcount();
    ifstream.clear();
    ifstream.seekg(0, std::ios_base::beg);

    speeds.resize(m_uFileSize);
    SAFE_READ(ifstream, speeds.data(), m_uFileSize);

    return true;
}

void SpeedsFile::_SerializeOut(std::ofstream& ofstream)
{
    ofstream.write((char*) speeds.data(), m_uFileSize);
    ofstream.close();
}

void SpeedsFile::SaveCSV(const std::string& speedsCsvPath, SpeedsFile& speedFile)
{
    LOG(INFO) << "Saving SPEED BIN File to CSV: " << speedsCsvPath;
    std::ofstream speedCsv(spe

    for (auto& speed : speedFile.speeds)
    {
        speedCsv << static_cast<uint16_t>(speed) << "," << std::endl;
    }

    speedCsv.close();
}


sakura::graphics::webgpu::GPUBuffer::GPUBuffer(const GpuBufferHandle handle,
	const webgpu::RenderDevice& dev, const BufferDescriptor& desc) noexcept
	:desc_(desc), handle_(handle)

{
	WGPUBufferDescriptor buffDesc = {};
	buffDesc.usage = translate(desc.usages, desc.access);
	buffDesc.size = desc_.length;
	buffer = wgpuDeviceCreateBuffer(dev.device, &buffDesc);
	if(desc.data)
	{
		wgpuQueueWriteBuffer(
			dev.default_queue, buffer, 0, desc.data, desc.length);
	}
}

sakura::graphics::webgpu::GPUBuffer::~GPUBuffer()
{
	if(buffer)
	{
		wgpuBufferDestroy(buffer);
		wgpuBufferRelease(buffer);
	}
}

sakura::graphics::RenderResourceHandle sakura::graphics::webgpu::GPUBuffer::handle() const
{
	return handle_;
}

size_t sakura::graphics::webgpu::GPUBuffer::size() const
{
	return desc_.length;
}

sakura::graphics::BufferUsages sakura::graphics::webgpu::GPUBuffer::usages() const
{
	return desc_.usages;
}


{
	if(buffer)
	{
		wgpuBufferDestroy(buffer);
		wgpuBufferRelease(buffer);
	}
}

#include <RenderGraphWebGPU/RenderGraphWebGPU.h>

sakura::graphics::webgpu::GPUBuffer::GPUBuffer(const GpuBufferHandle handle,
	const webgpu::RenderDevice& dev, const BufferDescriptor& desc) noexcept
	:desc_(desc), handle_(handle)
{
	WGPUBufferDescriptor buffDesc = {};
	buffDesc.usage = translate(desc.usages, desc.access);
	buffDesc.size = desc_.length;
	buffer = wgpuDeviceCreateBuffer(dev.device, &buffDesc);
	if(desc.data)
	{
		wgpuQueueWriteBuffer(
			dev.default_queue, buffer, 0, desc.data, desc.length);
	}
}

sakura::graphics::webgpu::GPUBuffer::~GPUBuffer()

sakura::graphics::RenderResourceHandle sakura::graphics::webgpu::GPUBuffer::handle() const
{
	return handle_;
}

size_t sakura::graphics::webgpu::GPUBuffer::size() const
{
	return desc_.length;
}

sakura::graphics::BufferUsages sakura::graphics::webgpu::GPUBuffer::usages() const
{
	return desc_.usages;
}


#include <RenderGraphWebGPU/RenderGraphWebGPU.h>

sakura::graphics::webgpu::GPUBuffer::GPUBuffer(const GpuBufferHandle handle,
	const webgpu::RenderDevice& dev, const BufferDescriptor& desc) noexcept
	:desc_(desc), handle_(handle)
{
	WGPUBufferDescriptor buffDesc = {};
	buffDesc.usage = translate(desc.usages, desc.access);
	buffDesc.size = desc_.length;
	buffer = wgpuDevic

	if(desc.data)
	{
		wgpuQueueWriteBuffer(
			dev.default_queue, buffer, 0, desc.data, desc.length);
	}
}

sakura::graphics::webgpu::GPUBuffer::~GPUBuffer()
{
	if(buffer)
	{
		wgpuBufferDestroy(buffer);
		wgpuBufferRelease(buffer);
	}
}

sakura::graphics::RenderResourceHandle sakura::graphics::webgpu::GPUBuffer::handle() const
{
	return handle_;
}

size_t sakura::graphics::webgpu::GPUBuffer::size() const
{
	return desc_.length;
}

sakura::graphics::BufferUsages sakura::graphics::webgpu::GPUBuffer::usages() const
{
	return desc_.usages;
}


static StringRef getModuleNameFromComponent(
    const std::pair<std::string, SourceLocation> &IdComponent)

//===- Module.cpp - Describe a module -------------------------------------===//
// This file defines the Module class, which describes a module in the source

#include "clang/Basic/Module.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/TargetInfo.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <functional>
#include <string>
#include <utility>
#include <vector>

using namespace clang;

Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
               bool IsFramework, bool IsExplicit, unsigned VisibilityID)
    : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent),
      Directory(), Umbrella(), ASTFile(nullptr),
      VisibilityID(VisibilityID), IsUnimportable(false),
      HasIncompatibleModuleFile(false), IsAvailable(true),
      IsFromModuleFile(false), IsFramework(IsFramework), IsExplicit(IsExplicit),
      IsSystem(false), IsExternC(false), IsInferred(false),
      InferSubmodules(false), InferExplicitSubmodules(false),
      InferExportWildcard(false), ConfigMacrosExhaustive(false),
      NoUndeclaredIncludes(false), ModuleMapIsPrivate(false),

      // SWIFT-SPECIFIC FIELDS HERE. Handling them separately helps avoid merge
      IsSwiftInferImportAsMember(false),

      HasUmbrellaDir(false), NameVisibility(Hidden) {
  if (Parent) {
    IsAvailable = Parent->isAvailable();
    IsUnimportable = Parent->isUnimportable();
    IsSystem = Parent->IsSystem;
    IsExternC = Parent->IsExternC;
    NoUndeclaredIncludes = Parent->NoUndeclaredIncludes;
    ModuleMapIsPrivate = Parent->ModuleMapIsPrivate;

    Parent->SubModuleIndex[Name] = Parent->SubModules.size();
    Parent->SubModules.push_back(this);
  }
}

Module::~Module() {
  for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
       I != IEnd; ++I) {
    delete *I;
  }
}

static bool isPlatformEnvironment(const TargetInfo &Target, StringRef Feature) {
  StringRef Platform = Target.getPlatformName();
  StringRef Env = Target.getTriple().getEnvironmentName();

  // Attempt to match platform and environment.
  if (Platform == Feature || Target.getTriple().getOSName() == Feature ||
      Env == Feature)
    return true;

  auto CmpPlatformEnv = [](StringRef LHS, StringRef RHS) {
    auto Pos = LHS.find("-");
    if (Pos == StringRef::npos)
      return false;
    SmallString<128> NewLHS = LHS.slice(0, Pos);
    NewLHS += LHS.slice(Pos+1, LHS.size());
    return NewLHS == RHS;
  };

  SmallString<128> PlatformEnv = Target.getTriple().getOSAndEnvironmentName();
  // Darwin has different but equivalent variants for simulators, example:
  // where both are valid examples of the same platform+environment but in the
  // variant (2) the simulator is hardcoded as part of the platform name. Both
  // forms above should match for "iossimulator" requirement.
  if (Target.getTriple().isOSDarwin() && PlatformEnv.endswith("simulator"))
    return PlatformEnv == Feature || CmpPlatformEnv(PlatformEnv, Feature);

  return PlatformEnv == Feature;
}

/// Determine whether a translation unit built using the current
/// language options has the given feature.
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
                       const TargetInfo &Target) {
  bool HasFeature = llvm::StringSwitch<bool>(Feature)
                        .Case("altivec", LangOpts.AltiVec)
                        .Case("blocks", LangOpts.Blocks)
                        .Case("coroutines", LangOpts.Coroutines)
                        .Case("cplusplus", LangOpts.CPlusPlus)
                        .Case("cplusplus11", LangOpts.CPlusPlus11)
                        .Case("cplusplus14", LangOpts.CPlusPlus14)
                        .Case("cplusplus17", LangOpts.CPlusPlus17)
                        .Case("c99", LangOpts.C99)
                        .Case("c11", LangOpts.C11)
                        .Case("c17", LangOpts.C17)
                        .Case("freestanding", LangOpts.Freestanding)
                        .Case("gnuinlineasm", LangOpts.GNUAsm)
                        .Case("objc", LangOpts.ObjC)
                        .Case("objc_arc", LangOpts.ObjCAutoRefCount)
                        .Case("opencl", LangOpts.OpenCL)
                        .Case("tls", Target.isTLSSupported())
                        .Case("zvector", LangOpts.ZVector)
                        .Default(Target.hasFeature(Feature) ||
                                 isPlatformEnvironment(Target, Feature));
  if (!HasFeature)
    HasFeature = std::find(LangOpts.ModuleFeatures.begin(),
                           LangOpts.ModuleFeatures.end(),
                           Feature) != LangOpts.ModuleFeatures.end();
  return HasFeature;
}

bool Module::isUnimportable(const LangOptions &LangOpts,
                            const TargetInfo &Target, Requirement &Req,
                            Module *&ShadowingModule) const {
  if (!IsUnimportable)
    return false;

  for (const Module *Current = this; Current; Current = Current->Parent) {
    if (Current->ShadowingModule) {
      ShadowingModule = Current->ShadowingModule;
      return true;
    }
    for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
      if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
              Current->Requirements[I].second) {
        Req = Current->Requirements[I];
        return true;
      }
    }
  }

  llvm_unreachable("could not find a reason why module is unimportable");
}

bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
                         Requirement &Req,
                         UnresolvedHeaderDirective &MissingHeader,
                         Module *&ShadowingModule) const {
  if (IsAvailable)
    return true;

  if (isUnimportable(LangOpts, Target, Req, ShadowingModule))
    return false;

  // FIXME: All missing headers are listed on the top-level module. Should we
  // just look there?
  for (const Module *Current = this; Current; Current = Current->Parent) {
    if (!Current->MissingHeaders.empty()) {
      MissingHeader = Current->MissingHeaders.front();
      return false;
    }
  }

  llvm_unreachable("could not find a reason why module is unavailable");
}

bool Module::isSubModuleOf(const Module *Other) const {
  const Module *This = this;
  do {
    if (This == Other)
      return true;

    This = This->Parent;
  } while (This);

  return false;
}

const Module *Module::getTopLevelModule() const {
  const Module *Result = this;
  while (Result->Parent)
    Result = Result->Parent;

  return Result;
}

{
  return IdComponent.first;
}

static StringRef getModuleNameFromComponent(StringRef R) { return R; }

template<typename InputIter>
static void printModuleId(raw_ostream &OS, InputIter Begin, InputIter End,
                          bool AllowStringLiterals = true) {
  for (InputIter It = Begin; It != End; ++It) {
    if (It != Begin)
      OS << ".";

    StringRef Name = getModuleNameFromComponent(*It);
    if (!AllowStringLiterals || isValidIdentifier(Name))
      OS << Name;
    else {
      OS << '"';
      OS.write_escaped(Name);
      OS << '"';
    }
  }
}

template<typename Container>
static void printModuleId(raw_ostream &OS, const Container &C) {
  return printModuleId(OS, C.begin(), C.end());
}

std::string Module::getFullModuleName(bool AllowStringLiterals) const {
  SmallVector<StringRef, 2> Names;

  // Build up the set of module names (from innermost to outermost).
  for (const Module *M = this; M; M = M->Parent)
    Names.push_back(M->Name);

  std::string Result;

  llvm::raw_string_ostream Out(Result);
  printModuleId(Out, Names.rbegin(), Names.rend(), AllowStringLiterals);
  Out.flush();

  return Result;
}

bool Module::fullModuleNameIs(ArrayRef<StringRef> nameParts) const {
  for (const Module *M = this; M; M = M->Parent) {
    if (nameParts.empty() || M->Name != nameParts.back())
      return false;
    nameParts = nameParts.drop_back();
  }
  return nameParts.empty();
}

Module::DirectoryName Module::getUmbrellaDir() const {
  if (Header U = getUmbrellaHeader())
    return {"", "", U.Entry->getDir()};

  return {UmbrellaAsWritten, UmbrellaRelativeToRootModuleDirectory,
          static_cast<const DirectoryEntry *>(Umbrella)};
}

void Module::addTopHeader(const FileEntry *File) {
  assert(File);
  TopHeaders.insert(File);
}

ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
  if (!TopHeaderNames.empty()) {
    for (std::vector<std::string>::iterator
           I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
      if (auto FE = FileMgr.getFile(*I))
        TopHeaders.insert(*FE);
    }
    TopHeaderNames.clear();
  }

  return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
}

bool Module::directlyUses(const Module *Requested) const {
  auto *Top = getTopLevelModule();

  // A top-level module implicitly uses itself.
  if (Requested->isSubModuleOf(Top))
    return true;

  for (auto *Use : Top->DirectUses)
    if (Requested->isSubModuleOf(Use))
      return true;

  // Anyone is allowed to use our builtin stddef.h and its accompanying module.
  if (!Requested->Parent && Requested->Name == "_Builtin_stddef_max_align_t")
    return true;

  return false;
}

void Module::addRequirement(StringRef Feature, bool RequiredState,
                            const LangOptions &LangOpts,
                            const TargetInfo &Target) {
  Requirements.push_back(Requirement(std::string(Feature), RequiredState));

  // If this feature is currently available, we're done.
  if (hasFeature(Feature, LangOpts, Target) == RequiredState)
    return;

  markUnavailable(/*Unimportable*/true);
}

void Module::markUnavailable(bool Unimportable) {
  auto needUpdate = [Unimportable](Module *M) {
    return M->IsAvailable || (!M->IsUnimportable && Unimportable);
  };

  if (!needUpdate(this))
    return;

  SmallVector<Module *, 2> Stack;
  Stack.push_back(this);
  while (!Stack.empty()) {
    Module *Current = Stack.back();
    Stack.pop_back();

    if (!needUpdate(Current))
      continue;

    Current->IsAvailable = false;
    Current->IsUnimportable |= Unimportable;
    for (submodule_iterator Sub = Current->submodule_begin(),
                         SubEnd = Current->submodule_end();
         Sub != SubEnd; ++Sub) {
      if (needUpdate(*Sub))
        Stack.push_back(*Sub);
    }
  }
}

Module *Module::findSubmodule(StringRef Name) const {
  llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
  if (Pos == SubModuleIndex.end())
    return nullptr;

  return SubModules[Pos->getValue()];
}

Module *Module::findOrInferSubmodule(StringRef Name) {
  llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
  if (Pos != SubModuleIndex.end())
    return SubModules[Pos->getValue()];
  if (!InferSubmodules)
    return nullptr;
  Module *Result = new Module(Name, SourceLocation(), this, false, InferExplicitSubmodules, 0);
  Result->InferExplicitSubmodules = InferExplicitSubmodules;
  Result->InferSubmodules = InferSubmodules;
  Result->InferExportWildcard = InferExportWildcard;
  if (Result->InferExportWildcard)
    Result->Exports.push_back(Module::ExportDecl(nullptr, true));
  return Result;
}

void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
  // All non-explicit submodules are exported.
  for (std::vector<Module *>::const_iterator I = SubModules.begin(),
                                             E = SubModules.end();
       I != E; ++I) {
    Module *Mod = *I;
    if (!Mod->IsExplicit)
      Exported.push_back(Mod);
  }

  // Find re-exported modules by filtering the list of imported modules.
  bool AnyWildcard = false;
  bool UnrestrictedWildcard = false;
  SmallVector<Module *, 4> WildcardRestrictions;
  for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
    Module *Mod = Exports[I].getPointer();
    if (!Exports[I].getInt()) {
      // Export a named module directly; no wildcards involved.
      Exported.push_back(Mod);

      continue;
    }

    // Wildcard export: export all of the imported modules that match
    // the given pattern.
    AnyWildcard = true;
    if (UnrestrictedWildcard)
      continue;

    if (Module *Restriction = Exports[I].getPointer())
      WildcardRestrictions.push_back(Restriction);
    else {
      WildcardRestrictions.clear();
      UnrestrictedWildcard = true;
    }
  }

  // If there were any wildcards, push any imported modules that were
  // re-exported by the wildcard restriction.
  if (!AnyWildcard)
    return;

  for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
    Module *Mod = Imports[I];
    bool Acceptable = UnrestrictedWildcard;
    if (!Acceptable) {
      // Check whether this module meets one of the restrictions.
      for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
        Module *Restriction = WildcardRestrictions[R];
        if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
          Acceptable = true;
          break;
        }
      }
    }

    if (!Acceptable)
      continue;

    Exported.push_back(Mod);
  }
}

void Module::buildVisibleModulesCache() const {
  assert(VisibleModulesCache.empty() && "cache does not need building");

  // This module is visible to itself.
  VisibleModulesCache.insert(this);

  // Every imported module is visible.
  SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
  while (!Stack.empty()) {
    Module *CurrModule = Stack.pop_back_val();

    // Every module transitively exported by an imported module is visible.
    if (VisibleModulesCache.insert(CurrModule).second)
      CurrModule->getExportedModules(Stack);
  }
}

void Module::print(raw_ostream &OS, unsigned Indent) const {
  OS.indent(Indent);
  if (IsFramework)
    OS << "framework ";
  if (IsExplicit)
    OS << "explicit ";
  OS << "module ";
  printModuleId(OS, &Name, &Name + 1);

  if (IsSystem || IsExternC) {
    OS.indent(Indent + 2);
    if (IsSystem)
      OS << " [system]";
    if (IsExternC)
      OS << " [extern_c]";
    if (IsSwiftInferImportAsMember)
      OS << " [swift_infer_import_as_member]";
  }

  OS << " {\n";

  if (!Requirements.empty()) {
    OS.indent(Indent + 2);
    OS << "requires ";
    for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
      if (I)
        OS << ", ";
      if (!Requirements[I].second)
        OS << "!";
      OS << Requirements[I].first;
    }
    OS << "\n";
  }

  if (Header H = getUmbrellaHeader()) {
    OS.indent(Indent + 2);
    OS << "umbrella header \"";
    OS.write_escaped(H.NameAsWritten);
    OS << "\"\n";
  } else if (DirectoryName D = getUmbrellaDir()) {
    OS.indent(Indent + 2);
    OS << "umbrella \"";
    OS.write_escaped(D.NameAsWritten);
    OS << "\"\n";
  }

  if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
    OS.indent(Indent + 2);
    OS << "config_macros ";
    if (ConfigMacrosExhaustive)
      OS << "[exhaustive]";
    for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
      if (I)
        OS << ", ";
      OS << ConfigMacros[I];
    }
    OS << "\n";
  }

  struct {
    StringRef Prefix;
    HeaderKind Kind;
  } Kinds[] = {{"", HK_Normal},
               {"textual ", HK_Textual},
               {"private ", HK_Private},
               {"private textual ", HK_PrivateTextual},
               {"exclude ", HK_Excluded}};

  for (auto &K : Kinds) {
    assert(&K == &Kinds[K.Kind] && "kinds in wrong order");
    for (auto &H : Headers[K.Kind]) {
      OS.indent(Indent + 2);
      OS << K.Prefix << "header \"";
      OS.write_escaped(H.NameAsWritten);
      OS << "\" { size " << H.Entry->getSize()
         << " mtime " << H.Entry->getModificationTime() << " }\n";
    }
  }
  for (auto *Unresolved : {&UnresolvedHeaders, &MissingHeaders}) {
    for (auto &U : *Unresolved) {
      OS.indent(Indent + 2);
      OS << Kinds[U.Kind].Prefix << "header \"";
      OS.write_escaped(U.FileName);
      OS << "\"";
      if (U.Size || U.ModTime) {
        OS << " {";
        if (U.Size)
          OS << " size " << *U.Size;
        if (U.ModTime)
          OS << " mtime " << *U.ModTime;
        OS << " }";
      }
      OS << "\n";
    }
  }

  if (!ExportAsModule.empty()) {
    OS.indent(Indent + 2);
    OS << "export_as" << ExportAsModule << "\n";
  }

  for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
       MI != MIEnd; ++MI)
    // Print inferred subframework modules so that we don't need to re-infer
    // them (requires expensive directory iteration + stat calls) when we build
    // the module. Regular inferred submodules are OK, as we need to look at all
    // those header files anyway.
    if (!(*MI)->IsInferred || (*MI)->IsFramework)
      (*MI)->print(OS, Indent + 2);

  for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
    OS.indent(Indent + 2);
    OS << "export ";
    if (Module *Restriction = Exports[I].getPointer()) {
      OS << Restriction->getFullModuleName(true);
      if (Exports[I].getInt())
        OS << ".*";
    } else {
      OS << "*";
    }
    OS << "\n";
  }

  for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
    OS.indent(Indent + 2);
    OS << "export ";
    printModuleId(OS, UnresolvedExports[I].Id);
    if (UnresolvedExports[I].Wildcard)
      OS << (UnresolvedExports[I].Id.empty() ? "*" : ".*");
    OS << "\n";
  }

  for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
    OS.indent(Indent + 2);
    OS << "use ";
    OS << DirectUses[I]->getFullModuleName(true);
    OS << "\n";
  }

  for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
    OS.indent(Indent + 2);
    OS << "use ";
    printModuleId(OS, UnresolvedDirectUses[I]);
    OS << "\n";
  }

  for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
    OS.indent(Indent + 2);
    OS << "link ";
    if (LinkLibraries[I].IsFramework)
      OS << "framework ";
    OS << "\"";
    OS.write_escaped(LinkLibraries[I].Library);
    OS << "\"";
  }

  for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
    OS.indent(Indent + 2);
    OS << "conflict ";
    printModuleId(OS, UnresolvedConflicts[I].Id);
    OS << ", \"";
    OS.write_escaped(UnresolvedConflicts[I].Message);
    OS << "\"\n";
  }

  for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
    OS.indent(Indent + 2);
    OS << "conflict ";
    OS << Conflicts[I].Other->getFullModuleName(true);
    OS << ", \"";
    OS.write_escaped(Conflicts[I].Message);
    OS << "\"\n";
  }

  if (InferSubmodules) {
    OS.indent(Indent + 2);
    if (InferExplicitSubmodules)
      OS << "explicit ";
    OS << "module * {\n";
    if (InferExportWildcard) {
      OS.indent(Indent + 4);
      OS << "export *\n";
    }
    OS.indent(Indent + 2);
    OS << "}\n";
  }

  OS.indent(Indent);
  OS << "}\n";
}

LLVM_DUMP_METHOD void Module::dump() const {
  print(llvm::errs());
}

void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
                                  VisibleCallback Vis, ConflictCallback Cb) {
  assert(Loc.isValid() && "setVisible expects a valid import location");
  if (isVisible(M))
    return;

  ++Generation;

  struct Visiting {
    Module *M;
    Visiting *ExportedBy;
  };

  std::function<void(Visiting)> VisitModule = [&](Visiting V) {
    // Nothing to do for a module that's already visible.
    unsigned ID = V.M->getVisibilityID();
    if (ImportLocs.size() <= ID)
      ImportLocs.resize(ID + 1);
    else if (ImportLocs[ID].isValid())
      return;

    ImportLocs[ID] = Loc;
    Vis(M);

    // Make any exported modules visible.
    SmallVector<Module *, 16> Exports;
    V.M->getExportedModules(Exports);
    for (Module *E : Exports) {
      if (!E->isUnimportable())
        VisitModule({E, &V});
    }

    for (auto &C : V.M->Conflicts) {
      if (isVisible(C.Other)) {
        llvm::SmallVector<Module*, 8> Path;
        for (Visiting *I = &V; I; I = I->ExportedBy)
          Path.push_back(I->M);
        Cb(Path, C.Other, C.Message);
      }
    }
  };
  VisitModule({M, nullptr});
}

ASTSourceDescriptor::ASTSourceDescriptor(Module &M)
    : Signature(M.Signature), ClangModule(&M) {
  if (M.Directory)
    Path = M.Directory->getName();
  if (auto *File = M.getASTFile())
    ASTFile = File->getName();
}

std::string ASTSourceDescriptor::getModuleName() const {
  if (ClangModule)
    return ClangModule->Name;
  else
    return std::string(PCHModuleName);
}