<commit_before>
#include "ofConstants.h"
#include "ofSystemUtils.h"
#include "ofFileUtils.h"

#ifdef TARGET_WIN32
#include <winuser.h>
#include <commdlg.h>
#define _WIN32_DCOM

#include <windows.h>
#include <shlobj.h>
#include <tchar.h>
#include <stdio.h>

#endif

#ifdef TARGET_OSX
	#include <sys/param.h> // for MAXPATHLEN
#endif

//------------------------------------------------------------------------------
ofFileDialogResult::ofFileDialogResult(){
	filePath = "";
	fileName = "";
	bSuccess = false;
}

//------------------------------------------------------------------------------
string ofFileDialogResult::getName(){
	return fileName;
}

//------------------------------------------------------------------------------
string ofFileDialogResult::getPath(){
	return filePath;
}

//------------------------------------------------------------------------------
void ofCreateAlertDialog(string errorMessage){

	#ifdef TARGET_WIN32
		MessageBox(NULL, LPWSTR(errorMessage.c_str()), L"Critical Error", MB_OK | MB_ICONERROR);
	#endif

	#ifdef TARGET_OSX
		CFStringRef msgStrRef = CFStringCreateWithCString(NULL, errorMessage.c_str(), kCFStringEncodingASCII);
		DialogRef theItem;
		DialogItemIndex itemIndex;
		CreateStandardAlert(kAlertNoteAlert, msgStrRef, NULL, NULL, &theItem);
		RunStandardAlert(theItem, NULL, &itemIndex);
	#endif

}

//----------------------------------------------------------------------------------------
//------------------------------------------------------------------------------       OSX
//----------------------------------------------------------------------------------------
#ifdef TARGET_OSX
//---------------------------------------------------------------------
// Gets a file to open from the user. Caller must release the CFURLRef.
CFURLRef GetOpenFileFromUser(bool bFolder)
{
	NavDialogCreationOptions dialogOptions;
	NavDialogRef dialog;
	NavReplyRecord replyRecord;
	CFURLRef fileAsCFURLRef = NULL;
	FSRef fileAsFSRef;
	OSStatus status;

	// Get the standard set of defaults
	status = NavGetDefaultDialogCreationOptions(&dialogOptions);

	require_noerr( status, CantGetNavOptions );

	// Make the window app-wide modal
	dialogOptions.modality = kWindowModalityAppModal;
	dialogOptions.optionFlags != kNavAllowOpenPackages;

	// Create the dialog
	if( bFolder ){
		status = NavCreateChooseFolderDialog(&dialogOptions, NULL, NULL, NULL, &dialog);
	}else{
		status = NavCreateGetFileDialog(&dialogOptions, NULL, NULL, NULL, NULL, NULL, &dialog);
	}

	require_noerr( status, CantCreateDialog );

	// Show it
	status = NavDialogRun(dialog);
	require_noerr( status, CantRunDialog );

	// Get the reply
	status = NavDialogGetReply(dialog, &replyRecord);
	require( ((status == noErr) || (status == userCanceledErr)), CantGetReply );

	// If the user clicked "Cancel", just bail
	if ( status == userCanceledErr ) goto UserCanceled;

	// Get the file
	//TODO: for multiple files - 1 specifies index
	status = AEGetNthPtr(&(replyRecord.selection), 1, typeFSRef, NULL, NULL, &fileAsFSRef, sizeof(FSRef), NULL);
	require_noerr( status, CantExtractFSRef );

	// Convert it to a CFURL
	fileAsCFURLRef = CFURLCreateFromFSRef(NULL, &fileAsFSRef);

	// Cleanup
CantExtractFSRef:
UserCanceled:
	verify_noerr( NavDisposeReply(&replyRecord) );
CantGetReply:
CantRunDialog:
	NavDialogDispose(dialog);
CantCreateDialog:
CantGetNavOptions:
    return fileAsCFURLRef;
}
#endif TARGET_OSX
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------

