Пример #1
0
void comauto::CommonLanguageRuntime::call( tagVARIANT* res, const std::wstring& assembly_, const std::wstring& class_, const std::wstring& method_, unsigned int argc, const tagVARIANT* argv, unsigned int lcid) const
{
	struct Local
	{
		Local() {::memset( this, 0, sizeof( *this)); varResult.vt = VT_EMPTY;}
		~Local()
		{
			if (spType) spType->Release();
			if (spAssembly) spAssembly->Release();
			if (spDefaultAppDomain) spDefaultAppDomain->Release();
		}
		EXCEPINFO excepInfo;
		VARIANT varResult; 
		DISPPARAMS dispParams;
		IUnknownPtr spAppDomainThunk;
		_AppDomainPtr spDefaultAppDomain; 
		_AssemblyPtr spAssembly; 
		_TypePtr spType;

		void getReturnVal( VARIANT* res)
		{
			std::memcpy( res, &varResult, sizeof(varResult));
			varResult.vt = VT_EMPTY;
			return;
		}
	};
	Local local;

	// The identifiers of the method in the .NET class to invoke:
	bstr_t bstrAssemblyName( assembly_.c_str()); 
	bstr_t bstrClassName( class_.c_str()); 
	bstr_t bstrMethodName( method_.c_str()); 
 
	WRAP( m_impl->m_runtimehost->GetDefaultDomain( &local.spAppDomainThunk));
	WRAP( local.spAppDomainThunk->QueryInterface( IID_PPV_ARGS( &local.spDefaultAppDomain)));
	WRAP( local.spDefaultAppDomain->Load_2( bstrAssemblyName, &local.spAssembly));
	WRAP( local.spAssembly->GetType_2( bstrClassName, &local.spType));

	// Create an instance of the object to invoke the method:
	variant_t vtObject;
	WRAP( local.spAssembly->CreateInstance( bstrClassName, &vtObject));
	if (!vtObject.punkVal)
	{
		throw std::runtime_error( std::string( "class definition not found '") + utf8string( bstrClassName.GetBSTR()) + "'");
	}

	// Initialize the method arguments structure:
	local.dispParams.cNamedArgs = 0;
	local.dispParams.cArgs = argc;
	local.dispParams.rgvarg = const_cast<VARIANT*>(argv);

	// Get the method invoker interface (IDispatch):
	IDispatch* dispatch = NULL;
	WRAP( vtObject.punkVal->QueryInterface( IID_IDispatch, (void**)&dispatch));

	// Get the method handle:
	DISPID gDispId = 0;
	LPOLESTR bstrMethodName_ = bstrMethodName;
	WRAP( dispatch->GetIDsOfNames( IID_NULL, &bstrMethodName_, 1, lcid, &gDispId));

	// Call that method:
	UINT puArgErr;
	HRESULT hr = dispatch->Invoke( gDispId, IID_NULL, lcid, DISPATCH_METHOD, &local.dispParams, &local.varResult, &local.excepInfo, &puArgErr);
	if (hr != S_OK)
	{
		std::string methodname = comauto::utf8string(class_) + "." + comauto::utf8string(method_);
		if (hr == DISP_E_EXCEPTION)
		{
			throw std::runtime_error( std::string("Error calling ") + methodname + " " + comauto::tostring( local.excepInfo));
		}
		else
		{
			_com_error error(hr);
			std::ostringstream errcode; 
			errcode << std::hex << " [0x" << hr << "]";
			throw std::runtime_error( std::string("Error calling ") + methodname + ": '" + comauto::utf8string(error.ErrorMessage()) + errcode.str());
		}
	}
	local.getReturnVal( res);
}
Пример #2
0
//
// class MessageBox::MessageBox					- Chapter 10, page 287
//
MessageBox::MessageBox(std::wstring msg, std::wstring title, int buttonFlags)
{
	// Initialize dialogs
	m_UI.Init( &D3DRenderer::g_DialogResourceManager );
    m_UI.SetCallback( OnGUIEvent ); 

	// Find the dimensions of the message
 	RECT rc;
	SetRect( &rc, 0,0,0,0);
	m_UI.CalcTextRect( msg.c_str(), m_UI.GetDefaultElement(DXUT_CONTROL_STATIC,0), &rc );
    int msgWidth = rc.right - rc.left;
    int msgHeight = rc.bottom - rc.top;

	int numButtons = 2;
	if ( (buttonFlags == MB_ABORTRETRYIGNORE) ||
		(buttonFlags == MB_CANCELTRYCONTINUE) ||
		(buttonFlags == MB_CANCELTRYCONTINUE) )
	{
		numButtons = 3;
	}
	else if (buttonFlags == MB_OK)
	{
		numButtons = 1;
	}

	int btnWidth = (int)((float) g_pApp->GetScreenSize().x * 0.15f);
	int btnHeight = (int)((float) g_pApp->GetScreenSize().y * 0.037f);
	int border = (int)((float) g_pApp->GetScreenSize().x * 0.043f);

	m_Width = std::max(msgWidth + 2 * border, btnWidth + 2 * border);
	m_Height = msgHeight + (numButtons * (btnHeight+border) ) + (2 * border);

	m_PosX = (g_pApp->GetScreenSize().x - m_Width)/2;
	m_PosY = (g_pApp->GetScreenSize().y - m_Height)/2;
	m_UI.SetLocation( m_PosX, m_PosY );

	m_UI.SetSize( m_Width, m_Height );
	//m_UI.SetBackgroundColors(g_Gray40);

	D3DCOLOR red = D3DCOLOR_ARGB(0xc0,0xff,0x00,0x00);
	m_UI.SetBackgroundColors(red);

	int iY = border; 
	int iX = (m_Width - msgWidth) / 2; 

	m_UI.AddStatic( 0, msg.c_str(), iX, iY, msgWidth, msgHeight);

	iX = (m_Width - btnWidth) / 2;
	iY = m_Height - btnHeight - border;

	buttonFlags &= 0xF;
	if ( (buttonFlags == MB_ABORTRETRYIGNORE) ||
		 (buttonFlags == MB_CANCELTRYCONTINUE) )

	{
		// The message box contains three push buttons: Cancel, Try Again, Continue. 
		// This is the new standard over Abort,Retry,Ignore
		m_UI.AddButton( IDCONTINUE, g_pApp->GetString(_T("IDS_CONTINUE")).c_str(), iX, iY - (2*border), btnWidth, btnHeight );
		m_UI.AddButton( IDTRYAGAIN, g_pApp->GetString(_T("IDS_TRYAGAIN")).c_str(), iX, iY - border, btnWidth, btnHeight );
		m_UI.AddButton( IDCANCEL, g_pApp->GetString(_T("IDS_CANCEL")).c_str(), iX, iY, btnWidth, btnHeight );
	}
	else if (buttonFlags == MB_OKCANCEL)
	{
		//The message box contains two push buttons: OK and Cancel.
		m_UI.AddButton( IDOK, g_pApp->GetString(_T("IDS_OK")).c_str(), iX, iY - border, btnWidth, btnHeight );
		m_UI.AddButton( IDCANCEL, g_pApp->GetString(_T("IDS_CANCEL")).c_str(), iX, iY, btnWidth, btnHeight );
	}
	else if (buttonFlags == MB_RETRYCANCEL)
	{
		//The message box contains two push buttons: Retry and Cancel.
		m_UI.AddButton( IDRETRY, g_pApp->GetString(_T("IDS_RETRY")).c_str(), iX, iY - border, btnWidth, btnHeight );
		m_UI.AddButton( IDCANCEL, g_pApp->GetString(_T("IDS_CANCEL")).c_str(), iX, iY, btnWidth, btnHeight );
	}
	else if (buttonFlags == MB_YESNO)
	{
		//The message box contains two push buttons: Yes and No.
		m_UI.AddButton( IDYES, g_pApp->GetString(_T("IDS_YES")).c_str(), iX, iY - border, btnWidth, btnHeight, 0x59 );
		m_UI.AddButton( IDNO, g_pApp->GetString(_T("IDS_NO")).c_str(), iX, iY, btnWidth, btnHeight, 0x4E );
	}
	else if (buttonFlags == MB_YESNOCANCEL)
	{
		//The message box contains three push buttons: Yes, No, and Cancel.
		m_UI.AddButton( IDYES, g_pApp->GetString(_T("IDS_YES")).c_str(), iX, iY - (2*border), btnWidth, btnHeight );
		m_UI.AddButton( IDNO, g_pApp->GetString(_T("IDS_NO")).c_str(), iX, iY - border, btnWidth, btnHeight );
		m_UI.AddButton( IDCANCEL, g_pApp->GetString(_T("IDS_CANCEL")).c_str(), iX, iY, btnWidth, btnHeight );
	}
	else //if (buttonFlags & MB_OK)
	{
        // The message box contains one push button: OK. This is the default.
		m_UI.AddButton( IDOK, g_pApp->GetString(_T("IDS_OK")).c_str(), iX, iY, btnWidth, btnHeight );
	}
}
Пример #3
0
//Print to screen and write to file
bool __fastcall PrintScreenAndWriteFile(
	const std::wstring Message, 
	const SSIZE_T ErrorCode, 
	const size_t Line)
{
//Get current date and time.
	tm TimeStructure;
	memset(&TimeStructure, 0, sizeof(tm));
	auto TimeValues = time(nullptr);
#if defined(PLATFORM_WIN)
	if (localtime_s(&TimeStructure, &TimeValues) > 0)
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
	if (localtime_r(&TimeValues, &TimeStructure) == nullptr)
#endif
		return false;

//Print startup time at first printing.
	time_t LogStartupTime = 0;
	if (GlobalRunningStatus.StartupTime > 0)
	{
		LogStartupTime = GlobalRunningStatus.StartupTime;
		GlobalRunningStatus.StartupTime = 0;
	}

//Print to screen.
#if defined(PLATFORM_WIN)
	if (GlobalRunningStatus.Console)
#elif defined(PLATFORM_LINUX)
	if (!GlobalRunningStatus.Daemon)
#endif
	{
		std::lock_guard<std::mutex> ScreenMutex(ScreenLock);

	//Print startup time.
		if (LogStartupTime > 0)
		{
			fwprintf_s(stderr, L"%d-%02d-%02d %02d:%02d:%02d -> Log opened at this moment.\n", 
				TimeStructure.tm_year + 1900, 
				TimeStructure.tm_mon + 1, 
				TimeStructure.tm_mday, 
				TimeStructure.tm_hour, 
				TimeStructure.tm_min, 
				TimeStructure.tm_sec);
		}

	//Print message.
		fwprintf_s(stderr, L"%d-%02d-%02d %02d:%02d:%02d -> ", 
			TimeStructure.tm_year + 1900, 
			TimeStructure.tm_mon + 1, 
			TimeStructure.tm_mday, 
			TimeStructure.tm_hour, 
			TimeStructure.tm_min, 
			TimeStructure.tm_sec);
		if (Line > 0 && ErrorCode > 0)
			fwprintf_s(stderr, Message.c_str(), Line, ErrorCode);
		else if (Line > 0)
			fwprintf_s(stderr, Message.c_str(), Line);
		else if (ErrorCode > 0)
			fwprintf_s(stderr, Message.c_str(), ErrorCode);
		else 
			fwprintf_s(stderr, Message.c_str());
	}

//Check whole file size.
	std::unique_lock<std::mutex> ErrorLogMutex(ErrorLogLock);
#if defined(PLATFORM_WIN)
	WIN32_FILE_ATTRIBUTE_DATA File_WIN32_FILE_ATTRIBUTE_DATA;
	memset(&File_WIN32_FILE_ATTRIBUTE_DATA, 0, sizeof(WIN32_FILE_ATTRIBUTE_DATA));
	if (GetFileAttributesExW(GlobalRunningStatus.Path_ErrorLog->c_str(), GetFileExInfoStandard, &File_WIN32_FILE_ATTRIBUTE_DATA) != FALSE)
	{
		LARGE_INTEGER ErrorFileSize;
		memset(&ErrorFileSize, 0, sizeof(LARGE_INTEGER));
		ErrorFileSize.HighPart = File_WIN32_FILE_ATTRIBUTE_DATA.nFileSizeHigh;
		ErrorFileSize.LowPart = File_WIN32_FILE_ATTRIBUTE_DATA.nFileSizeLow;
		if (ErrorFileSize.QuadPart > 0 && (size_t)ErrorFileSize.QuadPart >= Parameter.LogMaxSize)
		{
			if (DeleteFileW(GlobalRunningStatus.Path_ErrorLog->c_str()) != FALSE)
			{
				ErrorLogMutex.unlock();
				PrintError(LOG_LEVEL_3, LOG_MESSAGE_NOTICE, L"Old log files were deleted", 0, nullptr, 0);
				ErrorLogMutex.lock();
			}
			else {
				return false;
			}
		}
	}
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
	struct stat FileStat;
	memset(&FileStat, 0, sizeof(struct stat));
	if (stat(GlobalRunningStatus.sPath_ErrorLog->c_str(), &FileStat) == 0 && FileStat.st_size >= (off_t)Parameter.LogMaxSize)
	{
		if (remove(GlobalRunningStatus.sPath_ErrorLog->c_str()) == 0)
		{
			ErrorLogMutex.unlock();
			PrintError(LOG_LEVEL_3, LOG_MESSAGE_NOTICE, L"Old log files were deleted", 0, nullptr, 0);
			ErrorLogMutex.lock();
		}
		else {
			return false;
		}
	}
#endif

//Write to file.
#if defined(PLATFORM_WIN)
	FILE *Output = nullptr;
	if (_wfopen_s(&Output, GlobalRunningStatus.Path_ErrorLog->c_str(), L"a,ccs=UTF-8") == 0 && Output != nullptr)
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
	auto Output = fopen(GlobalRunningStatus.sPath_ErrorLog->c_str(), "a");
	if (Output != nullptr)
#endif
	{
	//Print startup time.
		if (LogStartupTime > 0)
		{
			fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Log opened at this moment.\n", 
				TimeStructure.tm_year + 1900, 
				TimeStructure.tm_mon + 1, 
				TimeStructure.tm_mday, 
				TimeStructure.tm_hour, 
				TimeStructure.tm_min, 
				TimeStructure.tm_sec);
		}

	//Print message.
		fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> ", 
			TimeStructure.tm_year + 1900, 
			TimeStructure.tm_mon + 1, 
			TimeStructure.tm_mday, 
			TimeStructure.tm_hour, 
			TimeStructure.tm_min, 
			TimeStructure.tm_sec);
		if (Line > 0 && ErrorCode > 0)
			fwprintf_s(Output, Message.c_str(), Line, ErrorCode);
		else if (Line > 0)
			fwprintf_s(Output, Message.c_str(), Line);
		else if (ErrorCode > 0)
			fwprintf_s(Output, Message.c_str(), ErrorCode);
		else 
			fwprintf_s(Output, Message.c_str());

		fclose(Output);
	}
	else {
		return false;
	}

	return true;
}
Пример #4
0
    void Update()
    {
        if(m_text==m_ss.str()){
            return;
        }

        m_text=m_ss.str();

        m_image->Clear();
        BYTE *data=m_image->GetSample();
        int pitch=m_image->GetWidth()*4;

        // フォントの生成
        LOGFONT lf = {m_fontsize, 0, 0, 0, 0, 0, 0, 0, 
            SHIFTJIS_CHARSET, OUT_TT_ONLY_PRECIS,
            CLIP_DEFAULT_PRECIS, PROOF_QUALITY, FIXED_PITCH | FF_MODERN, _T("MS 明朝")};
        HFONT hFont=CreateFontIndirect(&lf);
        if(!(hFont)){
            return;
        }

        // デバイスコンテキスト取得
        // デバイスにフォントを持たせないとGetGlyphOutline関数はエラーとなる
        HDC hdc = GetDC(NULL);
        HFONT oldFont = (HFONT)SelectObject(hdc, hFont);

        std::vector<BYTE> gryph;
        int x_pos=0;
        int y_pos=0;
        int col_size=m_fontsize/2;
        for(auto c=m_text.begin(); c!=m_text.end(); ++c){

            if(y_pos>=m_row*m_fontsize){
                break;
            }

            if(*c==L'\n'){
                y_pos+=m_fontsize+5;
                x_pos=0;
                continue;
            }

            if(x_pos+col_size>=m_col*col_size){
                y_pos+=m_fontsize+5;
                x_pos=0;
            }

            // フォントビットマップ取得
            TEXTMETRIC TM;
            GetTextMetrics( hdc, &TM );
            GLYPHMETRICS GM;
            CONST MAT2 Mat = {{0,1},{0,0},{0,0},{0,1}};
            DWORD size = GetGlyphOutline(hdc, *c, GGO_GRAY4_BITMAP, &GM, 0, NULL, &Mat);

            if(size>0){
                gryph.resize(size);
                GetGlyphOutline(hdc, *c, GGO_GRAY4_BITMAP, &GM, gryph.size(), &gryph[0], &Mat);

                // フォント情報の書き込み
                // iOfs_x, iOfs_y : 書き出し位置(左上)
                // iBmp_w, iBmp_h : フォントビットマップの幅高
                // Level : α値の段階 (GGO_GRAY4_BITMAPなので17段階)
                int iOfs_x = x_pos+GM.gmptGlyphOrigin.x;
                int iOfs_y = y_pos+TM.tmAscent - GM.gmptGlyphOrigin.y;
                int iBmp_w = GM.gmBlackBoxX + (4-(GM.gmBlackBoxX%4))%4;
                int iBmp_h = GM.gmBlackBoxY;
                int Level = 17;
                DWORD Alpha, Color;
                for(int y=iOfs_y; y<iOfs_y+iBmp_h; y++){
                    for(size_t x=iOfs_x; x<iOfs_x+GM.gmBlackBoxX; x++){
                        Alpha = (255 * gryph[x-iOfs_x + iBmp_w*(y-iOfs_y)]) / (Level-1);
                        Color = 0x00ffffff | (Alpha<<24);
                        memcpy((BYTE*)data + pitch*y + 4*x, &Color, sizeof(DWORD));
                    }
                }
                x_pos+=iBmp_w;
            }
            else{
                x_pos+=col_size;
            }
        }

        // デバイスコンテキストとフォントハンドルの開放
        SelectObject(hdc, oldFont);
        DeleteObject(hFont);
        ReleaseDC(NULL, hdc);
    }
