<commit_before>//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************

//
// FacebookDialog.xaml.cpp
// Implementation of the FacebookDialog class
//

#include "pch.h"
#include "FacebookDialog.xaml.h"
#include "FacebookSession.h"
#include "FacebookFeedRequest.h"

using namespace Platform;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Popups;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Facebook;
using namespace Facebook::Graph;

#if (defined(_MSC_VER) && (_MSC_VER >= 1800))
using namespace concurrency;
#else
using namespace pplx;
#endif

using namespace std;

void DebugSpew(
    String^ msg
    )
{
    String^ output = msg + L"\n";
    OutputDebugString(output->Data());
}

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
namespace Facebook
{
    FacebookDialog::FacebookDialog()
    {
        InitializeComponent();
        _popup = nullptr;
        _dialogResponse = nullptr;

        CoreWindow^ wnd1 = CoreApplication::MainView->CoreWindow;

        _grid = ref new Grid();
        _popup = ref new Popup();

        _popup->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Stretch;
        _popup->VerticalAlignment = Windows::UI::Xaml::VerticalAlignment::Stretch;

        // TODO: (sanjeevd) hard coded, remove and fix these
        _grid->Margin = Windows::UI::Xaml::Thickness(0, 0, 0, 0);
        _grid->Height = wnd1->Bounds.Height;
        _grid->Width = wnd1->Bounds.Width;

        Width = _grid->Width;

        _grid->Children->Append(this);
        _popup->Child = _grid;
    }

    extern HANDLE login_evt;

    FBResult^ FacebookDialog::DialogResponse::get()
    {
        FBResult^ response = _dialogResponse;
        if (response)
        {
            // Caller (FBSession) only gets the response *once*.  Then we reset
            // it to null, so it's valid to poll on the value being null again.
            _dialogResponse = nullptr;
        }

        return response;
    }

    void FacebookDialog::ShowLoginDialog(
        )
    {
        _dialogResponse = nullptr;
        Uri^ loginDialogUrl = BuildLoginDialogUrl();
        navigatingEventHandlerRegistrationToken = dialogWebBrowser->NavigationStarting +=
            ref new TypedEventHandler<WebView^, WebViewNavigationStartingEventArgs^>(
                this, &FacebookDialog::dialogWebView_LoginNavStarting);

        CoreWindow^ wnd1 = CoreApplication::MainView->CoreWindow;
        _grid->Height = wnd1->Bounds.Height;
        _grid->Width = wnd1->Bounds.Width;
        Width = _grid->Width;
        _popup->IsOpen = true;

        dialogWebBrowser->Navigate(loginDialogUrl);
    }

    void FacebookDialog::ShowFeedDialog(
        )
    {
        _dialogResponse = nullptr;
        Uri^ feedDialogUrl = BuildFeedDialogUrl();
        navigatingEventHandlerRegistrationToken = dialogWebBrowser->NavigationStarting +=
            ref new TypedEventHandler<WebView^, WebViewNavigationStartingEventArgs^>(
                this, &FacebookDialog::dialogWebView_FeedNavStarting);

        CoreWindow^ wnd1 = CoreApplication::MainView->CoreWindow;
        _grid->Height = wnd1->Bounds.Height;
        _grid->Width = wnd1->Bounds.Width;
        Width = _grid->Width;
        _popup->IsOpen = true;

        dialogWebBrowser->Navigate(feedDialogUrl);
    }

    void FacebookDialog::ShowRequestsDialog(
        )
    {
        _dialogResponse = nullptr;
        Uri^ requestDialogUrl = BuildRequestsDialogUrl();
        navigatingEventHandlerRegistrationToken = dialogWebBrowser->NavigationStarting +=
            ref new TypedEventHandler<WebView^, WebViewNavigationStartingEventArgs^>(
                this, &FacebookDialog::dialogWebView_RequestNavStarting);

        CoreWindow^ wnd1 = CoreApplication::MainView->CoreWindow;
        _grid->Height = wnd1->Bounds.Height;
        _grid->Width = wnd1->Bounds.Width;
        Width = _grid->Width;
        _popup->IsOpen = true;

        dialogWebBrowser->Navigate(requestDialogUrl);
    }

    String^ FacebookDialog::GetRedirectUriString(
        String^ FacebookDialogName
        )
    {
        FBSession^ sess = FBSession::ActiveSession;

        //String^ result = L"fb" + sess->FBAppId + "%3A%2F%2F" +
        //    FacebookDialogName + "_success&app_id=" +
        //    sess->FBAppId + L"&display=touch";

        String^ result = L"https%3A%2F%2Fwww.facebook.com%2Fconnect%2F" +
            "login_success.html&app_id=" +
            sess->FBAppId;

        DebugSpew(L"Redirect URI is " + result);
        return result;
    }

    Uri^ FacebookDialog::BuildLoginDialogUrl(
        )
    {
        FBSession^ sess = FBSession::ActiveSession;
        String^ dialogUriString =
            L"https://www.facebook.com/dialog/oauth?client_id=" +
            sess->FBAppId + L"&redirect_uri=" +
            GetRedirectUriString(L"login") + L"&scope="
            + sess->PermissionsToString() + L"&display=popup" +
            L"&response_type=token";

        //String^ dialogUriString =
        //    L"https://m.facebook.com/dialog/oauth?client_id=" +
        //    sess->FBAppId + L"&redirect_uri=" +
        //    GetRedirectUriString(L"login") + L"&scope="
        //    + sess->PermissionsToString() + L"&display=popup" +
        //    L"&response_type=token";

        DebugSpew(L"Request string is " + dialogUriString);

        return ref new Uri(dialogUriString);
    }

    Uri^ FacebookDialog::BuildFeedDialogUrl(
        )
    {
        FBSession^ sess = FBSession::ActiveSession;
        String^ dialogUriString =
            L"https://www.facebook.com/v2.1/dialog/feed?access_token=" +
            sess->AccessTokenData->AccessToken +
            L"&redirect_uri=" + GetRedirectUriString(L"feed");

        //String^ dialogUriString =
        //    L"https://m.facebook.com/v2.1/dialog/feed?access_token=" +
        //    sess->AccessTokenData->AccessToken +
        //    L"&redirect_uri=" + GetRedirectUriString(L"feed");

        return ref new Uri(dialogUriString);
    }

    Uri^ FacebookDialog::BuildRequestsDialogUrl(
        )
    {
        FBSession^ sess = FBSession::ActiveSession;
        //TODO: YOUR_MESSAGE_HERE?  Do we need a message parameter here?  It
        //doesn't appear to show up anywhere in the requests dialog...
        String^ dialogUriString =
            L"https://www.facebook.com/v2.1/dialog/apprequests?access_token=" +
            sess->AccessTokenData->AccessToken +
            L"&redirect_uri=" + GetRedirectUriString(L"requests") +
            L"&message=YOUR_MESSAGE_HERE";

        return ref new Uri(dialogUriString);
    }

    bool FacebookDialog::IsLoginSuccessRedirect(
        Uri^ Response
        )
    {
        return (String::CompareOrdinal(Response->Path, L"/connect/login_success.html") == 0);
    }

    void FacebookDialog::dialogWebView_LoginNavStarting(
        WebView^ sender,
        WebViewNavigationStartingEventArgs^ e
        )
    {
        DebugSpew(L"Navigating to " + e->Uri->DisplayUri);
        DebugSpew(L"Path is " + e->Uri->Path);

        if (IsLoginSuccessRedirect(e->Uri))
        {
            dialogWebBrowser->Stop();

            _popup->IsOpen = false;

            FBAccessTokenData^ tokenData = FBAccessTokenData::FromUri(e->Uri);
            if (tokenData)
            {
                _dialogResponse = ref new FBResult(tokenData);
            }
            else
            {
                String^ ErrorObjectJson = L"{\"error\": {\"message\": "
                    L"\"Operation Canceled\", \"type\": "
                    L"\"OAuthException\", \"code\": 4201, "
                    L"\"error_user_msg\": \"User canceled the Dialog flow\""
                    L"}}";

                FBError^ err = FBError::FromJson(ErrorObjectJson);
                _dialogResponse = ref new FBResult(err);
            }

            // deregister the event handler
            dialogWebBrowser->NavigationStarting -= navigatingEventHandlerRegistrationToken;
        }
    }

    void FacebookDialog::dialogWebView_FeedNavStarting(
        WebView^ sender,
        WebViewNavigationStartingEventArgs^ e
        )
    {
        DebugSpew(L"Navigating to " + e->Uri->DisplayUri);
        DebugSpew(L"Path is " + e->Uri->Path);

        if (IsLoginSuccessRedirect(e->Uri))
        {
            dialogWebBrowser->Stop();

            _popup->IsOpen = false;

            DebugSpew(L"Feed response is " + e->Uri->DisplayUri);

            FBFeedRequest^ request = FBFeedRequest::FromFeedDialogResponse(e->Uri);
            if (request)
            {
                _dialogResponse = ref new FBResult(request);
            }
            else
            {
                String^ ErrorObjectJson = L"{\"error\": {\"message\": "
                    L"\"Operation Canceled\", \"type\": "
                    L"\"OAuthException\", \"code\": 4201, "
                    L"\"error_user_msg\": \"User canceled the Dialog flow\""
                    L"}}";

                FBError^ err = FBError::FromJson(ErrorObjectJson);
                _dialogResponse = ref new FBResult(err);
            }

            // deregister the event handler
            dialogWebBrowser->NavigationStarting -= navigatingEventHandlerRegistrationToken;
        }
    }

    void FacebookDialog::dialogWebView_RequestNavStarting(
        WebView^ sender,
        WebViewNavigationStartingEventArgs^ e
        )
    {
        DebugSpew(L"Navigating to " + e->Uri->DisplayUri);
        DebugSpew(L"Path is " + e->Uri->Path);

        if (IsLoginSuccessRedirect(e->Uri))
        {
            dialogWebBrowser->Stop();

            _popup->IsOpen = false;

            DebugSpew(L"Request response is " + e->Uri->DisplayUri);

            String^ ErrorObjectJson = L"{\"error\": {\"message\": "
                L"\"Operation Canceled\", \"type\": "
                L"\"OAuthException\", \"code\": 4201, "
                L"\"error_user_msg\": \"User canceled the Dialog flow\""
                L"}}";

            FBError^ err = FBError::FromJson(ErrorObjectJson);
            _dialogResponse = ref new FBResult(err);

            // deregister the event handler
            dialogWebBrowser->NavigationStarting -= navigatingEventHandlerRegistrationToken;
        }
    }