// OS specific results here.  "" = cancel or something bad like can't load, can't save, etc...
ofFileDialogResult ofFileLoadDialog(bool bFolderSelection){

	ofFileDialogResult results;

	//----------------------------------------------------------------------------------------
	//------------------------------------------------------------------------------       OSX
	//----------------------------------------------------------------------------------------
#ifdef TARGET_OSX
	CFURLRef cfUrl = GetOpenFileFromUser(bFolderSelection);

	CFStringRef cfString = NULL;

	if ( cfUrl != NULL ){
		cfString = CFURLCopyFileSystemPath( cfUrl, kCFURLPOSIXPathStyle );
		CFRelease( cfUrl );

		// copy from a CFString into a local c string (http://www.carbondev.com/site/?page=CStrings+)
		const int kBufferSize = MAXPATHLEN;

		char fileUrl[kBufferSize];
		Boolean bool1 = CFStringGetCString(cfString,fileUrl,kBufferSize,kCFStringEncodingMacRoman);

		//char fileName[kBufferSize];
		//Boolean bool2 = CFStringGetCString(reply.saveFileName,fileName,kBufferSize,kCFStringEncodingMacRoman);

		// append strings together

		results.filePath = fileUrl;
	}

#endif
	//----------------------------------------------------------------------------------------
	//----------------------------------------------------------------------------------------
	//----------------------------------------------------------------------------------------

	//----------------------------------------------------------------------------------------
	//------------------------------------------------------------------------------   windoze
	//----------------------------------------------------------------------------------------
#ifdef TARGET_WIN32

	// TODO pc file choose dialog is now mega broken, please fix!

	char szFileName[MAX_PATH] = "";

	OPENFILENAME ofn;
	ZeroMemory(&ofn, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
	HWND hwnd = WindowFromDC(wglGetCurrentDC());
	ofn.hwndOwner = hwnd;
	ofn.lpstrFilter = _T("All Files (*.*)\0*.*\0");
	ofn.lpstrFile = LPWSTR(szFileName);
	ofn.nMaxFile = MAX_PATH;
	ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
	ofn.lpstrDefExt = 0;

	if(GetOpenFileName(&ofn)) {
		//printf("GetOpenFileName worked, got %s \n", szFileName);
		results.filePath = string(szFileName);
	}

	BROWSEINFO      bi;
	char            pszBuffer[MAX_PATH];
	LPITEMIDLIST    pidl;
	LPMALLOC		lpMalloc;

	// Get a pointer to the shell memory allocator
	if(SHGetMalloc(&lpMalloc) != S_OK)
	{
		MessageBox(NULL,_T("Error opening browse window"),_T("ERROR"),MB_OK);
		//CoUninitialize();
		//return 0;
	}

	bi.hwndOwner        =   NULL;
	bi.pidlRoot         =   NULL;
	bi.pszDisplayName   =   LPWSTR(pszBuffer);
	bi.lpszTitle        =   _T("Select a install Directory");
	bi.ulFlags          =   BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
	bi.lpfn             =   NULL;
	bi.lParam           =   0;

	if(pidl = SHBrowseForFolder(&bi))
	{
		// Copy the path directory to the buffer
		if(SHGetPathFromIDList(pidl,LPWSTR(pszBuffer)))
		{
			// pszBuffer now holds the directory path
			printf("You selected the directory: %s\n",pszBuffer);
		}

		lpMalloc->Free(pidl);
	}
	lpMalloc->Release();
	//----------------------------------------------------------------------------------------
	//------------------------------------------------------------------------------   windoze
	//----------------------------------------------------------------------------------------
#endif

	if( results.filePath.length() > 0 ){
		results.bSuccess = true;
		results.fileName = ofFileUtils::getFilenameFromPath(results.filePath);
	}

	return results;
}

ofFileDialogResult ofFileSaveDialog(string defaultName, string messageName){

	ofFileDialogResult results;

	//----------------------------------------------------------------------------------------
	//------------------------------------------------------------------------------       OSX
	//----------------------------------------------------------------------------------------
#ifdef TARGET_OSX

	short fRefNumOut;
	FSRef output_file;
	OSStatus err;

	NavDialogCreationOptions options;
	NavGetDefaultDialogCreationOptions( &options );

	options.optionFlags = kNavNoTypePopup + kNavSupportPackages + kNavAllowOpenPackages;
	options.modality = kWindowModalityAppModal;

	options.optionFlags = kNavDefaultNavDlogOptions;
	options.message = CFStringCreateWithCString(NULL, messageName.c_str(), kCFStringEncodingASCII);;
	options.saveFileName = CFStringCreateWithCString(NULL, defaultName.c_str(), kCFStringEncodingASCII);
	NavDialogRef dialog;

	err = NavCreatePutFileDialog(&options, '.mov', 'Moov', NULL, NULL, &dialog);

	//printf("NavCreatePutFileDialog returned %i\n", err );

	err = NavDialogRun(dialog);
	//printf("NavDialogRun returned %i\n", err );

	NavUserAction action;
	action = NavDialogGetUserAction( dialog );
	//printf("got action %i\n", action);
	if (action == kNavUserActionNone || action == kNavUserActionCancel) {

		return results;
	}

	// get dialog reply
	NavReplyRecord reply;
	err = NavDialogGetReply(dialog, &reply);
	if ( err != noErr )
		return results;

	if ( reply.replacing )
	{
		printf("need to replace\n");
	}

	AEKeyword keyword;
	DescType actual_type;
	Size actual_size;
	FSRef output_dir;
	err = AEGetNthPtr(&(reply.selection), 1, typeFSRef, &keyword, &actual_type,
					  &output_dir, sizeof(output_file), &actual_size);

	//printf("AEGetNthPtr returned %i\n", err );

	CFURLRef cfUrl = CFURLCreateFromFSRef( kCFAllocatorDefault, &output_dir );
	CFStringRef cfString = NULL;
	if ( cfUrl != NULL )
	{
		cfString = CFURLCopyFileSystemPath( cfUrl, kCFURLPOSIXPathStyle );
		CFRelease( cfUrl );
	}

	// copy from a CFString into a local c string (http://www.carbondev.com/site/?page=CStrings+)
	const int kBufferSize = 255;

	char folderURL[kBufferSize];
	Boolean bool1 = CFStringGetCString(cfString,folderURL,kBufferSize,kCFStringEncodingMacRoman);

	char fileName[kBufferSize];
	Boolean bool2 = CFStringGetCString(reply.saveFileName,fileName,kBufferSize,kCFStringEncodingMacRoman);

	// append strings together

	string url1 = folderURL;
	string url2 = fileName;
	string finalURL = url1 + "/" + url2;

	results.filePath = finalURL.c_str();

	//printf("url %s\n", finalURL.c_str());

	// cleanup dialog
	NavDialogDispose(dialog);

#endif
	//----------------------------------------------------------------------------------------
	//----------------------------------------------------------------------------------------
	//----------------------------------------------------------------------------------------

	//----------------------------------------------------------------------------------------
	//------------------------------------------------------------------------------   windoze
	//----------------------------------------------------------------------------------------
#ifdef TARGET_WIN32

	char fileName[260] = {0};
	fileName[0] = 0;
	static char info_fn[_MAX_PATH];		// hmmm what is this for?
	char *extension;
	OPENFILENAME ofn;

	//lstrcpy(fileName, info_fn);
	//extension = strrchr(fileName, '.');
	//lstrcpy(extension, ".mp4");
	//
    memset(&ofn, 0, sizeof(OPENFILENAME));
	ofn.lStructSize = sizeof(OPENFILENAME);
	HWND hwnd = WindowFromDC(wglGetCurrentDC());
	ofn.hwndOwner = hwnd;
	ofn.hInstance = GetModuleHandle(0);
	ofn.nMaxFileTitle = 31;
	ofn.lpstrFile = LPWSTR(fileName);
	ofn.nMaxFile = _MAX_PATH;
	ofn.lpstrFilter = _T("All Files (*.*)\0*.*\0");
	ofn.lpstrDefExt = _T("");	// we could do .rxml here?
	ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY;
	ofn.lpstrTitle = _T("Select Output File");
	//

	if (GetSaveFileName(&ofn))
	{
		//#error this needs checking on windows - what is the filePath.erase(0,1)
	    results.filePath = string(info_fn) + "/" + string(fileName);
		if (results.filePath.length() > 1) results.filePath.erase(0,1);
        cout << "GetSaveFileName worked, got " << results.filePath << endl;
	}
#endif
	//----------------------------------------------------------------------------------------
	//----------------------------------------------------------------------------------------
	//----------------------------------------------------------------------------------------

	if( results.filePath.length() > 0 ){
		results.bSuccess = true;
		results.fileName = ofFileUtils::getFilenameFromPath(results.filePath);
	}

	return results;
}

<commit_msg>fixes for wchar_t issues on vs2010<commit_after>
#include "ofConstants.h"
#include "ofSystemUtils.h"
#include "ofFileUtils.h"

#ifdef TARGET_WIN32
#include <winuser.h>
#include <commdlg.h>
#define _WIN32_DCOM

#include <windows.h>
#include <shlobj.h>
#include <tchar.h>
#include <stdio.h>

#endif

#ifdef TARGET_OSX
	#include <sys/param.h> // for MAXPATHLEN
#endif

#ifdef TARGET_WIN32
#include <locale>
#include <sstream>
#include <string>

std::string convertWideToNarrow( const wchar_t *s, char dfault = '?',
                      const std::locale& loc = std::locale() )
{
  std::ostringstream stm;

  while( *s != L'\0' ) {
    stm << std::use_facet< std::ctype<wchar_t> >( loc ).narrow( *s++, dfault );
  }
  return stm.str();
}
#endif

//------------------------------------------------------------------------------
ofFileDialogResult::ofFileDialogResult(){
	filePath = "";
	fileName = "";
	bSuccess = false;
}

//------------------------------------------------------------------------------
string ofFileDialogResult::getName(){
	return fileName;
}

//------------------------------------------------------------------------------
string ofFileDialogResult::getPath(){
	return filePath;
}

//------------------------------------------------------------------------------
void ofCreateAlertDialog(string errorMessage){

	#ifdef TARGET_WIN32
		// we need to convert error message to a wide char message.
		// first, figure out the length and allocate a wchar_t at that length + 1 (the +1 is for a terminating character)
		int length = strlen(errorMessage.c_str());
		wchar_t * widearray = new wchar_t[length+1];
		memset(widearray, 0, sizeof(wchar_t)*(length+1));
		// then, call mbstowcs:
		// http://www.cplusplus.com/reference/clibrary/cstdlib/mbstowcs/
		mbstowcs(widearray, errorMessage.c_str(), length);
		// launch the alert:
		MessageBox(NULL, widearray, L"alert", MB_OK);
		// clear the allocated memory:
		delete widearray;
	#endif

	#ifdef TARGET_OSX
		CFStringRef msgStrRef = CFStringCreateWithCString(NULL, errorMessage.c_str(), kCFStringEncodingASCII);
		DialogRef theItem;
		DialogItemIndex itemIndex;
		CreateStandardAlert(kAlertNoteAlert, msgStrRef, NULL, NULL, &theItem);
		RunStandardAlert(theItem, NULL, &itemIndex);
	#endif

}

//----------------------------------------------------------------------------------------
//------------------------------------------------------------------------------       OSX
//----------------------------------------------------------------------------------------
#ifdef TARGET_OSX
//---------------------------------------------------------------------
// Gets a file to open from the user. Caller must release the CFURLRef.
CFURLRef GetOpenFileFromUser(bool bFolder)
{
	NavDialogCreationOptions dialogOptions;
	NavDialogRef dialog;
	NavReplyRecord replyRecord;
	CFURLRef fileAsCFURLRef = NULL;
	FSRef fileAsFSRef;
	OSStatus status;

	// Get the standard set of defaults
	status = NavGetDefaultDialogCreationOptions(&dialogOptions);

	require_noerr( status, CantGetNavOptions );

	// Make the window app-wide modal
	dialogOptions.modality = kWindowModalityAppModal;
	dialogOptions.optionFlags != kNavAllowOpenPackages;

	// Create the dialog
	if( bFolder ){
		status = NavCreateChooseFolderDialog(&dialogOptions, NULL, NULL, NULL, &dialog);
	}else{
		status = NavCreateGetFileDialog(&dialogOptions, NULL, NULL, NULL, NULL, NULL, &dialog);
	}

	require_noerr( status, CantCreateDialog );

	// Show it
	status = NavDialogRun(dialog);
	require_noerr( status, CantRunDialog );

	// Get the reply
	status = NavDialogGetReply(dialog, &replyRecord);
	require( ((status == noErr) || (status == userCanceledErr)), CantGetReply );

	// If the user clicked "Cancel", just bail
	if ( status == userCanceledErr ) goto UserCanceled;

	// Get the file
	//TODO: for multiple files - 1 specifies index
	status = AEGetNthPtr(&(replyRecord.selection), 1, typeFSRef, NULL, NULL, &fileAsFSRef, sizeof(FSRef), NULL);
	require_noerr( status, CantExtractFSRef );

	// Convert it to a CFURL
	fileAsCFURLRef = CFURLCreateFromFSRef(NULL, &fileAsFSRef);

	// Cleanup
CantExtractFSRef:
UserCanceled:
	verify_noerr( NavDisposeReply(&replyRecord) );
CantGetReply:
CantRunDialog:
	NavDialogDispose(dialog);
CantCreateDialog:
CantGetNavOptions:
    return fileAsCFURLRef;
}
#endif TARGET_OSX
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------

// OS specific results here.  "" = cancel or something bad like can't load, can't save, etc...
ofFileDialogResult ofFileLoadDialog(bool bFolderSelection){

	ofFileDialogResult results;

	//----------------------------------------------------------------------------------------
	//------------------------------------------------------------------------------       OSX
	//----------------------------------------------------------------------------------------
#ifdef TARGET_OSX
	CFURLRef cfUrl = GetOpenFileFromUser(bFolderSelection);

	CFStringRef cfString = NULL;

	if ( cfUrl != NULL ){
		cfString = CFURLCopyFileSystemPath( cfUrl, kCFURLPOSIXPathStyle );
		CFRelease( cfUrl );

		// copy from a CFString into a local c string (http://www.carbondev.com/site/?page=CStrings+)
		const int kBufferSize = MAXPATHLEN;

		char fileUrl[kBufferSize];
		Boolean bool1 = CFStringGetCString(cfString,fileUrl,kBufferSize,kCFStringEncodingMacRoman);

		//char fileName[kBufferSize];
		//Boolean bool2 = CFStringGetCString(reply.saveFileName,fileName,kBufferSize,kCFStringEncodingMacRoman);

		// append strings together

		results.filePath = fileUrl;
	}

#endif
	//----------------------------------------------------------------------------------------
	//----------------------------------------------------------------------------------------
	//----------------------------------------------------------------------------------------

	//----------------------------------------------------------------------------------------
	//------------------------------------------------------------------------------   windoze
	//----------------------------------------------------------------------------------------
#ifdef TARGET_WIN32

	// TODO pc file choose dialog is now mega broken, please fix!

	if (bFolderSelection == false){

		wchar_t szFileName[MAX_PATH] = L"";
		OPENFILENAME ofn;
		ZeroMemory(&ofn, sizeof(ofn));
		ofn.lStructSize = sizeof(ofn);
		HWND hwnd = WindowFromDC(wglGetCurrentDC());
		ofn.hwndOwner = hwnd;
		ofn.lpstrFilter = _T("All Files (*.*)\0*.*\0");
		ofn.lpstrFile = szFileName;
		ofn.nMaxFile = MAX_PATH;
		ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
		ofn.lpstrDefExt = 0;

		if(GetOpenFileName(&ofn)) {
			results.filePath = convertWideToNarrow(szFileName);
			// TODO: name conversion, please!!
		}

	} else {

		BROWSEINFO      bi;
		wchar_t         wideCharacterBuffer[MAX_PATH];
		LPITEMIDLIST    pidl;
		LPMALLOC		lpMalloc;

		// Get a pointer to the shell memory allocator
		if(SHGetMalloc(&lpMalloc) != S_OK){
			//TODO: deal with some sort of error here?
		}
		bi.hwndOwner        =   NULL;
		bi.pidlRoot         =   NULL;
		bi.pszDisplayName   =   wideCharacterBuffer;
		bi.lpszTitle        =   _T("Select Directory");
		bi.ulFlags          =   BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
		bi.lpfn             =   NULL;
		bi.lParam           =   0;

		if(pidl = SHBrowseForFolder(&bi)){
			// Copy the path directory to the buffer
			if(SHGetPathFromIDList(pidl,wideCharacterBuffer)){
				results.filePath = convertWideToNarrow(wideCharacterBuffer);
			}
			lpMalloc->Free(pidl);
		}
		lpMalloc->Release();
	}

	//----------------------------------------------------------------------------------------
	//------------------------------------------------------------------------------   windoze
	//----------------------------------------------------------------------------------------
#endif

	if( results.filePath.length() > 0 ){
		results.bSuccess = true;
		results.fileName = ofFileUtils::getFilenameFromPath(results.filePath);
	}

	return results;
}

ofFileDialogResult ofFileSaveDialog(string defaultName, string messageName){

	ofFileDialogResult results;

	//----------------------------------------------------------------------------------------
	//------------------------------------------------------------------------------       OSX
	//----------------------------------------------------------------------------------------
#ifdef TARGET_OSX

	short fRefNumOut;
	FSRef output_file;
	OSStatus err;

	NavDialogCreationOptions options;
	NavGetDefaultDialogCreationOptions( &options );

	options.optionFlags = kNavNoTypePopup + kNavSupportPackages + kNavAllowOpenPackages;
	options.modality = kWindowModalityAppModal;

	options.optionFlags = kNavDefaultNavDlogOptions;
	options.message = CFStringCreateWithCString(NULL, messageName.c_str(), kCFStringEncodingASCII);;
	options.saveFileName = CFStringCreateWithCString(NULL, defaultName.c_str(), kCFStringEncodingASCII);
	NavDialogRef dialog;

	err = NavCreatePutFileDialog(&options, '.mov', 'Moov', NULL, NULL, &dialog);

	//printf("NavCreatePutFileDialog returned %i\n", err );

	err = NavDialogRun(dialog);
	//printf("NavDialogRun returned %i\n", err );

	NavUserAction action;
	action = NavDialogGetUserAction( dialog );
	//printf("got action %i\n", action);
	if (action == kNavUserActionNone || action == kNavUserActionCancel) {

		return results;
	}

	// get dialog reply
	NavReplyRecord reply;
	err = NavDialogGetReply(dialog, &reply);
	if ( err != noErr )
		return results;

	if ( reply.replacing )
	{
		printf("need to replace\n");
	}

	AEKeyword keyword;
	DescType actual_type;
	Size actual_size;
	FSRef output_dir;
	err = AEGetNthPtr(&(reply.selection), 1, typeFSRef, &keyword, &actual_type,
					  &output_dir, sizeof(output_file), &actual_size);

	//printf("AEGetNthPtr returned %i\n", err );

	CFURLRef cfUrl = CFURLCreateFromFSRef( kCFAllocatorDefault, &output_dir );
	CFStringRef cfString = NULL;
	if ( cfUrl != NULL )
	{
		cfString = CFURLCopyFileSystemPath( cfUrl, kCFURLPOSIXPathStyle );
		CFRelease( cfUrl );
	}

	// copy from a CFString into a local c string (http://www.carbondev.com/site/?page=CStrings+)
	const int kBufferSize = 255;

	char folderURL[kBufferSize];
	Boolean bool1 = CFStringGetCString(cfString,folderURL,kBufferSize,kCFStringEncodingMacRoman);

	char fileName[kBufferSize];
	Boolean bool2 = CFStringGetCString(reply.saveFileName,fileName,kBufferSize,kCFStringEncodingMacRoman);

	// append strings together

	string url1 = folderURL;
	string url2 = fileName;
	string finalURL = url1 + "/" + url2;

	results.filePath = finalURL.c_str();

	//printf("url %s\n", finalURL.c_str());

	// cleanup dialog
	NavDialogDispose(dialog);

#endif
	//----------------------------------------------------------------------------------------
	//----------------------------------------------------------------------------------------
	//----------------------------------------------------------------------------------------

	//----------------------------------------------------------------------------------------
	//------------------------------------------------------------------------------   windoze
	//----------------------------------------------------------------------------------------
#ifdef TARGET_WIN32

	wchar_t fileName[MAX_PATH] = L"";
	char * extension;
	OPENFILENAME ofn;
    memset(&ofn, 0, sizeof(OPENFILENAME));
	ofn.lStructSize = sizeof(OPENFILENAME);
	HWND hwnd = WindowFromDC(wglGetCurrentDC());
	ofn.hwndOwner = hwnd;
	ofn.hInstance = GetModuleHandle(0);
	ofn.nMaxFileTitle = 31;
	ofn.lpstrFile = fileName;
	ofn.nMaxFile = MAX_PATH;
	ofn.lpstrFilter = _T("All Files (*.*)\0*.*\0");
	ofn.lpstrDefExt = _T("");	// we could do .rxml here?
	ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY;
	ofn.lpstrTitle = _T("Select Output File");

	if (GetSaveFileName(&ofn)){
		results.filePath = convertWideToNarrow(fileName);
	}

#endif
	//----------------------------------------------------------------------------------------
	//----------------------------------------------------------------------------------------
	//----------------------------------------------------------------------------------------

	if( results.filePath.length() > 0 ){
		results.bSuccess = true;
		results.fileName = ofFileUtils::getFilenameFromPath(results.filePath);
	}

	return results;
}

<|endoftext|>


<commit_before>/*
Copyright (c) 2017, Vadim Malyshev, lboss75@gmail.com
All rights reserved
*/

#include "stdafx.h"
#include "private/udp_transport.h"
#include "messages/dht_message_type.h"
#include "private/dht_session.h"
#include "logger.h"
#include "dht_network_client.h"
#include "dht_network_client_p.h"

void vds::dht::network::udp_transport::start(const vds::service_provider &sp, uint16_t port,
                                             const const_data_buffer &this_node_id) {
  this->this_node_id_ = this_node_id;

  try {
    this->server_.start(sp, network_address::any_ip6(port));
  }
  catch (...) {
    this->server_.start(sp, network_address::any_ip4(port));
  }

  this->continue_read(sp.create_scope("vds::dht::network::udp_transport::continue_read"));
  this->timer_.start(sp, std::chrono::seconds(1), [sp, pthis = this->shared_from_this()]()->bool{
    pthis->on_timer(sp).execute([](const std::shared_ptr<std::exception> &){});
    return !sp.get_shutdown_event().is_shuting_down();
  });
}

void vds::dht::network::udp_transport::stop(const service_provider& sp) {
  this->server_.stop(sp);
}

vds::async_task<>
vds::dht::network::udp_transport::write_async(const service_provider &sp, const udp_datagram &datagram) {
//  std::unique_lock<std::debug_mutex> lock(this->write_mutex_);
//  while(this->write_in_progress_) {
//    this->write_cond_.wait(*reinterpret_cast<std::unique_lock<std::mutex> *>(&lock));
//  }
//  this->write_in_progress_ = true;
//#ifdef _DEBUG
//#ifndef _WIN32
//  this->owner_id_ = syscall(SYS_gettid);
//#else
//  this->owner_id_ = GetCurrentThreadId();
//#endif
//#endif//_DEBUG

  return [sp, pthis = this->shared_from_this(), datagram](const async_result<> & result) {
    std::unique_lock<std::debug_mutex> lock(pthis->write_mutex_);
    bool need_send = pthis->send_queue_.empty();
    pthis->send_queue_.push_back(std::make_tuple(datagram, std::move(result)));

    if(need_send) {
      sp.get<logger>()->trace(
        ThisModule,
        sp,
        "started send");
      pthis->continue_send(sp);
    }
  };
}

void
vds::dht::network::udp_transport::continue_send(const service_provider &sp) {

  this->server_.socket().write_async(std::get<0>(this->send_queue_.front()))
    .execute([sp, pthis = this->shared_from_this()](const std::shared_ptr<std::exception> &ex) {
    sp.get<logger>()->trace(
      ThisModule,
      sp,
      "udp_transport socket sent");
    mt_service::async(sp, [sp, ex, pthis]() {
      sp.get<logger>()->trace(
        ThisModule,
        sp,
        "udp_transport sent");

      std::unique_lock<std::debug_mutex> lock(pthis->write_mutex_);
      auto p = pthis->send_queue_.begin();
      auto datagram = std::move(std::get<0>(*p));
      auto result = std::move(std::get<1>(*p));
      pthis->send_queue_.pop_front();
      if (!pthis->send_queue_.empty()) {
        pthis->continue_send(sp);
      }
      else {
        sp.get<logger>()->trace(
          ThisModule,
          sp,
          "stopped send");
      }
      lock.unlock();

      if (ex) {
        sp.get<logger>()->error(
          ThisModule,
          sp,
          "%s at write UDP datagram %d bytes to %s",
          ex->what(),
          datagram.data_size(),
          datagram.address().to_string().c_str());

        result.error(ex);
      }
      else {
        result.done();
      }
    });
  });
}

vds::async_task<> vds::dht::network::udp_transport::on_timer(const service_provider& sp) {
  resizable_data_buffer out_message;
  auto result = async_task<>::empty();
  std::shared_lock<std::shared_mutex> lock(this->sessions_mutex_);
  for(auto & p : this->sessions_) {
    result = result.then([session = p.second, sp, pthis = this->shared_from_this()]() {
      return session->on_timer(sp, pthis);
    });
  }
  return result;
}

vds::async_task<> vds::dht::network::udp_transport::try_handshake(const service_provider& sp, const std::string& address) {

  this->block_list_mutex_.lock();
  auto p = this->block_list_.find(address);
  if(this->block_list_.end() != p && p->second < std::chrono::steady_clock::now()) {
    this->block_list_mutex_.unlock();
    return async_task<>::empty();
  }
  this->block_list_[address] = std::chrono::steady_clock::now() + std::chrono::minutes(1);
  this->block_list_mutex_.unlock();

  resizable_data_buffer out_message;
  out_message.add((uint8_t)protocol_message_type_t::HandshakeBroadcast);
  out_message.add(PROTOCOL_VERSION);
  out_message += this->this_node_id_;

  return this->write_async(sp, udp_datagram(
        network_address::parse(this->server_.address().family(), address),
        out_message.get_data()));
}

void vds::dht::network::udp_transport::get_session_statistics(session_statistic& session_statistic) {

  std::shared_lock<std::shared_mutex> lock(this->sessions_mutex_);
  for(const auto & p : this->sessions_) {
    const auto session = p.second;
    session_statistic.items_.push_back(session->get_statistic());
  }
}

void vds::dht::network::udp_transport::add_session(
  const vds::service_provider& sp,
  const network_address& address,
  const std::shared_ptr<dht_session>& session) {

  sp.get<logger>()->trace(ThisModule, sp, "Add session %s", address.to_string().c_str());

  std::unique_lock<std::shared_mutex> lock(this->sessions_mutex_);
  this->sessions_[address] = session;
  lock.unlock();

  (*sp.get<client>())->add_session(sp, session, 0);
}

std::shared_ptr<vds::dht::network::dht_session> vds::dht::network::udp_transport::get_session(
  const network_address& address) const {

  std::shared_lock<std::shared_mutex> lock(this->sessions_mutex_);
  auto p = this->sessions_.find(address);
  if(this->sessions_.end() == p) {
    return std::shared_ptr<dht_session>();
  }

  return p->second;
}

void vds::dht::network::udp_transport::continue_read(
  const vds::service_provider & sp) {
  if(!this->server_) {
    return;
  }
  this->server_.socket().read_async().execute([sp, pthis = this->shared_from_this()](
    const std::shared_ptr<std::exception> & ex,
    const vds::udp_datagram & datagram){

    if(sp.get_shutdown_event().is_shuting_down()) {
      return;
    }

    if (!ex && 0 != datagram.data_size()) {
      switch ((protocol_message_type_t)datagram.data()[0]) {
      case protocol_message_type_t::HandshakeBroadcast:
      case protocol_message_type_t::Handshake: {
        auto session = pthis->get_session(datagram.address());
        if (session) {
          break;
        }
        if (datagram.data_size() == NODE_ID_SIZE + 2 && PROTOCOL_VERSION == datagram.data()[1]) {
          const_data_buffer partner_node_id(datagram.data() + 2, NODE_ID_SIZE);
          if (partner_node_id == pthis->this_node_id_) {
            break;
          }

          uint32_t session_id = static_cast<uint32_t>(std::rand());
          pthis->add_session(
            sp,
            datagram.address(),
            std::make_shared<dht_session>(
              datagram.address(),
              pthis->this_node_id_,
              partner_node_id,
              session_id));

          resizable_data_buffer out_message;
          out_message.add(static_cast<uint8_t>(protocol_message_type_t::Welcome));
          out_message.add(static_cast<uint8_t>(session_id >> 24));
          out_message.add(static_cast<uint8_t>(session_id >> 16));
          out_message.add(static_cast<uint8_t>(session_id >> 8));
          out_message.add(static_cast<uint8_t>(session_id));
          out_message.add(pthis->this_node_id_.data(), pthis->this_node_id_.size());

          pthis->write_async(sp, udp_datagram(datagram.address(), out_message.get_data()))
            .execute([
              pthis,
                sp,
                scope = sp.create_scope("Send Welcome"),
                address = datagram.address().to_string()](const std::shared_ptr<std::exception> & ex) {
                if (ex) {
                  sp.get<logger>()->trace(ThisModule, sp, "%s at send welcome to %s", ex->what(), address.c_str());
                }
                pthis->continue_read(sp);
              });

          return;
        }
        else {
          throw std::runtime_error("Invalid protocol");
        }
        break;
      }
      case protocol_message_type_t::Welcome: {
        if (datagram.data_size() == NODE_ID_SIZE + 5) {
          uint32_t session_id = (datagram.data()[1] << 24)
            | (datagram.data()[2] << 16)
            | (datagram.data()[3] << 8)
            | (datagram.data()[4]);
          const_data_buffer partner_node_id(datagram.data() + 5, NODE_ID_SIZE);
          pthis->add_session(
            sp,
            datagram.address(), std::make_shared<dht_session>(
              datagram.address(),
              pthis->this_node_id_,
              partner_node_id,
              session_id));
        }
        else {
          throw std::runtime_error("Invalid protocol");
        }

        break;
      }
      case protocol_message_type_t::Failed: {
        auto session = pthis->get_session(datagram.address());
        if (session) {
          std::shared_lock<std::shared_mutex> lock(pthis->sessions_mutex_);
          pthis->sessions_.erase(datagram.address());
        }

        break;
      }
      default: {
        auto session = pthis->get_session(datagram.address());
        if (session) {
          try {
            auto scope = sp.create_scope("Process datagram");
            session->process_datagram(scope, pthis, const_data_buffer(datagram.data(), datagram.data_size()))
              .execute([pthis, sp, scope, address = datagram.address()](const std::shared_ptr<std::exception> & ex){
              if (ex) {
                std::shared_lock<std::shared_mutex> lock(pthis->sessions_mutex_);
                pthis->sessions_.erase(address);
              }
              pthis->continue_read(sp);
            });
            return;
          }
          catch(...) {
            std::shared_lock<std::shared_mutex> lock(pthis->sessions_mutex_);
            pthis->sessions_.erase(datagram.address());
          }
        }
        else {
          resizable_data_buffer out_message;
          out_message.add((uint8_t)protocol_message_type_t::Failed);
          auto scope = sp.create_scope("Send Failed");
          pthis->write_async(scope, udp_datagram(datagram.address(), out_message.get_data()))
            .execute([pthis, sp, scope, address = datagram.address().to_string()](const std::shared_ptr<std::exception> & ex) {
            if (ex) {
              sp.get<logger>()->trace(ThisModule, sp, "%s at send welcome to %s", ex->what(), address.c_str());
            }
            pthis->continue_read(sp);
          });

          return;
        }
        break;
      }
      }
      pthis->continue_read(sp);
    }
    else {
      if(ex) {
        sp.get<logger>()->trace(ThisModule, sp, "Error %s", ex->what());

        //auto sys_error = std::dynamic_pointer_cast<std::system_error>(ex);
        //if(sys_error && sys_error->code().value() == ERROR_PORT_UNREACHABLE) {
        //  return;
        //}
      }
      if(0 == datagram.data_size()) {
        sp.get<logger>()->trace(ThisModule, sp, "0 == datagram.data_size()");
      }
      mt_service::async(sp, [sp, pthis]() {
        if (!sp.get_shutdown_event().is_shuting_down()) {
          pthis->continue_read(sp);
        }
      });
    }
  });
}

vds::dht::network::udp_transport::udp_transport()
: write_in_progress_(false),
  timer_("UDP timer"){
}

<commit_msg>fix stack overflow<commit_after>/*
Copyright (c) 2017, Vadim Malyshev, lboss75@gmail.com
All rights reserved
*/

#include "stdafx.h"
#include "private/udp_transport.h"
#include "messages/dht_message_type.h"
#include "private/dht_session.h"
#include "logger.h"
#include "dht_network_client.h"
#include "dht_network_client_p.h"

void vds::dht::network::udp_transport::start(const vds::service_provider &sp, uint16_t port,
                                             const const_data_buffer &this_node_id) {
  this->this_node_id_ = this_node_id;

  try {
    this->server_.start(sp, network_address::any_ip6(port));
  }
  catch (...) {
    this->server_.start(sp, network_address::any_ip4(port));
  }

  this->continue_read(sp.create_scope("vds::dht::network::udp_transport::continue_read"));
  this->timer_.start(sp, std::chrono::seconds(1), [sp, pthis = this->shared_from_this()]()->bool{
    pthis->on_timer(sp).execute([](const std::shared_ptr<std::exception> &){});
    return !sp.get_shutdown_event().is_shuting_down();
  });
}

void vds::dht::network::udp_transport::stop(const service_provider& sp) {
  this->server_.stop(sp);
}

vds::async_task<>
vds::dht::network::udp_transport::write_async(const service_provider &sp, const udp_datagram &datagram) {
//  std::unique_lock<std::debug_mutex> lock(this->write_mutex_);
//  while(this->write_in_progress_) {
//    this->write_cond_.wait(*reinterpret_cast<std::unique_lock<std::mutex> *>(&lock));
//  }
//  this->write_in_progress_ = true;
//#ifdef _DEBUG
//#ifndef _WIN32
//  this->owner_id_ = syscall(SYS_gettid);
//#else
//  this->owner_id_ = GetCurrentThreadId();
//#endif
//#endif//_DEBUG

  return [sp, pthis = this->shared_from_this(), datagram](const async_result<> & result) {
    std::unique_lock<std::debug_mutex> lock(pthis->write_mutex_);
    bool need_send = pthis->send_queue_.empty();
    pthis->send_queue_.push_back(std::make_tuple(datagram, std::move(result)));

    if(need_send) {
      sp.get<logger>()->trace(
        ThisModule,
        sp,
        "started send");
      pthis->continue_send(sp);
    }
  };
}

void
vds::dht::network::udp_transport::continue_send(const service_provider &sp) {

  this->server_.socket().write_async(std::get<0>(this->send_queue_.front()))
    .execute([sp, pthis = this->shared_from_this()](const std::shared_ptr<std::exception> &ex) {
    sp.get<logger>()->trace(
      ThisModule,
      sp,
      "udp_transport socket sent");
    mt_service::async(sp, [sp, ex, pthis]() {
      sp.get<logger>()->trace(
        ThisModule,
        sp,
        "udp_transport sent");

      std::unique_lock<std::debug_mutex> lock(pthis->write_mutex_);
      auto p = pthis->send_queue_.begin();
      auto datagram = std::move(std::get<0>(*p));
      auto result = std::move(std::get<1>(*p));
      pthis->send_queue_.pop_front();
      if (!pthis->send_queue_.empty()) {
        pthis->continue_send(sp);
      }
      else {
        sp.get<logger>()->trace(
          ThisModule,
          sp,
          "stopped send");
      }
      lock.unlock();

      if (ex) {
        sp.get<logger>()->error(
          ThisModule,
          sp,
          "%s at write UDP datagram %d bytes to %s",
          ex->what(),
          datagram.data_size(),
          datagram.address().to_string().c_str());

        result.error(ex);
      }
      else {
        result.done();
      }
    });
  });
}

vds::async_task<> vds::dht::network::udp_transport::on_timer(const service_provider& sp) {
  resizable_data_buffer out_message;
  auto result = async_task<>::empty();
  std::shared_lock<std::shared_mutex> lock(this->sessions_mutex_);
  for(auto & p : this->sessions_) {
    result = result.then([session = p.second, sp, pthis = this->shared_from_this()]() {
      return session->on_timer(sp, pthis);
    });
  }
  return result;
}

vds::async_task<> vds::dht::network::udp_transport::try_handshake(const service_provider& sp, const std::string& address) {

  this->block_list_mutex_.lock();
  auto p = this->block_list_.find(address);
  if(this->block_list_.end() != p && p->second < std::chrono::steady_clock::now()) {
    this->block_list_mutex_.unlock();
    return async_task<>::empty();
  }
  this->block_list_[address] = std::chrono::steady_clock::now() + std::chrono::minutes(1);
  this->block_list_mutex_.unlock();

  resizable_data_buffer out_message;
  out_message.add((uint8_t)protocol_message_type_t::HandshakeBroadcast);
  out_message.add(PROTOCOL_VERSION);
  out_message += this->this_node_id_;

  return this->write_async(sp, udp_datagram(
        network_address::parse(this->server_.address().family(), address),
        out_message.get_data()));
}

void vds::dht::network::udp_transport::get_session_statistics(session_statistic& session_statistic) {

  std::shared_lock<std::shared_mutex> lock(this->sessions_mutex_);
  for(const auto & p : this->sessions_) {
    const auto session = p.second;
    session_statistic.items_.push_back(session->get_statistic());
  }
}

void vds::dht::network::udp_transport::add_session(
  const vds::service_provider& sp,
  const network_address& address,
  const std::shared_ptr<dht_session>& session) {

  sp.get<logger>()->trace(ThisModule, sp, "Add session %s", address.to_string().c_str());

  std::unique_lock<std::shared_mutex> lock(this->sessions_mutex_);
  this->sessions_[address] = session;
  lock.unlock();

  (*sp.get<client>())->add_session(sp, session, 0);
}

std::shared_ptr<vds::dht::network::dht_session> vds::dht::network::udp_transport::get_session(
  const network_address& address) const {

  std::shared_lock<std::shared_mutex> lock(this->sessions_mutex_);
  auto p = this->sessions_.find(address);
  if(this->sessions_.end() == p) {
    return std::shared_ptr<dht_session>();
  }

  return p->second;
}

void vds::dht::network::udp_transport::continue_read(
  const vds::service_provider & sp) {
  if(!this->server_) {
    return;
  }
  this->server_.socket().read_async().execute([sp, pthis = this->shared_from_this()](
    const std::shared_ptr<std::exception> & ex,
    const vds::udp_datagram & datagram){

    if(sp.get_shutdown_event().is_shuting_down()) {
      return;
    }

    if (!ex && 0 != datagram.data_size()) {
      switch ((protocol_message_type_t)datagram.data()[0]) {
      case protocol_message_type_t::HandshakeBroadcast:
      case protocol_message_type_t::Handshake: {
        auto session = pthis->get_session(datagram.address());
        if (session) {
          break;
        }
        if (datagram.data_size() == NODE_ID_SIZE + 2 && PROTOCOL_VERSION == datagram.data()[1]) {
          const_data_buffer partner_node_id(datagram.data() + 2, NODE_ID_SIZE);
          if (partner_node_id == pthis->this_node_id_) {
            break;
          }

          uint32_t session_id = static_cast<uint32_t>(std::rand());
          pthis->add_session(
            sp,
            datagram.address(),
            std::make_shared<dht_session>(
              datagram.address(),
              pthis->this_node_id_,
              partner_node_id,
              session_id));

          resizable_data_buffer out_message;
          out_message.add(static_cast<uint8_t>(protocol_message_type_t::Welcome));
          out_message.add(static_cast<uint8_t>(session_id >> 24));
          out_message.add(static_cast<uint8_t>(session_id >> 16));
          out_message.add(static_cast<uint8_t>(session_id >> 8));
          out_message.add(static_cast<uint8_t>(session_id));
          out_message.add(pthis->this_node_id_.data(), pthis->this_node_id_.size());

          pthis->write_async(sp, udp_datagram(datagram.address(), out_message.get_data()))
            .execute([
              pthis,
                sp,
                scope = sp.create_scope("Send Welcome"),
                address = datagram.address().to_string()](const std::shared_ptr<std::exception> & ex) {
                if (ex) {
                  sp.get<logger>()->trace(ThisModule, sp, "%s at send welcome to %s", ex->what(), address.c_str());
                }
                pthis->continue_read(sp);
              });

          return;
        }
        else {
          throw std::runtime_error("Invalid protocol");
        }
        break;
      }
      case protocol_message_type_t::Welcome: {
        if (datagram.data_size() == NODE_ID_SIZE + 5) {
          uint32_t session_id = (datagram.data()[1] << 24)
            | (datagram.data()[2] << 16)
            | (datagram.data()[3] << 8)
            | (datagram.data()[4]);
          const_data_buffer partner_node_id(datagram.data() + 5, NODE_ID_SIZE);
          pthis->add_session(
            sp,
            datagram.address(), std::make_shared<dht_session>(
              datagram.address(),
              pthis->this_node_id_,
              partner_node_id,
              session_id));
        }
        else {
          throw std::runtime_error("Invalid protocol");
        }

        break;
      }
      case protocol_message_type_t::Failed: {
        auto session = pthis->get_session(datagram.address());
        if (session) {
          std::shared_lock<std::shared_mutex> lock(pthis->sessions_mutex_);
          pthis->sessions_.erase(datagram.address());
        }

        break;
      }
      default: {
        auto session = pthis->get_session(datagram.address());
        if (session) {
          try {
            auto scope = sp.create_scope("Process datagram");
            session->process_datagram(scope, pthis, const_data_buffer(datagram.data(), datagram.data_size()))
              .execute([pthis, sp, scope, address = datagram.address()](const std::shared_ptr<std::exception> & ex){
              if (ex) {
                std::shared_lock<std::shared_mutex> lock(pthis->sessions_mutex_);
                pthis->sessions_.erase(address);
              }
              mt_service::async(sp, [sp, pthis](){
                pthis->continue_read(sp);
              });
            });
            return;
          }
          catch(...) {
            std::shared_lock<std::shared_mutex> lock(pthis->sessions_mutex_);
            pthis->sessions_.erase(datagram.address());
          }
        }
        else {
          resizable_data_buffer out_message;
          out_message.add((uint8_t)protocol_message_type_t::Failed);
          auto scope = sp.create_scope("Send Failed");
          pthis->write_async(scope, udp_datagram(datagram.address(), out_message.get_data()))
            .execute([pthis, sp, scope, address = datagram.address().to_string()](const std::shared_ptr<std::exception> & ex) {
            if (ex) {
              sp.get<logger>()->trace(ThisModule, sp, "%s at send welcome to %s", ex->what(), address.c_str());
            }
            pthis->continue_read(sp);
          });

          return;
        }
        break;
      }
      }
      pthis->continue_read(sp);
    }
    else {
      if(ex) {
        sp.get<logger>()->trace(ThisModule, sp, "Error %s", ex->what());

        //auto sys_error = std::dynamic_pointer_cast<std::system_error>(ex);
        //if(sys_error && sys_error->code().value() == ERROR_PORT_UNREACHABLE) {
        //  return;
        //}
      }
      if(0 == datagram.data_size()) {
        sp.get<logger>()->trace(ThisModule, sp, "0 == datagram.data_size()");
      }
      mt_service::async(sp, [sp, pthis]() {
        if (!sp.get_shutdown_event().is_shuting_down()) {
          pthis->continue_read(sp);
        }
      });
    }
  });
}

vds::dht::network::udp_transport::udp_transport()
: write_in_progress_(false),
  timer_("UDP timer"){
}

<|endoftext|>


<commit_before>#include "WebSink.hpp"
#include <EagleLib/Nodes/NodeInfo.hpp>
using namespace vclick;

WebSink::WebSink()
{
    h264_pass_through = mo::MetaObjectFactory::Instance()->Create("h264_pass_through");
    active_switch = h264_pass_through->GetParameter<bool>("active");
    moments.emplace_back(2, 0, 0);
    moments.emplace_back(0, 2, 0);
    moments.emplace_back(0, 0, 2);
}
void WebSink::SetContext(mo::Context* ctx, bool overwrite)
{
    Node::SetContext(ctx, overwrite);
    h264_pass_through->SetContext(ctx, overwrite);
}
std::vector<mo::IParameter*> WebSink::GetParameters(const std::string& filter) const
{
    auto h264_params = h264_pass_through->GetParameters();
    auto my_params = Node::GetParameters();
    my_params.insert(my_params.end(), h264_params.begin(), h264_params.end());
    return my_params;
}

bool WebSink::ProcessImpl()
{
    if(moments.empty())
    {
        moments.emplace_back(2, 0, 0);
        moments.emplace_back(0, 2, 0);
        moments.emplace_back(0, 0, 2);
        thresholds.push_back(0.1);
        thresholds.push_back(0.1);
        thresholds.push_back(0.1);
    }
    if(foreground_mask->empty() || point_cloud->empty())
        return false;
    cv::Mat mask = foreground_mask->GetMat(Stream());
    cv::Mat ptCloud = point_cloud->GetMat(Stream());
    int num_points = cv::countNonZero(mask);
    cv::Mat foreground_points(1, num_points, CV_32FC3);
    int count = 0;
    for (int i = 0; i < ptCloud.rows; ++i)
    {
        for (int j = 0; j < ptCloud.cols; ++j)
        {
            if (mask.at<uchar>(i, j))
            {
                foreground_points.at<cv::Vec3f>(count) = ptCloud.at<cv::Vec3f>(i, j);
                ++count;
            }
        }
    }
    foreground_points_param.UpdateData(foreground_points, point_cloud_param.GetTimestamp(), _ctx);
    for (auto& bb : bounding_boxes)
    {
        cv::Mat bb_mask = bb.Contains(foreground_points);
        cv::Vec3f centroid(0, 0, 0);
        uchar* mask_ptr = bb_mask.ptr<uchar>();
        float count = 0;
        for (int i = 0; i < foreground_points.cols; ++i)
        {
            if (mask_ptr[i])
            {
                centroid += foreground_points.at<cv::Vec3f>(i);
                ++count;
            }
        }
        if (count < min_points)
            continue;
        centroid /= count;
        for (int i = 0; i < moments.size(); ++i)
        {
            float value = moments[i].Evaluate(bb_mask, foreground_points, centroid);
            if (value > thresholds[i])
            {
                active_switch->UpdateData(true, point_cloud_param.GetTimestamp(), _ctx);
            }
        }
    }
    h264_pass_through->Process();
    return true;
}
MO_REGISTER_CLASS(WebSink);<commit_msg>Disable when leave bb.<commit_after>#include "WebSink.hpp"
#include <EagleLib/Nodes/NodeInfo.hpp>
using namespace vclick;

WebSink::WebSink()
{
    h264_pass_through = mo::MetaObjectFactory::Instance()->Create("h264_pass_through");
    active_switch = h264_pass_through->GetParameter<bool>("active");
    moments.emplace_back(2, 0, 0);
    moments.emplace_back(0, 2, 0);
    moments.emplace_back(0, 0, 2);
}
void WebSink::SetContext(mo::Context* ctx, bool overwrite)
{
    Node::SetContext(ctx, overwrite);
    h264_pass_through->SetContext(ctx, overwrite);
}
std::vector<mo::IParameter*> WebSink::GetParameters(const std::string& filter) const
{
    auto h264_params = h264_pass_through->GetParameters();
    auto my_params = Node::GetParameters();
    my_params.insert(my_params.end(), h264_params.begin(), h264_params.end());
    return my_params;
}

bool WebSink::ProcessImpl()
{
    if(moments.empty())
    {
        moments.emplace_back(2, 0, 0);
        moments.emplace_back(0, 2, 0);
        moments.emplace_back(0, 0, 2);
        thresholds.push_back(0.1);
        thresholds.push_back(0.1);
        thresholds.push_back(0.1);
    }
    if(foreground_mask->empty() || point_cloud->empty())
        return false;
    cv::Mat mask = foreground_mask->GetMat(Stream());
    cv::Mat ptCloud = point_cloud->GetMat(Stream());
    int num_points = cv::countNonZero(mask);
    cv::Mat foreground_points(1, num_points, CV_32FC3);
    int count = 0;
    for (int i = 0; i < ptCloud.rows; ++i)
    {
        for (int j = 0; j < ptCloud.cols; ++j)
        {
            if (mask.at<uchar>(i, j))
            {
                foreground_points.at<cv::Vec3f>(count) = ptCloud.at<cv::Vec3f>(i, j);
                ++count;
            }
        }
    }
    foreground_points_param.UpdateData(foreground_points, point_cloud_param.GetTimestamp(), _ctx);
    for (auto& bb : bounding_boxes)
    {
        cv::Mat bb_mask = bb.Contains(foreground_points);
        cv::Vec3f centroid(0, 0, 0);
        uchar* mask_ptr = bb_mask.ptr<uchar>();
        float count = 0;
        for (int i = 0; i < foreground_points.cols; ++i)
        {
            if (mask_ptr[i])
            {
                centroid += foreground_points.at<cv::Vec3f>(i);
                ++count;
            }
        }
        if (count < min_points)
            continue;
        centroid /= count;
        bool activated = false;
        for (int i = 0; i < moments.size(); ++i)
        {
            float value = moments[i].Evaluate(bb_mask, foreground_points, centroid);
            if (value > thresholds[i])
            {
                active_switch->UpdateData(true, point_cloud_param.GetTimestamp(), _ctx);
                activated = true;
            }
        }
        if(activated == false)
        {
            active_switch->UpdateData(false, point_cloud_param.GetTimestamp(), _ctx);
        }
    }
    h264_pass_through->Process();
    return true;
}
MO_REGISTER_CLASS(WebSink);<|endoftext|>


<commit_before>#ifndef LTL_WRAPPED_FUNCTION_HPP
#define LTL_WRAPPED_FUNCTION_HPP

#include <memory>
#include <functional>

#include "ltl/promise.hpp"

namespace ltl {
namespace detail {

class task_queue_impl;

typedef int not_a_copy_ctor;

template <typename R>
struct wrapped_function
{
	template <typename Function>
    wrapped_function(Function&& task, not_a_copy_ctor)
    : task_(std::move(task))
    , promise_(std::make_shared<promise<R>>())
    {
    }

    void operator()() const
    {
        apply(static_cast<R*>(nullptr));
    }

    template <typename U>
    void apply(U*) const
    {
        promise_->set_value(task_());
    }

    void apply(void*) const
    {
        task_();
        promise_->set_value();
    }

    std::function<R()> task_;
    std::shared_ptr<promise<R>> promise_;
};

} // namespace detail
} // namespace ltl

#endif // LTL_WRAPPED_FUNCTION_HPP<commit_msg>Replaced use of std::move with std::forward on an 'universal reference'.<commit_after>#ifndef LTL_WRAPPED_FUNCTION_HPP
#define LTL_WRAPPED_FUNCTION_HPP

#include <memory>
#include <functional>

#include "ltl/promise.hpp"

namespace ltl {
namespace detail {

class task_queue_impl;

typedef int not_a_copy_ctor;

template <typename R>
struct wrapped_function
{
	template <typename Function>
    wrapped_function(Function&& task, not_a_copy_ctor)
    : task_(std::forward<Function>(task))
    , promise_(std::make_shared<promise<R>>())
    {
    }

    void operator()() const
    {
        apply(static_cast<R*>(nullptr));
    }

    template <typename U>
    void apply(U*) const
    {
        promise_->set_value(task_());
    }

    void apply(void*) const
    {
        task_();
        promise_->set_value();
    }

    std::function<R()> task_;
    std::shared_ptr<promise<R>> promise_;
};

} // namespace detail
} // namespace ltl

#endif // LTL_WRAPPED_FUNCTION_HPP<|endoftext|>


<commit_before>/**
 * HGE widgets example for Guichan.
 *
 * @author Kevin Lynx
 * @author Olof Naessn
 */

// Include all necessary headers.
#include <guichan.hpp>
#include <guichan/hge.hpp>
#include <hge.h>

/*
 * Common stuff we need
 */
HGE *hge = NULL;
bool running = false;

/*
 * Guichan HGE stuff we need
 */
gnc::HGEInput *input;                    // Input driver
gnc::HGEGraphics *graphics;              // Graphics driver
gnc::HGEImageLoader *imageLoader;        // For loading images
gnc::HGEImageFont *font;                 // For displaying a font

/*
 * Guichan stuff we need
 */
gcn::Gui *gui;                      // A Gui object - binds it all together

/*
 * All of the default widgets
 */
gcn::Container *top;                 // A top container
gcn::Label* label;                   // A label
gcn::Icon* icon;                     // An icon (image)
gcn::Button* button;                 // A button
gcn::TextField* textField;           // One-line text field
gcn::TextBox* textBox;               // Multi-line text box
gcn::ScrollArea* textBoxScrollArea;  // Scroll area for the text box
gcn::ListBox* listBox;               // A list box
gcn::DropDown* dropDown;             // Drop down
gcn::CheckBox* checkBox1;            // Two checkboxes
gcn::CheckBox* checkBox2;
gcn::RadioButton* radioButton1;      // Three radio buttons
gcn::RadioButton* radioButton2;
gcn::RadioButton* radioButton3;
gcn::Slider* slider;                 // A slider
gcn::Image *image;                   // An image for the icon
gcn::Window *window;
gcn::Image *darkbitsImage;
gcn::Icon* darkbitsIcon;
gcn::ScrollArea* nestedScrollArea;
gcn::Container* nestedContainer;
gcn::Slider* nestedSlider;

/*
 * Forward declations
 */
void  init();
void  halt();
bool  frameFunc();

/*
 * List boxes and dropdowns needs an instance of a listmodel
 * to know what elements they have.
 */
class DemoListModel : public gcn::ListModel
{
public:
    int getNumberOfElements()
    {
        return 5;
    }

    std::string getElementAt(int i)
    {
        switch(i)
        {
          case 0:
              return std::string("zero");
          case 1:
              return std::string("one");
          case 2:
              return std::string("two");
          case 3:
              return std::string("three");
          case 4:
              return std::string("four");
          default: // Just to keep warnings away
              return std::string("");
        }
    }
};

DemoListModel demoListModel;

void initWidgets()
{
    /*
     * Create all the widgets
     */
    label = new gcn::Label("Label");

    image = gcn::Image::load("gui-chan.png");
    icon = new gcn::Icon(image);

    button = new gcn::Button("Button");

    textField = new gcn::TextField("Text field");

    textBox = new gcn::TextBox("Multiline\nText box");

    textBoxScrollArea = new gcn::ScrollArea(textBox);
    textBoxScrollArea->setWidth(200);
    textBoxScrollArea->setHeight(100);
    textBoxScrollArea->setBorderSize(1);

    listBox = new gcn::ListBox(&demoListModel);
    listBox->setBorderSize(1);

    dropDown = new gcn::DropDown(&demoListModel);

    checkBox1 = new gcn::CheckBox("Checkbox 1");
    checkBox2 = new gcn::CheckBox("Checkbox 2");

    radioButton1 = new gcn::RadioButton("RadioButton 1", "radiogroup", true);
    radioButton2 = new gcn::RadioButton("RadioButton 2", "radiogroup");
    radioButton3 = new gcn::RadioButton("RadioButton 3", "radiogroup");

    slider = new gcn::Slider(0, 10);
    slider->setSize(100, 10);

    window = new gcn::Window("I am a window  Drag me");
    window->setBaseColor(gcn::Color(255, 150, 200, 190));

    darkbitsImage = gcn::Image::load("darkbitslogo_by_haiko.bmp");
    darkbitsIcon = new gcn::Icon(darkbitsImage);
    window->add(darkbitsIcon);
    window->resizeToContent();

    nestedSlider = new gcn::Slider(0, 10);
    nestedSlider->setSize(100, 10);

    nestedContainer = new gcn::Container();
    nestedContainer->setSize(400, 200);
    nestedContainer->add(nestedSlider, 50, 70);

    nestedScrollArea = new gcn::ScrollArea(nestedContainer);
    nestedScrollArea->setSize(180, 90);
    nestedScrollArea->setBorderSize(1);

    /*
     * Add them to the top container
     */
    top->add(label, 10, 10);
    top->add(icon, 10, 30);
    top->add(button, 200, 10);
    top->add(textField, 300, 10);
    top->add(textBoxScrollArea, 200, 50);
    top->add(listBox, 200, 200);
    top->add(dropDown, 500, 10);
    top->add(checkBox1, 500, 130);
    top->add(checkBox2, 500, 150);
    top->add(radioButton1, 500, 200);
    top->add(radioButton2, 500, 220);
    top->add(radioButton3, 500, 240);
    top->add(slider, 500, 300);
    top->add(window, 100, 350);
    top->add(nestedScrollArea, 440, 350);
}

/**
 * Initializes the application
 */
void  init()
{
    imageLoader  = new gcn::HGEImageLoader();
    // The ImageLoader in use is static and must be set to be
    // able to load images
    gcn::Image::setImageLoader(imageLoader);

    graphics = new gcn::HGEGraphics();
    input = new gcn::HGEInput();

    /*
     * Last but not least it's time to initialize and create the gui
     * with Guichan stuff.
     */
    top = new gcn::Container();
    top->setDimension(gcn::Rectangle(0, 0, 640, 480));
    gui = new gcn::Gui();
    // Set gui to use the HGEGraphics object.
    gui->setGraphics(graphics);
    // Set gui to use the HGEInput object
    gui->setInput(input);
    // Set the top container
    gui->setTop(top);
    // Load the HGE image font.
    font = new gcn::HGEImageFont("font2.fnt");
    // The global font is static and must be set.
    gcn::Widget::setGlobalFont(font);

    initWidgets();
}

void  halt()
{
    /*
     * Destroy Guichan stuff
     */
    delete font;
    delete gui;

    /*
     * Widgets
     */
    delete label;
    delete icon;
    delete button;
    delete textField;
    delete textBox;
    delete textBoxScrollArea;
    delete listBox;
    delete dropDown;
    delete checkBox1;
    delete checkBox2;
    delete radioButton1;
    delete radioButton2;
    delete radioButton3;
    delete slider;
    delete window;
    delete darkbitsIcon;
    delete darkbitsImage;
    delete nestedScrollArea;
    delete nestedContainer;
    delete nestedSlider;

    /*
     * Destroy Guichan HGE stuff
     */
    delete input;
    delete graphics;
    delete imageLoader;
}

bool frameFunc()
{
    if (hge->Input_GetKeyState(HGEK_ESCAPE) || running)
    {
        return true;
    }

    // Let the gui perform it's logic (like handle input)
    gui->logic();

    // Begin rendering
    hge->Gfx_BeginScene();
    hge->Gfx_Clear( 0 );
    // Draw the gui
    gui->draw();
    // End rendering
    hge->Gfx_EndScene();

    return false;
}

int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
    hge = hgeCreate(HGE_VERSION);

    hge->System_SetState(HGE_FRAMEFUNC, frameFunc);

    hge->System_SetState(HGE_TITLE, "Guichan with HGE Demo : Created By Kevin Lynx 2007-03-16");
    hge->System_SetState(HGE_SCREENWIDTH, 640);
    hge->System_SetState(HGE_SCREENHEIGHT, 480);
    hge->System_SetState(HGE_WINDOWED, true);
    hge->System_SetState(HGE_HIDEMOUSE, false);
    hge->System_SetState(HGE_USESOUND, false);
#ifdef  _DEBUG
    hge->System_SetState(HGE_LOGFILE, "log.txt");
#endif

    try
    {
        if (hge->System_Initiate())
        {
            init();
            hge->System_Start();
        }
        else
        {
            MessageBox(NULL, hge->System_GetErrorMessage(), "Error", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
        }

        halt();
        hge->System_Shutdown();
        hge->Release();

        return 0;
    }
    /*
     * Catch all Guichan exceptions
     */
    catch (gcn::Exception e)
    {
        MessageBox(NULL, hge->System_GetErrorMessage(), e.getMessage(), MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
        return 1;
    }
    /*
     * Catch all Std exceptions
     */
    catch (std::exception e)
    {
        MessageBox(NULL, hge->System_GetErrorMessage(), e.what(), MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
        return 1;
    }
    /*
     * Catch all Unknown exceptions
     */
    catch (...)
    {
        MessageBox(NULL, hge->System_GetErrorMessage(), "Unknown exception", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
        return 1;
    }
}

<commit_msg>Compile error has been fixed.<commit_after>/**
 * HGE widgets example for Guichan.
 *
 * @author Kevin Lynx
 * @author Olof Naessn
 */

// Include all necessary headers.
#include <guichan.hpp>
#include <guichan/hge.hpp>
#include <hge.h>

/*
 * Common stuff we need
 */
HGE *hge = NULL;
bool running = false;

/*
 * Guichan HGE stuff we need
 */
gcn::HGEInput *input;                    // Input driver
gcn::HGEGraphics *graphics;              // Graphics driver
gcn::HGEImageLoader *imageLoader;        // For loading images
gcn::HGEImageFont *font;                 // For displaying a font

/*
 * Guichan stuff we need
 */
gcn::Gui *gui;                      // A Gui object - binds it all together

/*
 * All of the default widgets
 */
gcn::Container *top;                 // A top container
gcn::Label* label;                   // A label
gcn::Icon* icon;                     // An icon (image)
gcn::Button* button;                 // A button
gcn::TextField* textField;           // One-line text field
gcn::TextBox* textBox;               // Multi-line text box
gcn::ScrollArea* textBoxScrollArea;  // Scroll area for the text box
gcn::ListBox* listBox;               // A list box
gcn::DropDown* dropDown;             // Drop down
gcn::CheckBox* checkBox1;            // Two checkboxes
gcn::CheckBox* checkBox2;
gcn::RadioButton* radioButton1;      // Three radio buttons
gcn::RadioButton* radioButton2;
gcn::RadioButton* radioButton3;
gcn::Slider* slider;                 // A slider
gcn::Image *image;                   // An image for the icon
gcn::Window *window;
gcn::Image *darkbitsImage;
gcn::Icon* darkbitsIcon;
gcn::ScrollArea* nestedScrollArea;
gcn::Container* nestedContainer;
gcn::Slider* nestedSlider;

/*
 * Forward declations
 */
void  init();
void  halt();
bool  frameFunc();

/*
 * List boxes and dropdowns needs an instance of a listmodel
 * to know what elements they have.
 */
class DemoListModel : public gcn::ListModel
{
public:
    int getNumberOfElements()
    {
        return 5;
    }

    std::string getElementAt(int i)
    {
        switch(i)
        {
          case 0:
              return std::string("zero");
          case 1:
              return std::string("one");
          case 2:
              return std::string("two");
          case 3:
              return std::string("three");
          case 4:
              return std::string("four");
          default: // Just to keep warnings away
              return std::string("");
        }
    }
};

DemoListModel demoListModel;

void initWidgets()
{
    /*
     * Create all the widgets
     */
    label = new gcn::Label("Label");

    image = gcn::Image::load("gui-chan.png");
    icon = new gcn::Icon(image);

    button = new gcn::Button("Button");

    textField = new gcn::TextField("Text field");

    textBox = new gcn::TextBox("Multiline\nText box");

    textBoxScrollArea = new gcn::ScrollArea(textBox);
    textBoxScrollArea->setWidth(200);
    textBoxScrollArea->setHeight(100);
    textBoxScrollArea->setBorderSize(1);

    listBox = new gcn::ListBox(&demoListModel);
    listBox->setBorderSize(1);

    dropDown = new gcn::DropDown(&demoListModel);

    checkBox1 = new gcn::CheckBox("Checkbox 1");
    checkBox2 = new gcn::CheckBox("Checkbox 2");

    radioButton1 = new gcn::RadioButton("RadioButton 1", "radiogroup", true);
    radioButton2 = new gcn::RadioButton("RadioButton 2", "radiogroup");
    radioButton3 = new gcn::RadioButton("RadioButton 3", "radiogroup");

    slider = new gcn::Slider(0, 10);
    slider->setSize(100, 10);

    window = new gcn::Window("I am a window  Drag me");
    window->setBaseColor(gcn::Color(255, 150, 200, 190));

    darkbitsImage = gcn::Image::load("darkbitslogo_by_haiko.bmp");
    darkbitsIcon = new gcn::Icon(darkbitsImage);
    window->add(darkbitsIcon);
    window->resizeToContent();

    nestedSlider = new gcn::Slider(0, 10);
    nestedSlider->setSize(100, 10);

    nestedContainer = new gcn::Container();
    nestedContainer->setSize(400, 200);
    nestedContainer->add(nestedSlider, 50, 70);

    nestedScrollArea = new gcn::ScrollArea(nestedContainer);
    nestedScrollArea->setSize(180, 90);
    nestedScrollArea->setBorderSize(1);

    /*
     * Add them to the top container
     */
    top->add(label, 10, 10);
    top->add(icon, 10, 30);
    top->add(button, 200, 10);
    top->add(textField, 300, 10);
    top->add(textBoxScrollArea, 200, 50);
    top->add(listBox, 200, 200);
    top->add(dropDown, 500, 10);
    top->add(checkBox1, 500, 130);
    top->add(checkBox2, 500, 150);
    top->add(radioButton1, 500, 200);
    top->add(radioButton2, 500, 220);
    top->add(radioButton3, 500, 240);
    top->add(slider, 500, 300);
    top->add(window, 100, 350);
    top->add(nestedScrollArea, 440, 350);
}

/**
 * Initializes the application
 */
void  init()
{
    imageLoader  = new gcn::HGEImageLoader();
    // The ImageLoader in use is static and must be set to be
    // able to load images
    gcn::Image::setImageLoader(imageLoader);

    graphics = new gcn::HGEGraphics();
    input = new gcn::HGEInput();

    /*
     * Last but not least it's time to initialize and create the gui
     * with Guichan stuff.
     */
    top = new gcn::Container();
    top->setDimension(gcn::Rectangle(0, 0, 640, 480));
    gui = new gcn::Gui();
    // Set gui to use the HGEGraphics object.
    gui->setGraphics(graphics);
    // Set gui to use the HGEInput object
    gui->setInput(input);
    // Set the top container
    gui->setTop(top);
    // Load the HGE image font.
    font = new gcn::HGEImageFont("font2.fnt");
    // The global font is static and must be set.
    gcn::Widget::setGlobalFont(font);

    initWidgets();
}

void  halt()
{
    /*
     * Destroy Guichan stuff
     */
    delete font;
    delete gui;

    /*
     * Widgets
     */
    delete label;
    delete icon;
    delete button;
    delete textField;
    delete textBox;
    delete textBoxScrollArea;
    delete listBox;
    delete dropDown;
    delete checkBox1;
    delete checkBox2;
    delete radioButton1;
    delete radioButton2;
    delete radioButton3;
    delete slider;
    delete window;
    delete darkbitsIcon;
    delete darkbitsImage;
    delete nestedScrollArea;
    delete nestedContainer;
    delete nestedSlider;

    /*
     * Destroy Guichan HGE stuff
     */
    delete input;
    delete graphics;
    delete imageLoader;
}

bool frameFunc()
{
    if (hge->Input_GetKeyState(HGEK_ESCAPE) || running)
    {
        return true;
    }

    // Let the gui perform it's logic (like handle input)
    gui->logic();

    // Begin rendering
    hge->Gfx_BeginScene();
    hge->Gfx_Clear( 0 );
    // Draw the gui
    gui->draw();
    // End rendering
    hge->Gfx_EndScene();

    return false;
}

int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
    hge = hgeCreate(HGE_VERSION);

    hge->System_SetState(HGE_FRAMEFUNC, frameFunc);

    hge->System_SetState(HGE_TITLE, "Guichan with HGE Demo : Created By Kevin Lynx 2007-03-16");
    hge->System_SetState(HGE_SCREENWIDTH, 640);
    hge->System_SetState(HGE_SCREENHEIGHT, 480);
    hge->System_SetState(HGE_WINDOWED, true);
    hge->System_SetState(HGE_HIDEMOUSE, false);
    hge->System_SetState(HGE_USESOUND, false);
#ifdef  _DEBUG
    hge->System_SetState(HGE_LOGFILE, "log.txt");
#endif

    try
    {
        if (hge->System_Initiate())
        {
            init();
            hge->System_Start();
        }
        else
        {
            MessageBox(NULL, hge->System_GetErrorMessage(), "Error", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
        }

        halt();
        hge->System_Shutdown();
        hge->Release();

        return 0;
    }
    /*
     * Catch all Guichan exceptions
     */
    catch (gcn::Exception e)
    {
        MessageBox(NULL, hge->System_GetErrorMessage(), e.getMessage(), MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
        return 1;
    }
    /*
     * Catch all Std exceptions
     */
    catch (std::exception e)
    {
        MessageBox(NULL, hge->System_GetErrorMessage(), e.what(), MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
        return 1;
    }
    /*
     * Catch all Unknown exceptions
     */
    catch (...)
    {
        MessageBox(NULL, hge->System_GetErrorMessage(), "Unknown exception", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
        return 1;
    }
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: arealink.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: er $ $Date: 2001-04-21 20:31:39 $
 *
 *  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 SC_AREALINK_HXX
#define SC_AREALINK_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_REFRESHTIMER_HXX
#include "refreshtimer.hxx"
#endif

#ifndef _LNKBASE_HXX //autogen
#include <so3/lnkbase.hxx>
#endif

class ScDocShell;
class SfxObjectShell;

class ScAreaLink : public ::so3::SvBaseLink, public ScRefreshTimer
{
private:
    ScDocShell* pDocShell;      // Container
    String      aFileName;
    String      aFilterName;
    String      aOptions;
    String      aSourceArea;
    ScRange     aDestArea;
    BOOL        bAddUndo;
    BOOL        bInCreate;
    BOOL        bDoInsert;      // wird fuer das erste Update auf FALSE gesetzt

public:
    TYPEINFO();
    ScAreaLink( SfxObjectShell* pShell, const String& rFile,
                    const String& rFilter, const String& rOpt,
                    const String& rArea, const ScRange& rDest, ULONG nRefresh );
    virtual ~ScAreaLink();

    virtual void Closed();
    virtual void DataChanged( const String& rMimeType,
                              const ::com::sun::star::uno::Any & rValue );

    virtual BOOL Edit(Window* pParent);

    BOOL    Refresh( const String& rNewFile, const String& rNewFilter,
                    const String& rNewArea, ULONG nNewRefresh );

    void    SetInCreate(BOOL bSet)                  { bInCreate = bSet; }
    void    SetDoInsert(BOOL bSet)                  { bDoInsert = bSet; }
    void    SetDestArea(const ScRange& rNew);
    void    SetSource(const String& rDoc, const String& rFlt, const String& rOpt,
                        const String& rArea);

    BOOL    IsEqual( const String& rFile, const String& rFilter, const String& rOpt,
                        const String& rSource, const ScRange& rDest ) const;

    const String&   GetFile() const         { return aFileName;     }
    const String&   GetFilter() const       { return aFilterName;   }
    const String&   GetOptions() const      { return aOptions;      }
    const String&   GetSource() const       { return aSourceArea;   }
    const ScRange&  GetDestArea() const     { return aDestArea;     }

    DECL_LINK( RefreshHdl, ScAreaLink* );

};

#endif
<commit_msg>+ScAreaLink::FindExtRange()<commit_after>/*************************************************************************
 *
 *  $RCSfile: arealink.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: dr $ $Date: 2001-04-24 14:43:38 $
 *
 *  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 SC_AREALINK_HXX
#define SC_AREALINK_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_REFRESHTIMER_HXX
#include "refreshtimer.hxx"
#endif

#ifndef _LNKBASE_HXX //autogen
#include <so3/lnkbase.hxx>
#endif

class ScDocShell;
class SfxObjectShell;

class ScAreaLink : public ::so3::SvBaseLink, public ScRefreshTimer
{
private:
    ScDocShell* pDocShell;      // Container
    String      aFileName;
    String      aFilterName;
    String      aOptions;
    String      aSourceArea;
    ScRange     aDestArea;
    BOOL        bAddUndo;
    BOOL        bInCreate;
    BOOL        bDoInsert;      // wird fuer das erste Update auf FALSE gesetzt

    BOOL        FindExtRange( ScRange& rRange, ScDocument* pSrcDoc, const String& rAreaName );

public:
    TYPEINFO();
    ScAreaLink( SfxObjectShell* pShell, const String& rFile,
                    const String& rFilter, const String& rOpt,
                    const String& rArea, const ScRange& rDest, ULONG nRefresh );
    virtual ~ScAreaLink();

    virtual void Closed();
    virtual void DataChanged( const String& rMimeType,
                              const ::com::sun::star::uno::Any & rValue );

    virtual BOOL Edit(Window* pParent);

    BOOL    Refresh( const String& rNewFile, const String& rNewFilter,
                    const String& rNewArea, ULONG nNewRefresh );

    void    SetInCreate(BOOL bSet)                  { bInCreate = bSet; }
    void    SetDoInsert(BOOL bSet)                  { bDoInsert = bSet; }
    void    SetDestArea(const ScRange& rNew);
    void    SetSource(const String& rDoc, const String& rFlt, const String& rOpt,
                        const String& rArea);

    BOOL    IsEqual( const String& rFile, const String& rFilter, const String& rOpt,
                        const String& rSource, const ScRange& rDest ) const;

    const String&   GetFile() const         { return aFileName;     }
    const String&   GetFilter() const       { return aFilterName;   }
    const String&   GetOptions() const      { return aOptions;      }
    const String&   GetSource() const       { return aSourceArea;   }
    const ScRange&  GetDestArea() const     { return aDestArea;     }

    DECL_LINK( RefreshHdl, ScAreaLink* );

};

#endif
<|endoftext|>


<commit_before>/***********************************************************************
 multiquery.cpp - Example showing how to iterate over result sets upon
	execution of a query that returns more than one result set.  You can
	get multiple result sets when executing multiple separate SQL
	statments in a single query, or when dealing with the results of
	calling a stored procedure.

 Copyright (c) 1998 by Kevin Atkinson, (c) 1999-2001 by MySQL AB,
 (c) 2004-2009 by Educational Technology Resources, Inc., and (c)
 2005 by Arnon Jalon.  Others may also hold copyrights on code in
 this file.  See the CREDITS.txt file in the top directory of the
 distribution for details.

 This file is part of MySQL++.

 MySQL++ is free software; you can redistribute it and/or modify it
 under the terms of the GNU Lesser General Public License as published
 by the Free Software Foundation; either version 2.1 of the License, or
 (at your option) any later version.

 MySQL++ 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 MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include "cmdline.h"
#include "printdata.h"

#include <mysql++.h>

#include <iostream>
#include <iomanip>
#include <vector>

using namespace std;
using namespace mysqlpp;

typedef vector<size_t> IntVectorType;

static void
print_header(IntVectorType& widths, StoreQueryResult& res)
{
	cout << "  |" << setfill(' ');
	for (size_t i = 0; i < res.field_names()->size(); i++) {
		cout << " " << setw(widths.at(i)) << res.field_name(int(i)) << " |";
	}
	cout << endl;
}

static void
print_row(IntVectorType& widths, Row& row)
{
	cout << "  |" << setfill(' ');
	for (size_t i = 0; i < row.size(); ++i) {
		cout << " " << setw(widths.at(i)) << row[int(i)] << " |";
	}
	cout << endl;
}

static void
print_row_separator(IntVectorType& widths)
{
	cout << "  +" << setfill('-');
	for (size_t i = 0; i < widths.size(); i++) {
		cout << "-" << setw(widths.at(i)) << '-' << "-+";
	}
	cout << endl;
}

static void
print_result(StoreQueryResult& res, int index)
{
	// Show how many rows are in result, if any
	StoreQueryResult::size_type num_results = res.size();
	if (res && (num_results > 0)) {
		cout << "Result set " << index << " has " << num_results <<
				" row" << (num_results == 1 ? "" : "s") << ':' << endl;
	}
	else {
		cout << "Result set " << index << " is empty." << endl;
		return;
	}

	// Figure out the widths of the result set's columns
	IntVectorType widths;
	size_t size = res.num_fields();
	for (size_t i = 0; i < size; i++) {
		widths.push_back(max(
				res.field(i).max_length(),
				res.field_name(i).size()));
	}

	// Print result set header
	print_row_separator(widths);
	print_header(widths, res);
	print_row_separator(widths);

	// Display the result set contents
	for (StoreQueryResult::size_type i = 0; i < num_results; ++i) {
		print_row(widths, res[i]);
	}

	// Print result set footer
	print_row_separator(widths);
}

static void
print_multiple_results(Query& query)
{
	// Execute query and print all result sets
	StoreQueryResult res = query.store();
	print_result(res, 0);
	for (int i = 1; query.more_results(); ++i) {
		res = query.store_next();
		print_result(res, i);
	}
}

int
main(int argc, char *argv[])
{
	// Get connection parameters from command line
	mysqlpp::examples::CommandLine cmdline(argc, argv);
	if (!cmdline) {
		return 1;
	}

	try {
		// Enable multi-queries.  Notice that you almost always set
		// MySQL++ connection options before establishing the server
		// connection, and options are always set using this one
		// interface.  If you're familiar with the underlying C API,
		// you know that there is poor consistency on these matters;
		// MySQL++ abstracts these differences away.
		Connection con;
		con.set_option(new MultiStatementsOption(true));

		// Connect to the database
		if (!con.connect(mysqlpp::examples::db_name, cmdline.server(),
				cmdline.user(), cmdline.pass())) {
			return 1;
		}

		// Set up query with multiple queries.
		Query query = con.query();
		query << "DROP TABLE IF EXISTS test_table; " <<
				"CREATE TABLE test_table(id INT); " <<
				"INSERT INTO test_table VALUES(10); " <<
				"UPDATE test_table SET id=20 WHERE id=10; " <<
				"SELECT * FROM test_table; " <<
				"DROP TABLE test_table";
		cout << "Multi-query: " << endl << query << endl;

		// Execute statement and display all result sets.
		print_multiple_results(query);

#if MYSQL_VERSION_ID >= 50000
		// If it's MySQL v5.0 or higher, also test stored procedures, which
		// return their results the same way multi-queries do.
		query << "DROP PROCEDURE IF EXISTS get_stock; " <<
				"CREATE PROCEDURE get_stock" <<
				"( i_item varchar(20) ) " <<
				"BEGIN " <<
				"SET i_item = concat('%', i_item, '%'); " <<
				"SELECT * FROM stock WHERE lower(item) like lower(i_item); " <<
				"END;";
		cout << "Stored procedure query: " << endl << query << endl;

		// Create the stored procedure.
		print_multiple_results(query);

		// Call the stored procedure and display its results.
		query << "CALL get_stock('relish')";
		cout << "Query: " << query << endl;
		print_multiple_results(query);
#endif

		return 0;
	}
	catch (const BadOption& err) {
		cerr << err.what() << endl;
		cerr << "This example requires MySQL 4.1.1 or later." << endl;
		return 1;
	}
	catch (const ConnectionFailed& err) {
		cerr << "Failed to connect to database server: " <<
				err.what() << endl;
		return 1;
	}
	catch (const Exception& er) {
		// Catch-all for any other MySQL++ exceptions
		cerr << "Error: " << er.what() << endl;
		return 1;
	}
}
<commit_msg>#including algorithm.h in examples/multiquery.cpp for std::max(). Didn't need it before because we were apparently getting another version via another #include path.  Probably either the windows.h macro or the one in stdlib.h.<commit_after>/***********************************************************************
 multiquery.cpp - Example showing how to iterate over result sets upon
	execution of a query that returns more than one result set.  You can
	get multiple result sets when executing multiple separate SQL
	statments in a single query, or when dealing with the results of
	calling a stored procedure.

 Copyright (c) 1998 by Kevin Atkinson, (c) 1999-2001 by MySQL AB,
 (c) 2004-2009 by Educational Technology Resources, Inc., and (c)
 2005 by Arnon Jalon.  Others may also hold copyrights on code in
 this file.  See the CREDITS.txt file in the top directory of the
 distribution for details.

 This file is part of MySQL++.

 MySQL++ is free software; you can redistribute it and/or modify it
 under the terms of the GNU Lesser General Public License as published
 by the Free Software Foundation; either version 2.1 of the License, or
 (at your option) any later version.

 MySQL++ 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 MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include "cmdline.h"
#include "printdata.h"

#include <mysql++.h>

#include <algorithm>
#include <iostream>
#include <iomanip>
#include <vector>

using namespace std;
using namespace mysqlpp;

typedef vector<size_t> IntVectorType;

static void
print_header(IntVectorType& widths, StoreQueryResult& res)
{
	cout << "  |" << setfill(' ');
	for (size_t i = 0; i < res.field_names()->size(); i++) {
		cout << " " << setw(widths.at(i)) << res.field_name(int(i)) << " |";
	}
	cout << endl;
}

static void
print_row(IntVectorType& widths, Row& row)
{
	cout << "  |" << setfill(' ');
	for (size_t i = 0; i < row.size(); ++i) {
		cout << " " << setw(widths.at(i)) << row[int(i)] << " |";
	}
	cout << endl;
}

static void
print_row_separator(IntVectorType& widths)
{
	cout << "  +" << setfill('-');
	for (size_t i = 0; i < widths.size(); i++) {
		cout << "-" << setw(widths.at(i)) << '-' << "-+";
	}
	cout << endl;
}

static void
print_result(StoreQueryResult& res, int index)
{
	// Show how many rows are in result, if any
	StoreQueryResult::size_type num_results = res.size();
	if (res && (num_results > 0)) {
		cout << "Result set " << index << " has " << num_results <<
				" row" << (num_results == 1 ? "" : "s") << ':' << endl;
	}
	else {
		cout << "Result set " << index << " is empty." << endl;
		return;
	}

	// Figure out the widths of the result set's columns
	IntVectorType widths;
	size_t size = res.num_fields();
	for (size_t i = 0; i < size; i++) {
		widths.push_back(max(
				res.field(i).max_length(),
				res.field_name(i).size()));
	}

	// Print result set header
	print_row_separator(widths);
	print_header(widths, res);
	print_row_separator(widths);

	// Display the result set contents
	for (StoreQueryResult::size_type i = 0; i < num_results; ++i) {
		print_row(widths, res[i]);
	}

	// Print result set footer
	print_row_separator(widths);
}

static void
print_multiple_results(Query& query)
{
	// Execute query and print all result sets
	StoreQueryResult res = query.store();
	print_result(res, 0);
	for (int i = 1; query.more_results(); ++i) {
		res = query.store_next();
		print_result(res, i);
	}
}

int
main(int argc, char *argv[])
{
	// Get connection parameters from command line
	mysqlpp::examples::CommandLine cmdline(argc, argv);
	if (!cmdline) {
		return 1;
	}

	try {
		// Enable multi-queries.  Notice that you almost always set
		// MySQL++ connection options before establishing the server
		// connection, and options are always set using this one
		// interface.  If you're familiar with the underlying C API,
		// you know that there is poor consistency on these matters;
		// MySQL++ abstracts these differences away.
		Connection con;
		con.set_option(new MultiStatementsOption(true));

		// Connect to the database
		if (!con.connect(mysqlpp::examples::db_name, cmdline.server(),
				cmdline.user(), cmdline.pass())) {
			return 1;
		}

		// Set up query with multiple queries.
		Query query = con.query();
		query << "DROP TABLE IF EXISTS test_table; " <<
				"CREATE TABLE test_table(id INT); " <<
				"INSERT INTO test_table VALUES(10); " <<
				"UPDATE test_table SET id=20 WHERE id=10; " <<
				"SELECT * FROM test_table; " <<
				"DROP TABLE test_table";
		cout << "Multi-query: " << endl << query << endl;

		// Execute statement and display all result sets.
		print_multiple_results(query);

#if MYSQL_VERSION_ID >= 50000
		// If it's MySQL v5.0 or higher, also test stored procedures, which
		// return their results the same way multi-queries do.
		query << "DROP PROCEDURE IF EXISTS get_stock; " <<
				"CREATE PROCEDURE get_stock" <<
				"( i_item varchar(20) ) " <<
				"BEGIN " <<
				"SET i_item = concat('%', i_item, '%'); " <<
				"SELECT * FROM stock WHERE lower(item) like lower(i_item); " <<
				"END;";
		cout << "Stored procedure query: " << endl << query << endl;

		// Create the stored procedure.
		print_multiple_results(query);

		// Call the stored procedure and display its results.
		query << "CALL get_stock('relish')";
		cout << "Query: " << query << endl;
		print_multiple_results(query);
#endif

		return 0;
	}
	catch (const BadOption& err) {
		cerr << err.what() << endl;
		cerr << "This example requires MySQL 4.1.1 or later." << endl;
		return 1;
	}
	catch (const ConnectionFailed& err) {
		cerr << "Failed to connect to database server: " <<
				err.what() << endl;
		return 1;
	}
	catch (const Exception& er) {
		// Catch-all for any other MySQL++ exceptions
		cerr << "Error: " << er.what() << endl;
		return 1;
	}
}
<|endoftext|>