void MainWindow::donationButtonPressed() {
    MessageBox(0, L"OMG! Wow! Thanks!\n(Seriously, glad you enjoy my little program, thanks for considering)", L"Wow!", MB_OK);
    ShellExecute(0, 0, donationURL.c_str(), 0, 0 , SW_SHOW );
}
Пример #6
0
    InstallDialog()
    {
        SetWindowTitle(L"Taglib Handler Setup");
        SetMainInstructionText(L"Choose an install type");
		SetCommonButtons(TDCBF_CANCEL_BUTTON);
		content_text = L"To work, Taglib Handler needs to be both registered with the system, and registered with the file extensions which it will serve.";
		SetMainIcon(TD_SHIELD_ICON);
		SetContentText(content_text.c_str());
		SetDefaultButton(Button_DefaultInstall);

		installloc_x86 = getProgramFiles();
		if (onx64)
			installloc_x64 = getProgramFiles(true);

		expanded_msg = L"The installation will proceed as follows:\n"
			L"1) The files will be copied to '" + hyperlink(installloc_x86) + hyperlink(installloc_x86 + suffix, suffix) 
			+ (onx64 ? L"' (for the 32-bit binaries, and to '"
			+ hyperlink(installloc_x64) + hyperlink(installloc_x64 + suffix, suffix) + L"' for the 64-bit binaries)" : L"") +
			L".\n2) The DLL" + (onx64 ? L"s" : L"") + L" will be registered with the system.\n"
			L"3) Optionally, the file associations will be made:\n" +
			L"  • ";
		
		for (size_t i=0; i<ARRAYSIZE(extensions); ++i)
			expanded_msg = expanded_msg + extensions[i] +
				(i == ARRAYSIZE(extensions) - 2 ? L" and " : 
				(i != ARRAYSIZE(extensions) - 1 ? L", " : L" are supported.\n"));

		extguid_x32 = read_extension_guids(false);
		if (onx64)
		{
			extguid_x64 = read_extension_guids(true);

#if 0
			typedef std::map<std::wstring, std::pair<std::wstring, std::wstring> > guidext_t;

			guidext_t nonmatching;

			for (size_t i=0; i<ARRAYSIZE(extensions); ++i)
				if (extguid_x64[extensions[i]] != extguid_x32[extensions[i]])
					nonmatching[extensions[i]] = std::make_pair(extguid_x32[extensions[i]], extguid_x64[extensions[i]]);

			expanded_msg += L"  • There are " + boost::lexical_cast<std::wstring>(nonmatching.size()) + 
				L" extensions with differing x32 and x64 handlers" +
				(nonmatching.empty() ? L"." : L":") +
				L"\n";

			for (guidext_t::const_iterator it = nonmatching.begin(); it != nonmatching.end(); ++it)
				expanded_msg += L"    ◦ " + it->first + L" is associated with " + guidtoname(it->second.first, false) +
					L" (32) and " + guidtoname(it->second.second, true) + L" (64)\n";
#endif
		}

		struct NameCache
		{
			bool isx64;
			NameCache(bool isx64) : isx64(isx64) {}

			typedef std::map<std::wstring, std::wstring> guidname_t;
			
			std::wstring name(const std::wstring& guid) const
			{
				guidname_t::const_iterator it;
				if ((it = names.find(guid)) != names.end())
					return it->second;
				return names[guid] = guidtoname(guid, isx64);
			}
		private:
			mutable guidname_t names;
		} namecache32(false), namecache64(true);
		
		typedef std::map<std::pair<std::wstring, std::wstring>, std::set<std::wstring> > namesext_t;
		namesext_t nem;

		for (size_t i=0; i<ARRAYSIZE(extensions); ++i)
			nem[std::make_pair(
				namecache32.name(extguid_x32[extensions[i]]),(onx64 ? 
				namecache64.name(extguid_x64[extensions[i]]) : L""))].insert(extensions[i]);

		for (namesext_t::const_iterator it = nem.begin(); it != nem.end(); ++it)
			expanded_msg += L"    ◦ " + hrlist(it->second) + L" currently use" + (it->second.size() == 1 ? L"s" : L"") + L" " + 
			it->first.first + (onx64 ? (it->first.first == it->first.second ? 
			L" (both 32 and 64)" : L" (32) and " + it->first.second + L" (64)") : L"") + L".\n";

		const std::wstring def32 = namecache32.name(default_guid), def64 = namecache64.name(default_guid);

		expanded_msg = expanded_msg + L"  • By default, only ";

		for (size_t i=0; i<ARRAYSIZE(default_assoc); ++i)
			expanded_msg = expanded_msg + default_assoc[i] +
				(i == ARRAYSIZE(default_assoc) - 2 ? L" and " : 
				(i != ARRAYSIZE(default_assoc) - 1 ? L", " : L"")); 

		expanded_msg = expanded_msg + 
			L" have handlers, th" + (onx64 ? L"ese are" : L"is is") + L" called '" + 
			def32 + L"'" + (onx64 ? (def32 == def64 ? L" (both 32 and 64)" : L" and '" + def64 + 
			L"' (64)") : L"") + L".";

		SetExpandedInformationText(expanded_msg.c_str());

        static TASKDIALOG_BUTTON buttons[] =
        {
            { Button_DefaultInstall, L"Default Install (recommended)\nRegister with the system and for supported extensions not already claimed" },
            { Button_AllExts, L"Install For All Extensions\nRegister with the system and for all supported extensions" },
			{ Button_RestoreDefault, L"Uninstall\nRestore the system to the Windows default settings" },
        };

        SetButtons(buttons,
                   _countof(buttons));

        ModifyFlags(0, TDF_ALLOW_DIALOG_CANCELLATION |
                       TDF_USE_COMMAND_LINKS |
                       TDF_EXPAND_FOOTER_AREA |
					   TDF_ENABLE_HYPERLINKS);
    }