    void FacebookDialog::CloseDialogButton_OnClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    {
        _popup->IsOpen = false;

        // If the user hits the close button, exit the dialog
		if (login_evt)
		{
			SetEvent(login_evt);
		}
	}
}
<commit_msg>App requests are now successfully parsed out of request dialog response.<commit_after>//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************

//
// FacebookDialog.xaml.cpp
// Implementation of the FacebookDialog class
//

#include "pch.h"
#include "FacebookDialog.xaml.h"
#include "FacebookSession.h"
#include "FacebookFeedRequest.h"
#include "FacebookAppRequest.h"

using namespace Platform;
using namespace Platform::Collections;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Popups;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Facebook;
using namespace Facebook::Graph;

#if (defined(_MSC_VER) && (_MSC_VER >= 1800))
using namespace concurrency;
#else
using namespace pplx;
#endif

using namespace std;

void DebugSpew(
    String^ msg
    )
{
    String^ output = msg + L"\n";
    OutputDebugString(output->Data());
}

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
namespace Facebook
{
    FacebookDialog::FacebookDialog()
    {
        InitializeComponent();
        _popup = nullptr;
        _dialogResponse = nullptr;

        CoreWindow^ wnd1 = CoreApplication::MainView->CoreWindow;

        _grid = ref new Grid();
        _popup = ref new Popup();

        _popup->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Stretch;
        _popup->VerticalAlignment = Windows::UI::Xaml::VerticalAlignment::Stretch;

        // TODO: (sanjeevd) hard coded, remove and fix these
        _grid->Margin = Windows::UI::Xaml::Thickness(0, 0, 0, 0);
        _grid->Height = wnd1->Bounds.Height;
        _grid->Width = wnd1->Bounds.Width;

        Width = _grid->Width;

        _grid->Children->Append(this);
        _popup->Child = _grid;
    }

    extern HANDLE login_evt;

    FBResult^ FacebookDialog::DialogResponse::get()
    {
        FBResult^ response = _dialogResponse;
        if (response)
        {
            // Caller (FBSession) only gets the response *once*.  Then we reset
            // it to null, so it's valid to poll on the value being null again.
            _dialogResponse = nullptr;
        }

        return response;
    }

    void FacebookDialog::ShowLoginDialog(
        )
    {
        _dialogResponse = nullptr;
        Uri^ loginDialogUrl = BuildLoginDialogUrl();
        navigatingEventHandlerRegistrationToken = dialogWebBrowser->NavigationStarting +=
            ref new TypedEventHandler<WebView^, WebViewNavigationStartingEventArgs^>(
                this, &FacebookDialog::dialogWebView_LoginNavStarting);

        CoreWindow^ wnd1 = CoreApplication::MainView->CoreWindow;
        _grid->Height = wnd1->Bounds.Height;
        _grid->Width = wnd1->Bounds.Width;
        Width = _grid->Width;
        _popup->IsOpen = true;

        dialogWebBrowser->Navigate(loginDialogUrl);
    }

    void FacebookDialog::ShowFeedDialog(
        )
    {
        _dialogResponse = nullptr;
        Uri^ feedDialogUrl = BuildFeedDialogUrl();
        navigatingEventHandlerRegistrationToken = dialogWebBrowser->NavigationStarting +=
            ref new TypedEventHandler<WebView^, WebViewNavigationStartingEventArgs^>(
                this, &FacebookDialog::dialogWebView_FeedNavStarting);

        CoreWindow^ wnd1 = CoreApplication::MainView->CoreWindow;
        _grid->Height = wnd1->Bounds.Height;
        _grid->Width = wnd1->Bounds.Width;
        Width = _grid->Width;
        _popup->IsOpen = true;

        dialogWebBrowser->Navigate(feedDialogUrl);
    }

    void FacebookDialog::ShowRequestsDialog(
        )
    {
        _dialogResponse = nullptr;
        Uri^ requestDialogUrl = BuildRequestsDialogUrl();
        navigatingEventHandlerRegistrationToken = dialogWebBrowser->NavigationStarting +=
            ref new TypedEventHandler<WebView^, WebViewNavigationStartingEventArgs^>(
                this, &FacebookDialog::dialogWebView_RequestNavStarting);

        CoreWindow^ wnd1 = CoreApplication::MainView->CoreWindow;
        _grid->Height = wnd1->Bounds.Height;
        _grid->Width = wnd1->Bounds.Width;
        Width = _grid->Width;
        _popup->IsOpen = true;

        dialogWebBrowser->Navigate(requestDialogUrl);
    }

    String^ FacebookDialog::GetRedirectUriString(
        String^ FacebookDialogName
        )
    {
        FBSession^ sess = FBSession::ActiveSession;

        //String^ result = L"fb" + sess->FBAppId + "%3A%2F%2F" +
        //    FacebookDialogName + "_success&app_id=" +
        //    sess->FBAppId + L"&display=touch";

        String^ result = L"https%3A%2F%2Fwww.facebook.com%2Fconnect%2F" +
            "login_success.html&app_id=" +
            sess->FBAppId;

        DebugSpew(L"Redirect URI is " + result);
        return result;
    }

    Uri^ FacebookDialog::BuildLoginDialogUrl(
        )
    {
        FBSession^ sess = FBSession::ActiveSession;
        String^ dialogUriString =
            L"https://www.facebook.com/dialog/oauth?client_id=" +
            sess->FBAppId + L"&redirect_uri=" +
            GetRedirectUriString(L"login") + L"&scope="
            + sess->PermissionsToString() + L"&display=popup" +
            L"&response_type=token";

        //String^ dialogUriString =
        //    L"https://m.facebook.com/dialog/oauth?client_id=" +
        //    sess->FBAppId + L"&redirect_uri=" +
        //    GetRedirectUriString(L"login") + L"&scope="
        //    + sess->PermissionsToString() + L"&display=popup" +
        //    L"&response_type=token";

        DebugSpew(L"Request string is " + dialogUriString);

        return ref new Uri(dialogUriString);
    }

    Uri^ FacebookDialog::BuildFeedDialogUrl(
        )
    {
        FBSession^ sess = FBSession::ActiveSession;
        String^ dialogUriString =
            L"https://www.facebook.com/v2.1/dialog/feed?access_token=" +
            sess->AccessTokenData->AccessToken +
            L"&redirect_uri=" + GetRedirectUriString(L"feed");

        //String^ dialogUriString =
        //    L"https://m.facebook.com/v2.1/dialog/feed?access_token=" +
        //    sess->AccessTokenData->AccessToken +
        //    L"&redirect_uri=" + GetRedirectUriString(L"feed");

        return ref new Uri(dialogUriString);
    }

    Uri^ FacebookDialog::BuildRequestsDialogUrl(
        )
    {
        FBSession^ sess = FBSession::ActiveSession;
        //TODO: YOUR_MESSAGE_HERE?  Do we need a message parameter here?  It
        //doesn't appear to show up anywhere in the requests dialog...
        String^ dialogUriString =
            L"https://www.facebook.com/v2.1/dialog/apprequests?access_token=" +
            sess->AccessTokenData->AccessToken +
            L"&redirect_uri=" + GetRedirectUriString(L"requests") +
            L"&message=YOUR_MESSAGE_HERE";

        return ref new Uri(dialogUriString);
    }

    bool FacebookDialog::IsLoginSuccessRedirect(
        Uri^ Response
        )
    {
        return (String::CompareOrdinal(Response->Path, L"/connect/login_success.html") == 0);
    }

    void FacebookDialog::dialogWebView_LoginNavStarting(
        WebView^ sender,
        WebViewNavigationStartingEventArgs^ e
        )
    {
        DebugSpew(L"Navigating to " + e->Uri->DisplayUri);
        DebugSpew(L"Path is " + e->Uri->Path);

        if (IsLoginSuccessRedirect(e->Uri))
        {
            dialogWebBrowser->Stop();

            _popup->IsOpen = false;

            FBAccessTokenData^ tokenData = FBAccessTokenData::FromUri(e->Uri);
            if (tokenData)
            {
                _dialogResponse = ref new FBResult(tokenData);
            }
            else
            {
                String^ ErrorObjectJson = L"{\"error\": {\"message\": "
                    L"\"Operation Canceled\", \"type\": "
                    L"\"OAuthException\", \"code\": 4201, "
                    L"\"error_user_msg\": \"User canceled the Dialog flow\""
                    L"}}";

                FBError^ err = FBError::FromJson(ErrorObjectJson);
                _dialogResponse = ref new FBResult(err);
            }

            // deregister the event handler
            dialogWebBrowser->NavigationStarting -= navigatingEventHandlerRegistrationToken;
        }
    }

    void FacebookDialog::dialogWebView_FeedNavStarting(
        WebView^ sender,
        WebViewNavigationStartingEventArgs^ e
        )
    {
        DebugSpew(L"Navigating to " + e->Uri->DisplayUri);
        DebugSpew(L"Path is " + e->Uri->Path);

        if (IsLoginSuccessRedirect(e->Uri))
        {
            dialogWebBrowser->Stop();

            _popup->IsOpen = false;

            DebugSpew(L"Feed response is " + e->Uri->DisplayUri);

            FBFeedRequest^ request = FBFeedRequest::FromFeedDialogResponse(e->Uri);
            if (request)
            {
                _dialogResponse = ref new FBResult(request);
            }
            else
            {
                String^ ErrorObjectJson = L"{\"error\": {\"message\": "
                    L"\"Operation Canceled\", \"type\": "
                    L"\"OAuthException\", \"code\": 4201, "
                    L"\"error_user_msg\": \"User canceled the Dialog flow\""
                    L"}}";

                FBError^ err = FBError::FromJson(ErrorObjectJson);
                _dialogResponse = ref new FBResult(err);
            }

            // deregister the event handler
            dialogWebBrowser->NavigationStarting -= navigatingEventHandlerRegistrationToken;
        }
    }

    void FacebookDialog::dialogWebView_RequestNavStarting(
        WebView^ sender,
        WebViewNavigationStartingEventArgs^ e
        )
    {
        DebugSpew(L"Navigating to " + e->Uri->DisplayUri);
        DebugSpew(L"Path is " + e->Uri->Path);

        if (IsLoginSuccessRedirect(e->Uri))
        {
            dialogWebBrowser->Stop();

            _popup->IsOpen = false;

            DebugSpew(L"Request response is " + e->Uri->DisplayUri);

            FBAppRequest^ request = FBAppRequest::FromRequestDialogResponse(e->Uri);
            if (request)
            {
                _dialogResponse = ref new FBResult(request);
            }
            else
            {
                String^ ErrorObjectJson = L"{\"error\": {\"message\": "
                    L"\"Operation Canceled\", \"type\": "
                    L"\"OAuthException\", \"code\": 4201, "
                    L"\"error_user_msg\": \"User canceled the Dialog flow\""
                    L"}}";

                FBError^ err = FBError::FromJson(ErrorObjectJson);
                _dialogResponse = ref new FBResult(err);
            }

            // deregister the event handler
            dialogWebBrowser->NavigationStarting -= navigatingEventHandlerRegistrationToken;
        }
    }