Пример #7
0
bool IsFilename(const std::wstring& str) {
    // See if we can access the passed in value
    return (GetFileAttributes(str.c_str()) != INVALID_FILE_ATTRIBUTES);
}
Пример #8
0
//-------------------------------------------------------------------------------------
bool Script::install(const wchar_t* pythonHomeDir, std::wstring pyPaths, const char* moduleName, COMPONENT_TYPE componentType)
{
	std::wstring pySysPaths = SCRIPT_PATH;
	wchar_t* pwpySysResPath = char2wchar(const_cast<char*>(Resmgr::getPySysResPath().c_str()));
	kbe_replace(pySysPaths, L"../../res/", pwpySysResPath);
	pyPaths += pySysPaths;
	free(pwpySysResPath);

#if KBE_PLATFORM == PLATFORM_WIN32
	Py_SetPythonHome(const_cast<wchar_t*>(pythonHomeDir));								// 先设置python的环境变量
#else
	std::wstring fs = L";";
	std::wstring rs = L":";
	size_t pos = 0; 

	while(true)
	{ 
		pos = pyPaths.find(fs, pos);
		if (pos == std::wstring::npos) break;
		pyPaths.replace(pos, fs.length(), rs);
	}  

	Py_SetPath(pyPaths.c_str()); 
	char* tmpchar = wchar2char(const_cast<wchar_t*>(pyPaths.c_str()));
	DEBUG_MSG("Script::install: paths=%s.\n", tmpchar);
	free(tmpchar);
#endif
	// Initialise python
	// Py_VerboseFlag = 2;
	Py_FrozenFlag = 1;

	// Warn if tab and spaces are mixed in indentation.
	// Py_TabcheckFlag = 1;
	Py_NoSiteFlag = 1;
	Py_IgnoreEnvironmentFlag = 1;
	Py_Initialize();                      												// python解释器的初始化  
    if (!Py_IsInitialized())
    {
    	ERROR_MSG("Script::install::Py_Initialize is failed!\n");
        return false;
    } 

#if KBE_PLATFORM == PLATFORM_WIN32
	PySys_SetPath(pyPaths.c_str());
#endif

	PyObject *m = PyImport_AddModule("__main__");

	module_ = PyImport_AddModule(moduleName);										// 添加一个脚本基础模块
	if (module_ == NULL)
		return false;
	
	const char* componentName = COMPONENT_NAME_EX(componentType);
	if (PyModule_AddStringConstant(module_, "component", componentName))
	{
		ERROR_MSG( "Script::init: Unable to set KBEngine.component to %s\n",
			componentName );
		return false;
	}
	
	// 注册产生uuid方法到py
	APPEND_SCRIPT_MODULE_METHOD(module_,		genUUID64,			__py_genUUID64,					METH_VARARGS,			0);
	
#ifndef KBE_SINGLE_THREADED
	s_pOurInitTimeModules = PyDict_Copy( PySys_GetObject( "modules" ) );
	s_pMainThreadState = PyThreadState_Get();
	s_defaultContext = s_pMainThreadState;
	PyEval_InitThreads();

	KBEConcurrency::setMainThreadIdleFunctions(
		&Script::releaseLock, &Script::acquireLock );
#endif

	ScriptStdOutErr::installScript(NULL);											// 安装py重定向模块
	ScriptStdOutErrHook::installScript(NULL);

	static struct PyModuleDef moduleDesc =   
	{  
			 PyModuleDef_HEAD_INIT,  
			 moduleName,  
			 "This module is created by KBEngine!",  
			 -1,  
			 NULL  
	};  

	PyModule_Create(&moduleDesc);													// 初始化基础模块
	PyObject_SetAttrString(m, moduleName, module_);									// 将模块对象加入main

	pyStdouterr_ = new ScriptStdOutErr();											// 重定向python输出
	pyStdouterrHook_ = new ScriptStdOutErrHook();
	
	if(!pyStdouterr_->install()){													// 安装py重定向脚本模块
		ERROR_MSG("Script::install::pyStdouterr_->install() is failed!\n");
		SCRIPT_ERROR_CHECK();
		return false;
	}
	
	Pickler::initialize();
	Copy::initialize();
	Uuid::initialize();

	math::installModule("Math");
	INFO_MSG("Script::install is successfully!\n");
	return true;
}
Пример #9
0
bool BFCPFloorControlServer::RevokeFloorRequest(int floorRequestId, std::wstring statusInfo)
{
	::Debug("BFCPFloorControlServer::RevokeFloorRequest() | start | [floorRequestId: %d]\n", floorRequestId);

	BFCPFloorRequest *floorRequest = GetFloorRequest(floorRequestId);
	if (! floorRequest) {
		::Error("BFCPFloorControlServer::RevokeFloorRequest() | FloorRequest '%d' does not exist\n", floorRequestId);
		return false;
	}


	/* Check that the FloorRequest is in Granted status. */

	if (! floorRequest->IsGranted()) {
		::Error("BFCPFloorControlServer::RevokeFloorRequest() | cannot deny FloorRequest '%d' which is in status 'Granted'\n", floorRequestId);
		return false;
	}


	/* Update the current FloorRequest to "Revoked" and send the FloorRequestStatus notification
	 * to the FloorRequest sender. */

	::Debug("BFCPFloorControlServer::RevokeFloorRequest() | FloorRequest '%d' before beeing revoked:\n", floorRequestId);
	floorRequest->Dump();

	// Update the FloorRequest status to "Revoked".
	::Log("BFCPFloorControlServer::RevokeFloorRequest() | FloorRequest '%d' has been revoked\n", floorRequestId);
	floorRequest->SetStatus(BFCPAttrRequestStatus::Revoked);

	// Notify to the FloorRequest sender with a "Revoked" FloorRequestStatus notification.
	::Debug("BFCPFloorControlServer::RevokeFloorRequest() | sending 'Revoked' FloorRequestStatus notification for FloorRequest '%d'\n", floorRequestId);
	BFCPMsgFloorRequestStatus *floorRequestStatus = floorRequest->CreateFloorRequestStatus();
	if (! statusInfo.empty())
		floorRequestStatus->SetDescription(statusInfo);

	// Send the FloorRequestStatus notification to the requester of the FloorRequest.
	SendMessage(floorRequestStatus);

	// Delete it.
	delete floorRequestStatus;


	/* Notify with FloorStatus notifications to users who queried the status of any of the floors
	 * in the current FloorRequest. */

	NotifyForFloorRequest(floorRequest);


	/* Notify the chair. */

	// But first remove the FloorRequest from the map so in the ugly case in which the
	// chair calls to RevokeFloor() for this same FloorRequest it will fail.
	this->floorRequests.erase(floorRequestId);

	if (! this->ending) {
		::Debug("BFCPFloorControlServer::RevokeFloorRequest() | calling listener->onFloorReleased(%d)\n", floorRequestId);
		this->listener->onFloorReleased(floorRequestId, floorRequest->GetBeneficiaryId(), floorRequest->GetFloorIds());
		::Debug("BFCPFloorControlServer::RevokeFloorRequest() | listener->onFloorReleased(%d) returns\n", floorRequestId);
	}


	/* Delete the FloorRequest. */

	// NOTE: the FloorRequest may has been removed by the chair when notified onFloorReleased, so check it!
	if (GetFloorRequest(floorRequestId)) {
		delete floorRequest;
	}

	::Debug("BFCPFloorControlServer::RevokeFloorRequest() | end | [floorRequestId: %d]\n", floorRequestId);

	return true;
}
Пример #10
0
/////////////////////////
// 表示
void CLog::Log(std::wstring str)
{
	str += L"\n";
	::OutputDebugStringW(str.c_str());
	wprintf(str.c_str());
}
Пример #11
0
void Window::SetCaption(const std::wstring& caption)
{
    SetWindowText(windowHandle, caption.c_str());
}
Пример #12
0
void DVLib::FileCopy(const std::wstring& from, const std::wstring& to, bool overwrite)
{
	CHECK_WIN32_BOOL(::CopyFileW(from.c_str(), to.c_str(), overwrite),
		L"Error copying \"" << from << L"\" to \"" << to << L"\"");
}
Пример #13
0
void DVLib::FileDelete(const std::wstring& filename)
{
	CHECK_WIN32_BOOL(::DeleteFileW(filename.c_str()),
		L"Error deleting \"" << filename << L"\"");
}
Пример #14
0
bool DVLib::ResourceExists(HMODULE h, const std::wstring& resource, const std::wstring& type)
{
	return (NULL != ::FindResource(h, resource.c_str(), type.c_str()));
}
Пример #15
0
std::wstring hyperlink(const std::wstring thing, const std::wstring text = std::wstring())
{
	return L"<a href=\"" + thing + L"\">" + (text.empty() ? thing : text)+ L"</a>";
}
Пример #16
0
float Font::measureWidth(const std::wstring &text,
    float fontSize,
    bool precise) const {
  return measureWidth(text, 0, text.length(), fontSize, precise);
}
Пример #17
0
	void copyFile(const std::wstring& from, const std::wstring& to, bool failifexists = false)
	{
		if (!CopyFileTransacted(from.c_str(), to.c_str(), NULL, NULL, NULL,
			(failifexists ? COPY_FILE_FAIL_IF_EXISTS : 0), transaction))
			throw win32_error(L"Couldn't copy '" + from + L"' to '" + to + L"'");
	}