    void FacebookDialog::CloseDialogButton_OnClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    {
        _popup->IsOpen = false;

        // If the user hits the close button, exit the dialog
		if (login_evt)
		{
			SetEvent(login_evt);
		}
	}
}
<|endoftext|>


<commit_before>aa3d3fc2-ad5c-11e7-8977-ac87a332f658<commit_msg>Too poor for Dropbox<commit_after>aaa3aabd-ad5c-11e7-b07a-ac87a332f658<|endoftext|>


<commit_before>#include <node.h>
#include <v8.h>
#include <string>
#include <iostream>
#include "steamworks-sdk/public/steam/steam_api.h"
#include "steamworks-sdk/public/steam/steam_gameserver.h"
#include "steamworks-sdk/public/steam/isteamremotestorage.h"

using namespace v8;
using namespace std;

struct FileIOAsync {
	Persistent<Function> errorCallback;
	Persistent<Function> successCallback;
	string sFilename;
	string sContent;
	string sError;
	bool bSuccess;
};

struct CloudQuota {
	Persistent<Function> errorCallback;
	Persistent<Function> successCallback;
	int nTotalBytes;
	int nAvailableBytes;
	bool bSuccess;
};

struct Achievement {
	Persistent<Function> errorCallback;
	Persistent<Function> successCallback;
	string sAchievementId;
	bool bSuccess;
};

class GreenheartGames : node::ObjectWrap {
	private:

		static void steamWriteToFile(uv_work_t *req) {
			FileIOAsync *writeData = (FileIOAsync*)req->data;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			// Checking quota (in the future we may need it)
			int nTotal = -1, nAvailable = -1;

			if (!pSteamRemoteStorage->GetQuota(&nTotal, &nAvailable)) {
				writeData->sError = "Error getting Cloud quota";
				writeData->bSuccess = false;
				return;
			}

			writeData->bSuccess = pSteamRemoteStorage->FileWrite(writeData->sFilename.c_str(), writeData->sContent.c_str(), (int)strlen(writeData->sContent.c_str()));
			if (!writeData->bSuccess)
				writeData->sError = "Error writing to file. ";

			return;
		}

		static void steamReadFromFile(uv_work_t *req) {
			FileIOAsync *readData = (FileIOAsync*)req->data;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			// Check if file exists
			if (!pSteamRemoteStorage->FileExists(readData->sFilename.c_str())) {
				readData->bSuccess = false;
				readData->sError = "File doesn't exist";
				return;
			}

			int32 nFileSize = pSteamRemoteStorage->GetFileSize(readData->sFilename.c_str());

			char *sFileContents = new char[nFileSize+1];
			int32 cubRead = pSteamRemoteStorage->FileRead( readData->sFilename.c_str(), sFileContents, nFileSize );
			sFileContents[cubRead] = 0; // null-terminate

			if (cubRead == 0 && nFileSize > 0) {
				readData->bSuccess = false;
				readData->sError = "Error loading file";
			}
			else {
				readData->bSuccess = true;
				readData->sContent = sFileContents;
			}

			delete sFileContents;
			return;
		}

		static void steamGetCloudQuota(uv_work_t *req) {
			CloudQuota *quotaData = (CloudQuota*)req->data;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			int nTotal = -1, nAvailable = -1;

			if (!pSteamRemoteStorage->GetQuota(&nTotal, &nAvailable)) {
				quotaData->bSuccess = false;
				return;
			}

			quotaData->bSuccess = true;
			quotaData->nTotalBytes = nTotal;
			quotaData->nAvailableBytes = nAvailable;

			return;
		}

		static void steamSetAchievement(uv_work_t *req) {
			Achievement *achievementData = (Achievement*)req->data;
			ISteamUserStats *pSteamUserStats = SteamUserStats();

			pSteamUserStats->SetAchievement(achievementData->sAchievementId.c_str());
			achievementData->bSuccess = pSteamUserStats->StoreStats();

			return;
		}