Пример #18
0
		bool operator()(const std::wstring& _Left, const std::wstring& _Right) const
		{
			return _wcsicmp(_Left.c_str(), _Right.c_str()) < 0;//忽略大小写
		}
Пример #19
0
void GUIManager::updateTeamsViewer()
{
    TeamManager const* teamManager = _engine->getTeamManager();
    std::map<std::string, TeamManager::Team> const& infos = teamManager->getTeamsInfo();
    
    _teamTable->clear();
    _teamTable->addColumn(L"Teams");
    _teamTable->addColumn(L"1");
    _teamTable->addColumn(L"2");
    _teamTable->addColumn(L"3");
    _teamTable->addColumn(L"4");
    _teamTable->addColumn(L"5");
    _teamTable->addColumn(L"6");
    _teamTable->addColumn(L"7");
    _teamTable->addColumn(L"8");
    _teamTable->addColumn(L"Food");
    _teamTable->addColumn(L"s1");
    _teamTable->addColumn(L"s2");
    _teamTable->addColumn(L"s3");
    _teamTable->addColumn(L"s4");
    _teamTable->addColumn(L"s5");
    _teamTable->addColumn(L"Egg");
    _teamTable->addRow(0);
    
    //    IGUIWindow * skillWindow = irrGui->addWindow(rect<s32>(30, 100, 330, 600), false, L"Skills");
    //skillWindow->setVisible(false);
    //IGUIStaticText * skillCat1 = irrGui->addStaticText(L"Gathering skills",rect<s32>(10, 30, 290, 45),false,true,skillWindow);
    //skillCat1->setOverrideFont(bigFont);
    //IGUITable * skillTree = irrGui->addTable(rect<s32>(10, 55, 290, 110),skillWindow, -1, false);
    //skillTree->addColumn(L"Name");
    //skillTree->addColumn(L"Skill");
    //skillTree->setColumnWidth(0,220);
    //skillTree->setColumnWidth(1,50);
    //skillTree->setColumnOrdering(0, EGCO_FLIP_ASCENDING_DESCENDING);
    //skillTree->setColumnOrdering(1, EGCO_FLIP_ASCENDING_DESCENDING);
    
    s32 columnCount = _teamTable->getColumnCount();
    float columnSize = (float)_x / (float)(columnCount) * (1.f/3.f);
//    for (s32 i = 0; i < columnCount; i++)
//	_teamTable->setColumnWidth(i, columnSize);
    
    int i = 0;
    for (std::pair<std::string, TeamManager::Team>&& info : infos) {
	const std::string name = info.first;
	const std::wstring wname(name.begin(), name.end());
	if (_teamTable->getRowCount() == i)
	    _teamTable->addRow(i);
	_teamTable->setCellText(i,0, wname.c_str());
	for (int j = 1; j <= Assets::LEVEL_MAX; j++)
	{
	    const std::wstring wlevel = intToWstring(info.second.players_by_level[j - 1]);
	    _teamTable->setCellText(i,j, wlevel.c_str());
	}
	for (int j = Assets::LEVEL_MAX + 1; j < RESSOURCE_TYPE_COUNT + Assets::LEVEL_MAX; j++)
	{
	    const std::wstring wressource = intToWstring(info.second.ressources[j - Assets::LEVEL_MAX - 1]);
	    _teamTable->setCellText(i,j, wressource.c_str());
	}
	const std::wstring wegg = intToWstring(info.second.eggs);
	_teamTable->setCellText(i,columnCount-1, wegg.c_str());
	i++;
    }
}
Пример #20
0
	static bool execute(const std::wstring &cmd, const std::wstring &args)
	{
		return (int)ShellExecuteW(NULL, NULL, cmd.c_str(), args.c_str(), NULL, SW_SHOWNORMAL) > 32;
	}
Пример #21
0
sstring::sstring(const std::wstring& cp)
{
	*this = "";
	for(int i = 0 ; i < cp.length() ; i++)
		*this += cp[i];
}
Пример #22
0
	static bool open(const std::wstring &path)
	{
		return (int)ShellExecuteW(NULL, L"open", path.c_str(), NULL, NULL, SW_SHOWNORMAL) > 32;
	}
void MainWindow::helpButtonPressed() {
    ShellExecute(0, 0, threadURL.c_str(), 0, 0 , SW_SHOW );
}
Пример #24
0
		inline void open_stream(std::ifstream & _stream, const std::wstring& _wide) { _stream.open(_wide.c_str()); }
Пример #25
0
void WorldSession::BuildListAuctionItems(std::vector<AuctionEntry*> const& auctions, WorldPacket& data, std::wstring const& wsearchedname, uint32 listfrom, uint32 levelmin,
        uint32 levelmax, uint32 usable, uint32 inventoryType, uint32 itemClass, uint32 itemSubClass, uint32 quality, uint32& count, uint32& totalcount, bool isFull)
{
    int loc_idx = _player->GetSession()->GetSessionDbLocaleIndex();

    for (std::vector<AuctionEntry*>::const_iterator itr = auctions.begin(); itr != auctions.end(); ++itr)
    {
        AuctionEntry* Aentry = *itr;
        Item* item = sAuctionMgr.GetAItem(Aentry->itemGuidLow);
        if (!item)
            continue;

        if (isFull)
        {
            ++count;
            Aentry->BuildAuctionInfo(data);
        }
        else
        {
            ItemPrototype const* proto = item->GetProto();

            if (itemClass != 0xffffffff && proto->Class != itemClass)
                continue;

            if (itemSubClass != 0xffffffff && proto->SubClass != itemSubClass)
                continue;

            if (inventoryType != 0xffffffff && proto->InventoryType != inventoryType)
                continue;

            if (quality != 0xffffffff && proto->Quality < quality)
                continue;

            if (levelmin != 0x00 && (proto->RequiredLevel < levelmin || (levelmax != 0x00 && proto->RequiredLevel > levelmax)))
                continue;

            if (usable != 0x00)
            {
                if (_player->CanUseItem(item) != EQUIP_ERR_OK)
                    continue;

                if (proto->Class == ITEM_CLASS_RECIPE)
                {
                    if (SpellEntry const* spell = sSpellStore.LookupEntry(proto->Spells[0].SpellId))
                    {
                        if (_player->HasSpell(spell->EffectTriggerSpell[EFFECT_INDEX_0]))
                            continue;
                    }
                }
            }

            std::string name = proto->Name1;
            sObjectMgr.GetItemLocaleStrings(proto->ItemId, loc_idx, &name);

            if (!wsearchedname.empty() && !Utf8FitTo(name, wsearchedname))
                continue;

            if (count < 50 && totalcount >= listfrom)
            {
                ++count;
                Aentry->BuildAuctionInfo(data);
            }
        }

        ++totalcount;
    }
}
Пример #26
0
std::string StringUtils::toShortString( std::wstring wideString )
{
	std::string shortString;
	return shortString.assign( wideString.begin(), wideString.end() );
}
Пример #27
0
bool
Portfolio::save( const std::wstring& filename ) const
{
    return impl_->getDocument().save_file( filename.c_str() );
}
Пример #28
0
void CMainWindow::RunCommand(const std::wstring& command)
{
    tstring tortoiseProcPath = GetAppDirectory() + _T("TortoiseProc.exe");
    CCreateProcessHelper::CreateProcessDetached(tortoiseProcPath.c_str(), const_cast<TCHAR*>(command.c_str()));
}
Пример #29
0
/*
** Executes a custom bang.
**
*/
void CMeasureScript::Command(const std::wstring& command)
{
	std::string str = ConvertToUTF8(command.c_str());
	m_LuaScript->RunString(str.c_str());
}
Пример #30
0
std::wstring IniFile::ReadString(const wchar_t* section, const wchar_t* key, const std::wstring& def)
{
	wchar_t ret_string[MAX_PATH];
	GetPrivateProfileString(section, key, def.c_str(), ret_string, MAX_PATH, _file_name.c_str());
	return ret_string;
}