		static void fileWrote(uv_work_t *req) {
			FileIOAsync *writeData = (FileIOAsync*)req->data;

			// Calling callback here
			Handle<Value> callbackResultArgs[1];

			if (writeData->bSuccess) {
				callbackResultArgs[0] = Undefined();
				writeData->successCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
			else {
				callbackResultArgs[0] = String::New(writeData->sError.c_str());
				writeData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}

			return;
		}

		static void fileLoaded(uv_work_t *req) {
			FileIOAsync *readData = (FileIOAsync*)req->data;

			// Calling callback here
			Handle<Value> callbackResultArgs[1];

			if (readData->bSuccess) {
				callbackResultArgs[0] = String::New(readData->sContent.c_str());
				readData->successCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
			else {
				callbackResultArgs[0] = String::New(readData->sError.c_str());
				readData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
		}

		static void gotQuota(uv_work_t *req) {
			CloudQuota *quotaData = (CloudQuota*)req->data;

			Handle<Value> callbackResultArgs[2];

			if (quotaData->bSuccess) {
				callbackResultArgs[0] = Integer::New(quotaData->nTotalBytes);
				callbackResultArgs[1] = Integer::New(quotaData->nAvailableBytes);
				quotaData->successCallback->Call(Context::GetCurrent()->Global(), 2, callbackResultArgs);
			}
			else {
				callbackResultArgs[0] = Undefined();
				quotaData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
		}

		static void achievementStored(uv_work_t *req) {
			Achievement *achievementData = (Achievement*)req->data;

			Handle<Value> callbackResultArgs[1];
			callbackResultArgs[0] = Undefined();

			if (achievementData->bSuccess) {
				achievementData->successCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
			else {
				achievementData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
		}

	public:
		GreenheartGames()  {}
		~GreenheartGames() {}

		static Handle<Value> initAPI(const Arguments& args) {
			HandleScope scope;

			// Initializing Steam API
			bool bSuccess = SteamAPI_Init();

			if (bSuccess) {
				ISteamUserStats *pSteamUserStats = SteamUserStats();
				pSteamUserStats->RequestCurrentStats();
			}

			return scope.Close(Boolean::New(bSuccess));
		}

		static Handle<Value> getCloudQuota(const Arguments& args) {
			HandleScope scope;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			Local<Function>successCallback = Local<Function>::Cast(args[0]);
			Local<Function>errorCallback   = Local<Function>::Cast(args[1]);

			CloudQuota *quotaData = new CloudQuota;
			quotaData->successCallback  = Persistent<Function>::New(successCallback);
			quotaData->errorCallback    = Persistent<Function>::New(errorCallback);

			uv_work_t *req = new uv_work_t;
			req->data = quotaData;

			// Call separate thread work
			uv_queue_work(uv_default_loop(), req, steamGetCloudQuota, (uv_after_work_cb)gotQuota);

			return scope.Close(Undefined());
		}

		static Handle<Value> saveTextToFile(const Arguments& args) {
			HandleScope scope;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			// Convert passed string arguments directly to std::string
			string sFilename(*String::Utf8Value(args[0]));
			string sContent(*String::Utf8Value(args[1]));
			Local<Function>successCallback = Local<Function>::Cast(args[2]);
			Local<Function>errorCallback   = Local<Function>::Cast(args[3]);

			FileIOAsync *writeData = new FileIOAsync;
			writeData->successCallback  = Persistent<Function>::New(successCallback);
			writeData->errorCallback    = Persistent<Function>::New(errorCallback);
			writeData->sFilename = sFilename;
			writeData->sContent  = sContent;

			// Preparing separate thread work call
			uv_work_t *req = new uv_work_t;
			req->data = writeData;

			// Call separate thread work
			uv_queue_work(uv_default_loop(), req, steamWriteToFile, (uv_after_work_cb)fileWrote);

			return scope.Close(Undefined());
		}

		static Handle<Value> readTextFromFile(const Arguments& args) {
			HandleScope scope;

			// Convert passed string arguments directly to std::string
			string sFilename(*String::Utf8Value(args[0]));
			Local<Function>successCallback = Local<Function>::Cast(args[1]);
			Local<Function>errorCallback   = Local<Function>::Cast(args[2]);

			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();
			FileIOAsync *readData = new FileIOAsync;
			readData->successCallback  = Persistent<Function>::New(successCallback);
			readData->errorCallback    = Persistent<Function>::New(errorCallback);
			readData->sFilename = sFilename;

			// Preparing separate thread work call
			uv_work_t *req = new uv_work_t;
			req->data = readData;

			// Call separate thread work
			uv_queue_work(uv_default_loop(), req, steamReadFromFile, (uv_after_work_cb)fileLoaded);

			return scope.Close(Undefined());
		}

		static Handle<Value> activateAchievement(const Arguments& args) {
			HandleScope scope;

			string sAchievementId(*String::Utf8Value(args[0]));
			Local<Function>successCallback = Local<Function>::Cast(args[1]);
			Local<Function>errorCallback   = Local<Function>::Cast(args[2]);

			Achievement *achievementData = new Achievement;
			achievementData->successCallback = Persistent<Function>::New(successCallback);
			achievementData->errorCallback   = Persistent<Function>::New(errorCallback);
			achievementData->sAchievementId  = sAchievementId;

			// Preparing separate thread work call
			uv_work_t *req = new uv_work_t;
			req->data = achievementData;

			// Call separate thread work
			uv_queue_work(uv_default_loop(), req, steamSetAchievement, (uv_after_work_cb)achievementStored);

			return scope.Close(Undefined());
		}
};

void init(Handle<Object> exports) {
	exports->Set(String::NewSymbol("initAPI"), FunctionTemplate::New(GreenheartGames::initAPI)->GetFunction());
	exports->Set(String::NewSymbol("getCloudQuota"), FunctionTemplate::New(GreenheartGames::getCloudQuota)->GetFunction());
	exports->Set(String::NewSymbol("saveTextToFile"), FunctionTemplate::New(GreenheartGames::saveTextToFile)->GetFunction());
	exports->Set(String::NewSymbol("readTextFromFile"), FunctionTemplate::New(GreenheartGames::readTextFromFile)->GetFunction());
	exports->Set(String::NewSymbol("activateAchievement"), FunctionTemplate::New(GreenheartGames::activateAchievement)->GetFunction());
}

#ifdef _WIN32
	NODE_MODULE(greenworks_win, init)
#elif __APPLE__
	NODE_MODULE(greenworks_osx, init)
#elif __linux__
	NODE_MODULE(greenworks_linux, init)
#endif
<commit_msg>changed main classname from GreenheartGames to Greenworks<commit_after>#include <node.h>
#include <v8.h>
#include <string>
#include <iostream>
#include "steamworks-sdk/public/steam/steam_api.h"
#include "steamworks-sdk/public/steam/steam_gameserver.h"
#include "steamworks-sdk/public/steam/isteamremotestorage.h"

using namespace v8;
using namespace std;

struct FileIOAsync {
	Persistent<Function> errorCallback;
	Persistent<Function> successCallback;
	string sFilename;
	string sContent;
	string sError;
	bool bSuccess;
};

struct CloudQuota {
	Persistent<Function> errorCallback;
	Persistent<Function> successCallback;
	int nTotalBytes;
	int nAvailableBytes;
	bool bSuccess;
};

struct Achievement {
	Persistent<Function> errorCallback;
	Persistent<Function> successCallback;
	string sAchievementId;
	bool bSuccess;
};

class Greenworks : node::ObjectWrap {
	private:

		static void steamWriteToFile(uv_work_t *req) {
			FileIOAsync *writeData = (FileIOAsync*)req->data;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			// Checking quota (in the future we may need it)
			int nTotal = -1, nAvailable = -1;

			if (!pSteamRemoteStorage->GetQuota(&nTotal, &nAvailable)) {
				writeData->sError = "Error getting Cloud quota";
				writeData->bSuccess = false;
				return;
			}

			writeData->bSuccess = pSteamRemoteStorage->FileWrite(writeData->sFilename.c_str(), writeData->sContent.c_str(), (int)strlen(writeData->sContent.c_str()));
			if (!writeData->bSuccess)
				writeData->sError = "Error writing to file. ";

			return;
		}

		static void steamReadFromFile(uv_work_t *req) {
			FileIOAsync *readData = (FileIOAsync*)req->data;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			// Check if file exists
			if (!pSteamRemoteStorage->FileExists(readData->sFilename.c_str())) {
				readData->bSuccess = false;
				readData->sError = "File doesn't exist";
				return;
			}

			int32 nFileSize = pSteamRemoteStorage->GetFileSize(readData->sFilename.c_str());

			char *sFileContents = new char[nFileSize+1];
			int32 cubRead = pSteamRemoteStorage->FileRead( readData->sFilename.c_str(), sFileContents, nFileSize );
			sFileContents[cubRead] = 0; // null-terminate

			if (cubRead == 0 && nFileSize > 0) {
				readData->bSuccess = false;
				readData->sError = "Error loading file";
			}
			else {
				readData->bSuccess = true;
				readData->sContent = sFileContents;
			}

			delete sFileContents;
			return;
		}

		static void steamGetCloudQuota(uv_work_t *req) {
			CloudQuota *quotaData = (CloudQuota*)req->data;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			int nTotal = -1, nAvailable = -1;

			if (!pSteamRemoteStorage->GetQuota(&nTotal, &nAvailable)) {
				quotaData->bSuccess = false;
				return;
			}

			quotaData->bSuccess = true;
			quotaData->nTotalBytes = nTotal;
			quotaData->nAvailableBytes = nAvailable;

			return;
		}

		static void steamSetAchievement(uv_work_t *req) {
			Achievement *achievementData = (Achievement*)req->data;
			ISteamUserStats *pSteamUserStats = SteamUserStats();

			pSteamUserStats->SetAchievement(achievementData->sAchievementId.c_str());
			achievementData->bSuccess = pSteamUserStats->StoreStats();

			return;
		}

		static void fileWrote(uv_work_t *req) {
			FileIOAsync *writeData = (FileIOAsync*)req->data;

			// Calling callback here
			Handle<Value> callbackResultArgs[1];

			if (writeData->bSuccess) {
				callbackResultArgs[0] = Undefined();
				writeData->successCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
			else {
				callbackResultArgs[0] = String::New(writeData->sError.c_str());
				writeData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}

			return;
		}

		static void fileLoaded(uv_work_t *req) {
			FileIOAsync *readData = (FileIOAsync*)req->data;

			// Calling callback here
			Handle<Value> callbackResultArgs[1];

			if (readData->bSuccess) {
				callbackResultArgs[0] = String::New(readData->sContent.c_str());
				readData->successCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
			else {
				callbackResultArgs[0] = String::New(readData->sError.c_str());
				readData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
		}

		static void gotQuota(uv_work_t *req) {
			CloudQuota *quotaData = (CloudQuota*)req->data;

			Handle<Value> callbackResultArgs[2];

			if (quotaData->bSuccess) {
				callbackResultArgs[0] = Integer::New(quotaData->nTotalBytes);
				callbackResultArgs[1] = Integer::New(quotaData->nAvailableBytes);
				quotaData->successCallback->Call(Context::GetCurrent()->Global(), 2, callbackResultArgs);
			}
			else {
				callbackResultArgs[0] = Undefined();
				quotaData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
		}

		static void achievementStored(uv_work_t *req) {
			Achievement *achievementData = (Achievement*)req->data;

			Handle<Value> callbackResultArgs[1];
			callbackResultArgs[0] = Undefined();

			if (achievementData->bSuccess) {
				achievementData->successCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
			else {
				achievementData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
		}

	public:
		GreenheartGames()  {}
		~GreenheartGames() {}

		static Handle<Value> initAPI(const Arguments& args) {
			HandleScope scope;

			// Initializing Steam API
			bool bSuccess = SteamAPI_Init();

			if (bSuccess) {
				ISteamUserStats *pSteamUserStats = SteamUserStats();
				pSteamUserStats->RequestCurrentStats();
			}

			return scope.Close(Boolean::New(bSuccess));
		}

		static Handle<Value> getCloudQuota(const Arguments& args) {
			HandleScope scope;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			Local<Function>successCallback = Local<Function>::Cast(args[0]);
			Local<Function>errorCallback   = Local<Function>::Cast(args[1]);

			CloudQuota *quotaData = new CloudQuota;
			quotaData->successCallback  = Persistent<Function>::New(successCallback);
			quotaData->errorCallback    = Persistent<Function>::New(errorCallback);

			uv_work_t *req = new uv_work_t;
			req->data = quotaData;

			// Call separate thread work
			uv_queue_work(uv_default_loop(), req, steamGetCloudQuota, (uv_after_work_cb)gotQuota);

			return scope.Close(Undefined());
		}

		static Handle<Value> saveTextToFile(const Arguments& args) {
			HandleScope scope;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			// Convert passed string arguments directly to std::string
			string sFilename(*String::Utf8Value(args[0]));
			string sContent(*String::Utf8Value(args[1]));
			Local<Function>successCallback = Local<Function>::Cast(args[2]);
			Local<Function>errorCallback   = Local<Function>::Cast(args[3]);

			FileIOAsync *writeData = new FileIOAsync;
			writeData->successCallback  = Persistent<Function>::New(successCallback);
			writeData->errorCallback    = Persistent<Function>::New(errorCallback);
			writeData->sFilename = sFilename;
			writeData->sContent  = sContent;

			// Preparing separate thread work call
			uv_work_t *req = new uv_work_t;
			req->data = writeData;

			// Call separate thread work
			uv_queue_work(uv_default_loop(), req, steamWriteToFile, (uv_after_work_cb)fileWrote);

			return scope.Close(Undefined());
		}

		static Handle<Value> readTextFromFile(const Arguments& args) {
			HandleScope scope;

			// Convert passed string arguments directly to std::string
			string sFilename(*String::Utf8Value(args[0]));
			Local<Function>successCallback = Local<Function>::Cast(args[1]);
			Local<Function>errorCallback   = Local<Function>::Cast(args[2]);

			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();
			FileIOAsync *readData = new FileIOAsync;
			readData->successCallback  = Persistent<Function>::New(successCallback);
			readData->errorCallback    = Persistent<Function>::New(errorCallback);
			readData->sFilename = sFilename;

			// Preparing separate thread work call
			uv_work_t *req = new uv_work_t;
			req->data = readData;

			// Call separate thread work
			uv_queue_work(uv_default_loop(), req, steamReadFromFile, (uv_after_work_cb)fileLoaded);

			return scope.Close(Undefined());
		}

		static Handle<Value> activateAchievement(const Arguments& args) {
			HandleScope scope;

			string sAchievementId(*String::Utf8Value(args[0]));
			Local<Function>successCallback = Local<Function>::Cast(args[1]);
			Local<Function>errorCallback   = Local<Function>::Cast(args[2]);

			Achievement *achievementData = new Achievement;
			achievementData->successCallback = Persistent<Function>::New(successCallback);
			achievementData->errorCallback   = Persistent<Function>::New(errorCallback);
			achievementData->sAchievementId  = sAchievementId;

			// Preparing separate thread work call
			uv_work_t *req = new uv_work_t;
			req->data = achievementData;

			// Call separate thread work
			uv_queue_work(uv_default_loop(), req, steamSetAchievement, (uv_after_work_cb)achievementStored);

			return scope.Close(Undefined());
		}
};

void init(Handle<Object> exports) {
	exports->Set(String::NewSymbol("initAPI"), FunctionTemplate::New(GreenheartGames::initAPI)->GetFunction());
	exports->Set(String::NewSymbol("getCloudQuota"), FunctionTemplate::New(GreenheartGames::getCloudQuota)->GetFunction());
	exports->Set(String::NewSymbol("saveTextToFile"), FunctionTemplate::New(GreenheartGames::saveTextToFile)->GetFunction());
	exports->Set(String::NewSymbol("readTextFromFile"), FunctionTemplate::New(GreenheartGames::readTextFromFile)->GetFunction());
	exports->Set(String::NewSymbol("activateAchievement"), FunctionTemplate::New(GreenheartGames::activateAchievement)->GetFunction());
}

#ifdef _WIN32
	NODE_MODULE(greenworks_win, init)
#elif __APPLE__
	NODE_MODULE(greenworks_osx, init)
#elif __linux__
	NODE_MODULE(greenworks_linux, init)
#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <sstream>
#include <sys/stat.h>

using namespace std;

void help() {
    cout << "xxd:  make a hexdump" << endl;
    cout << "visit https://HelloACM.com" << endl;
    cout << "-u uppercase" << endl;
    cout << "-c column" << endl;
}

inline bool file_exists(const string& name) {
    struct stat buffer;
    return (stat (name.c_str(), &buffer) == 0);
}

string tohex(int x, int w = 7, bool upper = false) {
    stringstream stream;
    stream << std::hex << (x & 0xFF);
    string result(stream.str());
    if (upper) {
        std::transform(result.begin(), result.end(), result.begin(), ::toupper);
    }
    int j = w - result.length();
    while (j-- > 0) { // zero padding
        result = '0' + result;
    }
    return result;
}

void print_xxd(string content, int w = 16, bool upper = false) {
    int len = content.size();
    int num = 0;
    string curline = "";
    int width = 9 + (w / 2) * 5 + 1;
    if (w & 1 == 1) {
        width += 3;
    }
    int cw = 1;
    int kk = 1;
    for (int i = 0; i < len ; i ++) {
        if ((i % w) == 0) {
            cout << tohex(num) << ": ";
            cw = 9;
        }
        char t = content[i];
        cout << tohex((int)t, 2, upper);
        cw += 2;
        curline += t;
        if ((i & 1) == kk) {
            cout << " ";
            cw += 1;
        }
        if ((i % w) == (w - 1)) {
            num += w;
            cout << "  ";
            cw += 2;
            int k = i - w + 1;
            for (int j = 0; j < w; j ++) {
                t = content[k ++];
                if ((int)t <= 32) { // non-printable characters
                    t = '.';
                }
                cout << t;
                cw ++;
            }
            cout << "\n\r";
            curline = "";
            cw = 0;
            if (w & 1 == 1) {
                kk = kk == 1 ? 0 : 1;
            }
        }
    }
    // remaining characters;
    int j = width - cw + 1;
    while (j-- > 0) {
        cout << " ";
    }
    for (int i = 0; i < curline.size(); i ++) {
        char t = content[i ++];
        if ((int)t <= 32) { // non-printable characters
            t = '.';
        }
        cout << t;
    }
}

std::string get_file_contents(const char *filename)
{
      std::ifstream in(filename, std::ios::in | std::ios::binary);
      if (in) {
            std::string contents;
            in.seekg(0, std::ios::end);
            contents.resize(in.tellg());
            in.seekg(0, std::ios::beg);
            in.read(&contents[0], contents.size());
            in.close();
            return(contents);
      }
      throw(errno);
}

void xxd(string filename, int w = 16, bool upper = false) {
    if (!file_exists(filename)) {
        cout << "xxd: " << filename << ": No such file or directory" << endl;
        return;
    }
    print_xxd(get_file_contents(filename.c_str()), w, upper);
}

int main(int argc, char ** argv)
{
    bool upper = false;
    int w = 16;
    bool io = true;
    for (int i = 2; i <= argc; i ++) {
        string cur = argv[i - 1];
        if (cur == "-h") {
            help();
            return 0;
        }
        if (cur == "-u") {
            upper = true;
        }
        else if ((cur[0] == '-') && (cur.length() > 1)) {
            if (cur[1] == 'c') {
                if (cur.length() > 2) {
                    string num = cur.substr(2);
                    std::stringstream str(num);
                    int x;
                    str >> x;
                    if (str) {
                        if (x > 0) {
                            w = x;
                        }
                    }
                } else {
                    if (i != argc) {
                        string num = string(argv[i]);
                        std::stringstream str(num);
                        int x;
                        str >> x;
                        if (str) {
                            if (x > 0) {
                                w = x;
                            }
                        }
                        i ++;
                    }
                }
            }
        }
        else {
            xxd(cur, w, upper);
            io = false;
        }
    }
    if (io) {
        // standard input
        std::string line;
        std::string all = "";
        while (std::getline(std::cin, line))
        {
            all += line;
        }
        print_xxd(all, w, upper);
    }
    return 0;
}
<commit_msg>minor fixes<commit_after>#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <sstream>
#include <sys/stat.h>

using namespace std;

void help() {
    cout << "xxd:  make a hexdump" << endl;
    cout << "visit https://HelloACM.com" << endl;
    cout << "-u uppercase" << endl;
    cout << "-c column" << endl;
    cout << "-h help" << endl;
}

inline bool file_exists(const string& name) {
    struct stat buffer;
    return (stat (name.c_str(), &buffer) == 0);
}

string tohex(int x, int w = 7, bool upper = false) {
    stringstream stream;
    stream << std::hex << (x & 0xFF);
    string result(stream.str());
    if (upper) {
        std::transform(result.begin(), result.end(), result.begin(), ::toupper);
    }
    int j = w - result.length();
    while (j-- > 0) { // zero padding
        result = '0' + result;
    }
    return result;
}

void print_xxd(string content, int w = 16, bool upper = false) {
    int len = content.size();
    int num = 0;
    string curline = "";
    int width = 9 + (w / 2) * 5 + 1;
    if (w & 1 == 1) {
        width += 3;
    }
    int cw = 1;
    int kk = 1;
    for (int i = 0; i < len ; i ++) {
        if ((i % w) == 0) {
            cout << tohex(num) << ": ";
            cw = 9;
        }
        char t = content[i];
        cout << tohex((int)t, 2, upper);
        cw += 2;
        curline += t;
        if ((i & 1) == kk) {
            cout << " ";
            cw += 1;
        }
        if ((i % w) == (w - 1)) {
            num += w;
            cout << "  ";
            cw += 2;
            int k = i - w + 1;
            for (int j = 0; j < w; j ++) {
                t = content[k ++];
                if ((int)t < 32) { // non-printable characters
                    t = '.';
                }
                cout << t;
                cw ++;
            }
            cout << "\n\r";
            curline = "";
            cw = 0;
            if (w & 1 == 1) {
                kk = kk == 1 ? 0 : 1;
            }
        }
    }
    // remaining characters;
    int j = width - cw + 1;
    while (j-- > 0) {
        cout << " ";
    }
    for (int i = 0; i < curline.size(); i ++) {
        char t = content[i ++];
        if ((int)t <= 32) { // non-printable characters
            t = '.';
        }
        cout << t;
    }
}

std::string get_file_contents(const char *filename)
{
      std::ifstream in(filename, std::ios::in | std::ios::binary);
      if (in) {
            std::string contents;
            in.seekg(0, std::ios::end);
            contents.resize(in.tellg());
            in.seekg(0, std::ios::beg);
            in.read(&contents[0], contents.size());
            in.close();
            return(contents);
      }
      throw(errno);
}

void xxd(string filename, int w = 16, bool upper = false) {
    if (!file_exists(filename)) {
        cout << "xxd: " << filename << ": No such file or directory" << endl;
        return;
    }
    print_xxd(get_file_contents(filename.c_str()), w, upper);
}

int main(int argc, char ** argv)
{
    bool upper = false;
    int w = 16;
    bool io = true;
    for (int i = 2; i <= argc; i ++) {
        string cur = argv[i - 1];
        if (cur == "-h") {
            help();
            return 0;
        }
        if (cur == "-u") {
            upper = true;
        }
        else if ((cur[0] == '-') && (cur.length() > 1)) {
            if (cur[1] == 'c') {
                if (cur.length() > 2) {
                    string num = cur.substr(2);
                    std::stringstream str(num);
                    int x;
                    str >> x;
                    if (str) {
                        if (x > 0) {
                            w = x;
                        }
                    }
                } else {
                    if (i != argc) {
                        string num = string(argv[i]);
                        std::stringstream str(num);
                        int x;
                        str >> x;
                        if (str) {
                            if (x > 0) {
                                w = x;
                            }
                        }
                        i ++;
                    }
                }
            }
        }
        else {
            xxd(cur, w, upper);
            io = false;
        }
    }
    if (io) {
        // standard input
        std::string line;
        std::string all = "";
        while (std::getline(std::cin, line))
        {
            all += line;
        }
        print_xxd(all, w, upper);
    }
    return 0;
}
<|endoftext|>


<commit_before>29a4ce78-2748-11e6-ad2a-e0f84713e7b8<commit_msg>fix for the previous fix<commit_after>29b0b654-2748-11e6-ad7f-e0f84713e7b8<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: bootstrap.hxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: jb $ $Date: 2001-04-03 16:33:58 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef CONFIGMGR_BOOTSTRAP_HXX_
#define CONFIGMGR_BOOTSTRAP_HXX_

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif

namespace osl {
    class Profile;
}

namespace configmgr
{
    class IConfigSession;

    // ===================================================================================

    #define PORTAL_SESSION_IDENTIFIER           "portal"
    #define REMOTE_SESSION_IDENTIFIER           "remote"
    #define LOCAL_SESSION_IDENTIFIER            "local"
    #define SETUP_SESSION_IDENTIFIER            "setup"
    #define PLUGIN_SESSION_IDENTIFIER           "plugin"

    // ===================================================================================
    // = ConnectionSettings
    // ===================================================================================
    class ConnectionSettings
    {
    public:
        enum SETTING_ORIGIN
        {
            SO_SREGISTRY,
            SO_OVERRIDE,
            SO_FALLBACK,
            SO_UNKNOWN
        };

    protected:
        // ine single setting
        struct Setting
        {
            ::com::sun::star::uno::Any      aValue;
            SETTING_ORIGIN                  eOrigin;

            Setting() : eOrigin(SO_UNKNOWN) { }
            Setting(const ::rtl::OUString& _rValue, SETTING_ORIGIN _eOrigin) : aValue(::com::sun::star::uno::makeAny(_rValue)), eOrigin(_eOrigin) { }
            Setting(const sal_Int32 _nValue, SETTING_ORIGIN _eOrigin) : aValue(::com::sun::star::uno::makeAny(_nValue)), eOrigin(_eOrigin) { }
            Setting(const ::com::sun::star::uno::Any& _rValue, SETTING_ORIGIN _eOrigin) : aValue(_rValue), eOrigin(_eOrigin) { }
        };
        DECLARE_STL_USTRINGACCESS_MAP( Setting, SettingsImpl );
        SettingsImpl        m_aImpl;

        ::osl::Profile*     m_pSRegistry;
        sal_Bool            m_bFoundRegistry;

    public:
        /// default ctor
        ConnectionSettings();

        /// dtor
        ~ConnectionSettings();

        /// copy ctor
        ConnectionSettings(const ConnectionSettings& _rSource);

        /** construct a settings object.

The runtime overrides given will be merged with the settings found in a sversion.ini (sversionrc),
            if any. The former overrule the latter

        */
        ConnectionSettings(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rRuntimeOverrides );

        /// merge the given overrides into a new ConnectionSettings object
        ConnectionSettings& mergeOverrides(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides);

        /// merge the given overrides into the object itself
        ConnectionSettings createMergedSettings(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides) const
        {
            return ConnectionSettings(*this).mergeOverrides(_rOverrides);
        }

        // check setting existence
        sal_Bool            hasRegistry() const { return m_bFoundRegistry; }
        sal_Bool            hasUser() const;
        sal_Bool            hasPassword() const;
        sal_Bool            hasServer() const;
        sal_Bool            hasPort() const;
        sal_Bool            hasTimeout() const;
        sal_Bool            hasService() const;

        sal_Bool            isLocalSession() const;
        sal_Bool            isRemoteSession() const;

        sal_Bool            isValidSourcePath() const;
        sal_Bool            isValidUpdatePath() const;

        // get a special setting
        ::rtl::OUString     getSessionType() const;
        ::rtl::OUString     getUser() const;
        ::rtl::OUString     getPassword() const;
        ::rtl::OUString     getSourcePath() const;
        ::rtl::OUString     getUpdatePath() const;
        ::rtl::OUString     getServer() const;
        ::rtl::OUString     getService() const;
        sal_Int32           getPort() const;
        sal_Int32           getTimeout() const;

        // make sure this behaves as a user session
        void setUserSession();
        void setUserSession(const ::rtl::OUString& _rRemoteServiceName);

        // make sure this behaves as an administrative session
        void setAdminSession();
        void setAdminSession(const ::rtl::OUString& _rRemoteServiceName);

        // set a new session type. Must be one of the *_SESSION_IDENTIFIER defines
        void                setSessionType(const ::rtl::OUString& _rSessionIdentifier);
        // set a desired service, only necessary in remote environments
        sal_Bool            isServiceRequired() const;
        void                setService(const ::rtl::OUString& _rService);

        IConfigSession* ConnectionSettings::createConnection(
            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > const& _rxServiceMgr) const;

    protected:
        void construct(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides);

        // transfer runtime overwrites into m_aImpl. Existent settings will be overwritten.
        void implTranslate(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides)
            throw (::com::sun::star::lang::IllegalArgumentException);

        /** normalize a path setting, delete it if the value could not be normalized
            @return <TRUE/> if the setting exists and is a valid path
        */
        sal_Bool implNormalizePathSetting(const sal_Char* _pSetting);

        // translate old settings, which exist for compatiblity only, into new ones
        void implTranslateCompatibilitySettings();

        // if we do not already have the given config path setting, ensure that it exists (calculated relative to a given path)
        void ensureConfigPath(const sal_Char* _pSetting, const ::rtl::OUString& _rBasePath, const sal_Char* _pRelative);

        sal_Bool        haveSetting(const sal_Char* _pName) const;
        void            putSetting(const sal_Char* _pName, const Setting& _rSetting);
        void            clearSetting(const sal_Char* _pName);

        ::rtl::OUString getStringSetting(const sal_Char* _pName) const;
        sal_Int32       getIntSetting(const sal_Char* _pName) const;
        Setting         getSetting(const sal_Char* _pName) const;
        Setting         getMaybeSetting(const sal_Char* _pName) const;

        ::rtl::OUString getProfileStringItem(const sal_Char* _pSection, const sal_Char* _pKey);
        sal_Int32       getProfileIntItem(const sal_Char* _pSection, const sal_Char* _pKey);

    private:
        // ensures that m_aImpl contains a session type
        // to be called from within construct only
        void implDetermineSessionType();

        // collect settings from the sregistry, put them into m_aImpl, if not overruled by runtime settings
        void implCollectSRegistrySetting();

        // clear items which are not relevant because of the session type origin
        void clearIrrelevantItems();
    };
}

#endif // CONFIGMGR_BOOTSTRAP_HXX_

<commit_msg>Now support 'locale' and 'lazywrite' in sregistryrc and provider creation arguments; admin mode now uses 'all locales' as default<commit_after>/*************************************************************************
 *
 *  $RCSfile: bootstrap.hxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: jb $ $Date: 2001-04-05 14:31:45 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef CONFIGMGR_BOOTSTRAP_HXX_
#define CONFIGMGR_BOOTSTRAP_HXX_

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif

namespace osl {
    class Profile;
}

namespace configmgr
{
    class IConfigSession;

    // ===================================================================================

    #define PORTAL_SESSION_IDENTIFIER           "portal"
    #define REMOTE_SESSION_IDENTIFIER           "remote"
    #define LOCAL_SESSION_IDENTIFIER            "local"
    #define SETUP_SESSION_IDENTIFIER            "setup"
    #define PLUGIN_SESSION_IDENTIFIER           "plugin"

    // ===================================================================================
    // = ConnectionSettings
    // ===================================================================================
    class ConnectionSettings
    {
    public:
        enum SETTING_ORIGIN
        {
            SO_SREGISTRY,
            SO_OVERRIDE,
            SO_FALLBACK,
            SO_UNKNOWN
        };

    protected:
        // ine single setting
        struct Setting
        {
            ::com::sun::star::uno::Any      aValue;
            SETTING_ORIGIN                  eOrigin;

            Setting() : eOrigin(SO_UNKNOWN) { }
            Setting(const ::rtl::OUString& _rValue, SETTING_ORIGIN _eOrigin) : aValue(::com::sun::star::uno::makeAny(_rValue)), eOrigin(_eOrigin) { }
            Setting(const sal_Int32 _nValue, SETTING_ORIGIN _eOrigin) : aValue(::com::sun::star::uno::makeAny(_nValue)), eOrigin(_eOrigin) { }
            Setting(const ::com::sun::star::uno::Any& _rValue, SETTING_ORIGIN _eOrigin) : aValue(_rValue), eOrigin(_eOrigin) { }
        };
        DECLARE_STL_USTRINGACCESS_MAP( Setting, SettingsImpl );
        SettingsImpl        m_aImpl;

        ::osl::Profile*     m_pSRegistry;
        sal_Bool            m_bFoundRegistry;

    public:
        /// default ctor
        ConnectionSettings();

        /// dtor
        ~ConnectionSettings();

        /// copy ctor
        ConnectionSettings(const ConnectionSettings& _rSource);

        /** construct a settings object.

The runtime overrides given will be merged with the settings found in a sversion.ini (sversionrc),
            if any. The former overrule the latter

        */
        ConnectionSettings(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rRuntimeOverrides );

        /// merge the given overrides into a new ConnectionSettings object
        ConnectionSettings& mergeOverrides(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides);

        /// merge the given overrides into the object itself
        ConnectionSettings createMergedSettings(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides) const
        {
            return ConnectionSettings(*this).mergeOverrides(_rOverrides);
        }

        // check setting existence
        sal_Bool            hasRegistry() const { return m_bFoundRegistry; }
        sal_Bool            hasUser() const;
        sal_Bool            hasPassword() const;
        sal_Bool            hasLocale() const;
        sal_Bool            hasAsyncSetting() const;
        sal_Bool            hasServer() const;
        sal_Bool            hasPort() const;
        sal_Bool            hasTimeout() const;
        sal_Bool            hasService() const;

        sal_Bool            isLocalSession() const;
        sal_Bool            isRemoteSession() const;

        sal_Bool            isValidSourcePath() const;
        sal_Bool            isValidUpdatePath() const;

        // get a special setting
        ::rtl::OUString     getSessionType() const;
        ::rtl::OUString     getUser() const;
        ::rtl::OUString     getPassword() const;
        ::rtl::OUString     getLocale() const;
        ::rtl::OUString     getSourcePath() const;
        ::rtl::OUString     getUpdatePath() const;
        ::rtl::OUString     getServer() const;
        ::rtl::OUString     getService() const;
        sal_Int32           getPort() const;
        sal_Int32           getTimeout() const;
        sal_Bool            getAsyncSetting() const;

        // make sure this behaves as a user session
        void setUserSession();
        void setUserSession(const ::rtl::OUString& _rRemoteServiceName);

        // make sure this behaves as an administrative session
        void setAdminSession();
        void setAdminSession(const ::rtl::OUString& _rRemoteServiceName);

        // set a new session type. Must be one of the *_SESSION_IDENTIFIER defines
        void                setSessionType(const ::rtl::OUString& _rSessionIdentifier);
        // set a desired service, only necessary in remote environments
        sal_Bool            isServiceRequired() const;
        void                setService(const ::rtl::OUString& _rService);

        // set this to a wildcard locale
        void                setAnyLocale();

        IConfigSession* ConnectionSettings::createConnection(
            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > const& _rxServiceMgr) const;

    protected:
        void construct(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides);

        // transfer runtime overwrites into m_aImpl. Existent settings will be overwritten.
        void implTranslate(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rOverrides)
            throw (::com::sun::star::lang::IllegalArgumentException);

        /** normalize a path setting, delete it if the value could not be normalized
            @return <TRUE/> if the setting exists and is a valid path
        */
        sal_Bool implNormalizePathSetting(const sal_Char* _pSetting);

        // translate old settings, which exist for compatiblity only, into new ones
        void implTranslateCompatibilitySettings();

        // if we do not already have the given config path setting, ensure that it exists (calculated relative to a given path)
        void ensureConfigPath(const sal_Char* _pSetting, const ::rtl::OUString& _rBasePath, const sal_Char* _pRelative);

        sal_Bool        haveSetting(const sal_Char* _pName) const;
        void            putSetting(const sal_Char* _pName, const Setting& _rSetting);
        void            clearSetting(const sal_Char* _pName);

        ::rtl::OUString getStringSetting(const sal_Char* _pName) const;
        sal_Int32       getIntSetting(const sal_Char* _pName) const;
        sal_Bool        getBoolSetting(const sal_Char* _pName) const;
        Setting         getSetting(const sal_Char* _pName) const;
        Setting         getMaybeSetting(const sal_Char* _pName) const;

        ::rtl::OUString getProfileStringItem(const sal_Char* _pSection, const sal_Char* _pKey);
        sal_Int32       getProfileIntItem(const sal_Char* _pSection, const sal_Char* _pKey);

    private:
        // ensures that m_aImpl contains a session type
        // to be called from within construct only
        void implDetermineSessionType();

        // collect settings from the sregistry, put them into m_aImpl, if not overruled by runtime settings
        void implCollectSRegistrySetting();

        // clear items which are not relevant because of the session type origin
        void clearIrrelevantItems();
    };
}

#endif // CONFIGMGR_BOOTSTRAP_HXX_

<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

/*!
 * \file
 * \brief Contains forward declarations and using declarations for
 * the various value types.
 */

#pragma once

#include <cstddef>
#include "cpp_utils/array_wrapper.hpp"
#include "cpp_utils/aligned_vector.hpp"
#include "cpp_utils/aligned_array.hpp"

namespace etl {

template <typename T>
static constexpr size_t alloc_size_vec(size_t size) {
    return padding
        ? size + (size % default_intrinsic_traits<T>::size == 0 ? 0 : (default_intrinsic_traits<T>::size - (size % default_intrinsic_traits<T>::size)))
        : size;
}

#ifdef ETL_ADVANCED_PADDING

template <typename T>
static constexpr size_t alloc_size_mat(size_t size, size_t last) {
    return size == 0 ? 0 :
        (padding
        ? (size / last) * (last + (last % default_intrinsic_traits<T>::size == 0 ? 0 : (default_intrinsic_traits<T>::size - last % default_intrinsic_traits<T>::size)))
        : size);
}

#else

template <typename T>
static constexpr size_t alloc_size_mat(size_t size, size_t /*last*/) {
    return size == 0 ? 0 : alloc_size_vec<T>(size);
}

#endif

template <typename T, size_t... Dims>
static constexpr size_t alloc_size_mat() {
    return alloc_size_mat<T>(mul_all<Dims...>(), nth_size<sizeof...(Dims) - 1, 0, Dims...>::value);
}

template <typename T, typename ST, order SO, size_t... Dims>
struct fast_matrix_impl;

template <typename T, typename ST, order SO, size_t... Dims>
struct custom_fast_matrix_impl;

template <typename T, order SO, size_t D = 2>
struct dyn_matrix_impl;

template <typename T, order SO, size_t D = 2>
struct custom_dyn_matrix_impl;

template <typename T, sparse_storage SS, size_t D>
struct sparse_matrix_impl;

template <typename Stream>
struct serializer;

template <typename Stream>
struct deserializer;

/*!
 * \brief Symmetric matrix adapter
 * \tparam Matrix The adapted matrix
 */
template <typename Matrix>
struct symmetric_matrix;

/*!
 * \brief Hermitian matrix adapter
 * \tparam Matrix The adapted matrix
 */
template <typename Matrix>
struct hermitian_matrix;

/*!
 * \brief Diagonal matrix adapter
 * \tparam Matrix The adapted matrix
 */
template <typename Matrix>
struct diagonal_matrix;

/*!
 * \brief Upper triangular matrix adapter
 * \tparam Matrix The adapted matrix
 */
template <typename Matrix>
struct upper_matrix;

/*!
 * \brief Strictly upper triangular matrix adapter
 * \tparam Matrix The adapted matrix
 */
template <typename Matrix>
struct strictly_upper_matrix;

/*!
 * \brief Uni upper triangular matrix adapter
 * \tparam Matrix The adapted matrix
 */
template <typename Matrix>
struct uni_upper_matrix;

/*!
 * \brief Lower triangular matrix adapter
 * \tparam Matrix The adapted matrix
 */
template <typename Matrix>
struct lower_matrix;

/*!
 * \brief Strictly lower triangular matrix adapter
 * \tparam Matrix The adapted matrix
 */
template <typename Matrix>
struct strictly_lower_matrix;

/*!
 * \brief Uni lower triangular matrix adapter
 * \tparam Matrix The adapted matrix
 */
template <typename Matrix>
struct uni_lower_matrix;

/*!
 * \brief A static matrix with fixed dimensions, in row-major order
 */
template <typename T, size_t... Dims>
using fast_matrix = fast_matrix_impl<T, cpp::aligned_array<T, alloc_size_mat<T, Dims...>(), default_intrinsic_traits<T>::alignment>, order::RowMajor, Dims...>;

/*!
 * \brief A static matrix with fixed dimensions, in column-major order
 */
template <typename T, size_t... Dims>
using fast_matrix_cm = fast_matrix_impl<T, cpp::aligned_array<T, alloc_size_mat<T, Dims...>(), default_intrinsic_traits<T>::alignment>, order::ColumnMajor, Dims...>;

/*!
 * \brief A static vector with fixed dimensions, in row-major order
 */
template <typename T, size_t Rows>
using fast_vector = fast_matrix_impl<T, cpp::aligned_array<T, alloc_size_vec<T>(Rows), default_intrinsic_traits<T>::alignment>, order::RowMajor, Rows>;

/*!
 * \brief A static vector with fixed dimensions, in column-major order
 */
template <typename T, size_t Rows>
using fast_vector_cm = fast_matrix_impl<T, cpp::aligned_array<T, alloc_size_vec<T>(Rows), default_intrinsic_traits<T>::alignment>, order::ColumnMajor, Rows>;

/*!
 * \brief A hybrid vector with fixed dimensions, in row-major order
 */
template <typename T, size_t Rows>
using fast_dyn_vector = fast_matrix_impl<T, cpp::aligned_vector<T, default_intrinsic_traits<T>::alignment>, order::RowMajor, Rows>;

/*!
 * \brief A hybrid matrix with fixed dimensions, in row-major order
 */
template <typename T, size_t... Dims>
using fast_dyn_matrix = fast_matrix_impl<T, cpp::aligned_vector<T, default_intrinsic_traits<T>::alignment>, order::RowMajor, Dims...>;

/*!
 * \brief A dynamic matrix, in row-major order, of D dimensions
 */
template <typename T, size_t D = 2>
using dyn_matrix                    = dyn_matrix_impl<T, order::RowMajor, D>;

/*!
 * \brief A dynamic matrix, in column-major order, of D dimensions
 */
template <typename T, size_t D = 2>
using dyn_matrix_cm                 = dyn_matrix_impl<T, order::ColumnMajor, D>;

/*!
 * \brief A dynamic vector, in row-major order
 */
template <typename T>
using dyn_vector = dyn_matrix_impl<T, order::RowMajor, 1>;

/*!
 * \brief A dynamic matrix, in row-major order, of D dimensions
 */
template <typename T, size_t D = 2>
using custom_dyn_matrix                    = custom_dyn_matrix_impl<T, order::RowMajor, D>;

/*!
 * \brief A dynamic matrix, in column-major order, of D dimensions
 */
template <typename T, size_t D = 2>
using custom_dyn_matrix_cm                 = custom_dyn_matrix_impl<T, order::ColumnMajor, D>;

/*!
 * \brief A dynamic vector, in row-major order
 */
template <typename T>
using custom_dyn_vector = custom_dyn_matrix_impl<T, order::RowMajor, 1>;

/*!
 * \brief A hybrid vector with fixed dimensions, in row-major order
 */
template <typename T, size_t Rows>
using custom_fast_vector = custom_fast_matrix_impl<T, cpp::array_wrapper<T>, order::RowMajor, Rows>;

/*!
 * \brief A hybrid matrix with fixed dimensions, in row-major order
 */
template <typename T, size_t... Dims>
using custom_fast_matrix = custom_fast_matrix_impl<T, cpp::array_wrapper<T>, order::RowMajor, Dims...>;

/*!
 * \brief A sparse matrix, of D dimensions
 */
template <typename T, size_t D = 2>
using sparse_matrix                 = sparse_matrix_impl<T, sparse_storage::COO, D>;

} //end of namespace etl
<commit_msg>New helpers dyn_matrix_o / fast_dyn_matrix_o<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

/*!
 * \file
 * \brief Contains forward declarations and using declarations for
 * the various value types.
 */

#pragma once

#include <cstddef>
#include "cpp_utils/array_wrapper.hpp"
#include "cpp_utils/aligned_vector.hpp"
#include "cpp_utils/aligned_array.hpp"

namespace etl {

template <typename T>
static constexpr size_t alloc_size_vec(size_t size) {
    return padding
        ? size + (size % default_intrinsic_traits<T>::size == 0 ? 0 : (default_intrinsic_traits<T>::size - (size % default_intrinsic_traits<T>::size)))
        : size;
}

#ifdef ETL_ADVANCED_PADDING

template <typename T>
static constexpr size_t alloc_size_mat(size_t size, size_t last) {
    return size == 0 ? 0 :
        (padding
        ? (size / last) * (last + (last % default_intrinsic_traits<T>::size == 0 ? 0 : (default_intrinsic_traits<T>::size - last % default_intrinsic_traits<T>::size)))
        : size);
}

#else

template <typename T>
static constexpr size_t alloc_size_mat(size_t size, size_t /*last*/) {
    return size == 0 ? 0 : alloc_size_vec<T>(size);
}

#endif

template <typename T, size_t... Dims>
static constexpr size_t alloc_size_mat() {
    return alloc_size_mat<T>(mul_all<Dims...>(), nth_size<sizeof...(Dims) - 1, 0, Dims...>::value);
}

template <typename T, typename ST, order SO, size_t... Dims>
struct fast_matrix_impl;

template <typename T, typename ST, order SO, size_t... Dims>
struct custom_fast_matrix_impl;

template <typename T, order SO, size_t D = 2>
struct dyn_matrix_impl;

template <typename T, order SO, size_t D = 2>
struct custom_dyn_matrix_impl;

template <typename T, sparse_storage SS, size_t D>
struct sparse_matrix_impl;

template <typename Stream>
struct serializer;

template <typename Stream>
struct deserializer;

/*!
 * \brief Symmetric matrix adapter
 * \tparam Matrix The adapted matrix
 */
template <typename Matrix>
struct symmetric_matrix;

/*!
 * \brief Hermitian matrix adapter
 * \tparam Matrix The adapted matrix
 */
template <typename Matrix>
struct hermitian_matrix;

/*!
 * \brief Diagonal matrix adapter
 * \tparam Matrix The adapted matrix
 */
template <typename Matrix>
struct diagonal_matrix;

/*!
 * \brief Upper triangular matrix adapter
 * \tparam Matrix The adapted matrix
 */
template <typename Matrix>
struct upper_matrix;

/*!
 * \brief Strictly upper triangular matrix adapter
 * \tparam Matrix The adapted matrix
 */
template <typename Matrix>
struct strictly_upper_matrix;

/*!
 * \brief Uni upper triangular matrix adapter
 * \tparam Matrix The adapted matrix
 */
template <typename Matrix>
struct uni_upper_matrix;

/*!
 * \brief Lower triangular matrix adapter
 * \tparam Matrix The adapted matrix
 */
template <typename Matrix>
struct lower_matrix;

/*!
 * \brief Strictly lower triangular matrix adapter
 * \tparam Matrix The adapted matrix
 */
template <typename Matrix>
struct strictly_lower_matrix;

/*!
 * \brief Uni lower triangular matrix adapter
 * \tparam Matrix The adapted matrix
 */
template <typename Matrix>
struct uni_lower_matrix;

/*!
 * \brief A static matrix with fixed dimensions, in row-major order
 */
template <typename T, size_t... Dims>
using fast_matrix = fast_matrix_impl<T, cpp::aligned_array<T, alloc_size_mat<T, Dims...>(), default_intrinsic_traits<T>::alignment>, order::RowMajor, Dims...>;

/*!
 * \brief A static matrix with fixed dimensions, in column-major order
 */
template <typename T, size_t... Dims>
using fast_matrix_cm = fast_matrix_impl<T, cpp::aligned_array<T, alloc_size_mat<T, Dims...>(), default_intrinsic_traits<T>::alignment>, order::ColumnMajor, Dims...>;

/*!
 * \brief A static vector with fixed dimensions, in row-major order
 */
template <typename T, size_t Rows>
using fast_vector = fast_matrix_impl<T, cpp::aligned_array<T, alloc_size_vec<T>(Rows), default_intrinsic_traits<T>::alignment>, order::RowMajor, Rows>;

/*!
 * \brief A static vector with fixed dimensions, in column-major order
 */
template <typename T, size_t Rows>
using fast_vector_cm = fast_matrix_impl<T, cpp::aligned_array<T, alloc_size_vec<T>(Rows), default_intrinsic_traits<T>::alignment>, order::ColumnMajor, Rows>;

/*!
 * \brief A hybrid vector with fixed dimensions, in row-major order
 */
template <typename T, size_t Rows>
using fast_dyn_vector = fast_matrix_impl<T, cpp::aligned_vector<T, default_intrinsic_traits<T>::alignment>, order::RowMajor, Rows>;

/*!
 * \brief A hybrid matrix with fixed dimensions, in row-major order
 */
template <typename T, size_t... Dims>
using fast_dyn_matrix = fast_matrix_impl<T, cpp::aligned_vector<T, default_intrinsic_traits<T>::alignment>, order::RowMajor, Dims...>;

/*!
 * \brief A hybrid matrix with fixed dimensions, in specified  order
 */
template <typename T, order SO, size_t... Dims>
using fast_dyn_matrix_o = fast_matrix_impl<T, cpp::aligned_vector<T, default_intrinsic_traits<T>::alignment>, SO, Dims...>;

/*!
 * \brief A dynamic matrix, in row-major order, of D dimensions
 */
template <typename T, size_t D = 2>
using dyn_matrix = dyn_matrix_impl<T, order::RowMajor, D>;

/*!
 * \brief A dynamic matrix, in column-major order, of D dimensions
 */
template <typename T, size_t D = 2>
using dyn_matrix_cm = dyn_matrix_impl<T, order::ColumnMajor, D>;

/*!
 * \brief A dynamic matrix, in specific storage order, of D dimensions
 */
template <typename T, order SO, size_t D = 2>
using dyn_matrix_o = dyn_matrix_impl<T, SO, D>;

/*!
 * \brief A dynamic vector, in row-major order
 */
template <typename T>
using dyn_vector = dyn_matrix_impl<T, order::RowMajor, 1>;

/*!
 * \brief A dynamic matrix, in row-major order, of D dimensions
 */
template <typename T, size_t D = 2>
using custom_dyn_matrix                    = custom_dyn_matrix_impl<T, order::RowMajor, D>;

/*!
 * \brief A dynamic matrix, in column-major order, of D dimensions
 */
template <typename T, size_t D = 2>
using custom_dyn_matrix_cm                 = custom_dyn_matrix_impl<T, order::ColumnMajor, D>;

/*!
 * \brief A dynamic vector, in row-major order
 */
template <typename T>
using custom_dyn_vector = custom_dyn_matrix_impl<T, order::RowMajor, 1>;

/*!
 * \brief A hybrid vector with fixed dimensions, in row-major order
 */
template <typename T, size_t Rows>
using custom_fast_vector = custom_fast_matrix_impl<T, cpp::array_wrapper<T>, order::RowMajor, Rows>;

/*!
 * \brief A hybrid matrix with fixed dimensions, in row-major order
 */
template <typename T, size_t... Dims>
using custom_fast_matrix = custom_fast_matrix_impl<T, cpp::array_wrapper<T>, order::RowMajor, Dims...>;

/*!
 * \brief A sparse matrix, of D dimensions
 */
template <typename T, size_t D = 2>
using sparse_matrix                 = sparse_matrix_impl<T, sparse_storage::COO, D>;

} //end of namespace etl
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
// Jikken - 3D Abstract High Performance Graphics API
// Copyright(c) 2017 Jeff Hutchinson
// Copyright(c) 2017 Tim Barnes
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//-----------------------------------------------------------------------------

#ifndef _JIKKEN_MEMORY_HPP_
#define _JIKKEN_MEMORY_HPP_

#include <cstdint>
#include <vector>

namespace Jikken
{
	/// A custom memory allocator that operates as if it was on a stack.
	/// Once free() is called, all memory is considered to be reset.
	class PerFrameMemoryPool
	{
		const size_t PAGE_SIZE = 2048;
	public:
		PerFrameMemoryPool()
		{
			// Allocate a page of memory.
			mMemory.push_back(new uint8_t[PAGE_SIZE]);
			mCurrentPtr = 0;
			mCurrentPage = 0;
		}

		~PerFrameMemoryPool()
		{
			// Deallocate page
			for (auto mem : mMemory)
			{
				delete[] mem;
				mem = nullptr;
			}
		}

		template<class T>
		T* malloc()
		{
			size_t size = sizeof(T);
			if (size + mCurrentPtr >= PAGE_SIZE)
			{
				// See if we already have a page allocated.
				// If we do, we're golden. If not, just alloc another page!
				mCurrentPage++;
				if (mMemory.size() == mCurrentPage)
					mMemory.push_back(new uint8_t[PAGE_SIZE]);
				mCurrentPtr = 0;
			}

			T *obj = reinterpret_cast<T*>(mMemory[mCurrentPage] + mCurrentPtr);
			mCurrentPtr += size;

			// Note the use of placement new. It doesn't do any
			// allocation. It just calls the constructor of our
			// already allocated object.
			return new(obj) T();
		}

		void free()
		{
			// Reset the stack.
			mCurrentPtr = 0;
			mCurrentPage = 0;
		}

	private:
		std::vector<uint8_t *> mMemory;
		uint32_t mCurrentPtr;
		uint32_t mCurrentPage;
	};
}

#endif<commit_msg>implement a linked list for the memory manager for pages instead of having extra overhead of a vector.<commit_after>//-----------------------------------------------------------------------------
// Jikken - 3D Abstract High Performance Graphics API
// Copyright(c) 2017 Jeff Hutchinson
// Copyright(c) 2017 Tim Barnes
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//-----------------------------------------------------------------------------

#ifndef _JIKKEN_MEMORY_HPP_
#define _JIKKEN_MEMORY_HPP_

#include <cstdint>
#include <vector>

namespace Jikken
{
	/// A custom memory allocator that operates as if it was on a stack.
	/// Once a page fills up within the pool, a new page is generated.
	/// Page references to the next page are stored as the last
	/// sizeof(uintptr_t) bytes on the current page.
	/// Once free() is called, all memory is considered to be reset.
	class PerFrameMemoryPool
	{
	public:
		const size_t PAGE_SIZE = 2048;

		const size_t PAGE_OFFSET = PAGE_SIZE - 1 - sizeof(uintptr_t);

		/// Gets the pointer to the next page of memory in the pool.
		/// @param page The memory page we are checking.
		/// @return a pointer to the next page, or 0x0 if one does not eixst.
	private:
		inline uintptr_t* getNextPageOffset(uintptr_t *page)
		{
			return &page[PAGE_OFFSET];
		}

	public:
		PerFrameMemoryPool()
		{
			// Allocate a page of memory.
			mMemory = new uint8_t[PAGE_SIZE];

			// The last bytes will hold a pointer to the next page of memory we will
			// allocate. Since we only want 1 page for now, just store 0x0
			memset(getNextPageOffset(reinterpret_cast<uintptr_t*>(mMemory)), 0, sizeof(size_t));

			// Offset within our current page.
			mCurrentPtr = 0;

			// Pointer to our current page
			mCurrentPage = reinterpret_cast<uintptr_t*>(mMemory);
		}

		~PerFrameMemoryPool()
		{
			// First we have to bulid the list of pages that we have to free.
			std::vector<uintptr_t*> pages;
			uintptr_t *page = reinterpret_cast<uintptr_t*>(&mMemory[0]);
			while (page != nullptr)
			{
				pages.push_back(page);
				page = getNextPageOffset(page);
			}

			// Now that we have our list of pages, we can free them.
			for (uintptr_t *mem : pages)
			{
				delete[] mem;
			}
		}

		template<class T>
		T* malloc()
		{
			size_t size = sizeof(T);
			if (size + mCurrentPtr >= PAGE_OFFSET)
			{
				// See if we already have a page allocated.
				// If we do, we're golden. If not, just alloc another page!
				uintptr_t *next = getNextPageOffset(mCurrentPage);
				if (next == nullptr)
				{
					// Alloc new page.
					uint8_t *page = new uint8_t[PAGE_SIZE];

					// Assign the current page's next page ptr to this page.
					getNextPageOffset(mCurrentPage) = page;

					// The last bytes will hold a pointer to the next page of memory we will
					// allocate. Set it to null since we are only allocating 1 page at a time.
					memset(getNextPageOffset(reinterpret_cast<uintptr_t*>(page)), 0, sizeof(size_t));

					// Set current page
					mCurrentPage = page;
				}
				else
				{
					// we already have a page allocated
					mCurrentPage = next;
				}

				// reset current offset of new page to beginning.
				mCurrentPtr = 0;
			}

			T *obj = reinterpret_cast<T*>(mCurrentPage + mCurrentPtr);
			mCurrentPtr += size;

			// Note the use of placement new. It doesn't do any
			// allocation. It just calls the constructor of our
			// already allocated object.
			return new(obj) T();
		}

		void free()
		{
			// Reset the stack.
			mCurrentPtr = 0;
			mCurrentPage = reinterpret_cast<uintptr_t*>(mMemory);
		}

		uint8_t* getCommandQueuePtr() const
		{
			return mMemory;
		}

	private:
		uint8_t *mMemory;
		uint32_t mCurrentPtr;
		uintptr_t *mCurrentPage;
	};
}

#endif<|endoftext|>