Example #1
0
CAddressBar::CBnt::CBnt(int64 ID,tstring text)
			:ButtonItem(ID,text.c_str(),NULL,false)
{
	
};
Example #2
0
int Helium::Execute( const tstring& command, tstring& output, bool showWindow )
{
    HANDLE hReadPipe;
    HANDLE hWritePipe;
    SECURITY_ATTRIBUTES sa;
    sa.nLength              = sizeof(sa);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle       = TRUE;
    if( !CreatePipe( &hReadPipe, &hWritePipe, &sa, 0 ) )
    {
        return -1;
    }

    STARTUPINFO          si;
    memset( &si, 0, sizeof(si) );
    si.cb          = sizeof(si);
    si.dwFlags     = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    si.wShowWindow = static_cast<int>( showWindow );
    si.hStdOutput  = hWritePipe;
    si.hStdError   = hWritePipe;      

    PROCESS_INFORMATION  pi;
    memset( &pi, 0, sizeof( pi ) );

    if( !CreateProcess(
        NULL,                                                 // filename
        (tchar_t*) command.c_str(),                           // command line for child
        NULL,                                                 // process security descriptor
        NULL,                                                 // thread security descriptor
        TRUE,                                                 // inherit handles?
        showWindow ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW,   // creation flags
        NULL,                                                 // inherited environment address
        NULL,                                                 // startup dir; NULL = start in current
        &si,                                                  // pointer to startup info (input)
        &pi ) )                                               // pointer to process info (output)
    {
        ::CloseHandle( hReadPipe );
        ::CloseHandle( hWritePipe );
        return -1;
    }

    // close the write end of the pipe so the child will terminate it with EOF
    ::CloseHandle( hWritePipe );

    // read from the pipe until EOF condition reached
    tchar_t buffer[80];
    unsigned long count;
    tstringstream stream;
    BOOL success = TRUE;
    do
    {
        while ( success = ReadFile( hReadPipe, buffer, sizeof(buffer), &count, NULL ) )
        {
            if( success )
            {
                stream.write( buffer, count );
            }
            else
            {
                if ( ::GetLastError() == ERROR_BROKEN_PIPE )
                {
                    break;
                }
                else
                {
                    return -1;
                }
            }
        }
    } while( success && count );

    // done reading, close our read pipe
    ::CloseHandle( hReadPipe );

    // copy output string
    output = stream.str();

    // get exit code
    DWORD result = 0;
    BOOL codeResult = ::GetExitCodeProcess( pi.hProcess, &result );
    HELIUM_ASSERT( codeResult );

    // close the process handle
    ::CloseHandle( pi.hProcess );
    ::CloseHandle( pi.hThread );

    return result;
}
Example #3
0
 gcc_pure
 tstring::const_pointer GetName() const {
   return task_name.c_str();
 }
void CQuotesProviderBase::WriteContactRate(MCONTACT hContact,double dRate,const tstring& rsSymbol/* = ""*/)
{
	time_t nTime = ::time(NULL);

	if(false == rsSymbol.empty())
	{
		db_set_ts(hContact,QUOTES_PROTOCOL_NAME,DB_STR_QUOTE_SYMBOL,rsSymbol.c_str());
	}

	double dPrev = 0.0;
	bool bValidPrev = Quotes_DBReadDouble(hContact,QUOTES_PROTOCOL_NAME,DB_STR_QUOTE_CURR_VALUE,dPrev);
	if(true == bValidPrev)
	{
		Quotes_DBWriteDouble(hContact,QUOTES_PROTOCOL_NAME,DB_STR_QUOTE_PREV_VALUE,dPrev);
	}

	Quotes_DBWriteDouble(hContact,QUOTES_PROTOCOL_NAME,DB_STR_QUOTE_CURR_VALUE,dRate);
	db_set_dw(hContact,QUOTES_PROTOCOL_NAME,DB_STR_QUOTE_FETCH_TIME,nTime);

	tstring sSymbol = rsSymbol;

	tostringstream oNick;
	oNick.imbue(GetSystemLocale());
	if(false == m_sContactListFormat.empty())
	{
		tstring s = format_rate(this,hContact,m_sContactListFormat,dRate);
		oNick << s;
	}
	else
	{
		if(true == sSymbol.empty())
		{
			sSymbol = Quotes_DBGetStringT(hContact,QUOTES_PROTOCOL_NAME,DB_STR_QUOTE_SYMBOL);
		}
		oNick << std::setfill(_T(' ')) << std::setw(10) << std::left << sSymbol << std::setw(6) << std::right << dRate;
	}
	CTendency tendency;

	if (true == tendency.Parse(this, m_sTendencyFormat, hContact))
		do_set_contact_extra_icon(hContact, tendency);

	db_set_ts(hContact,LIST_MODULE_NAME,CONTACT_LIST_NAME,oNick.str().c_str());

	tstring sStatusMsg = format_rate(this,hContact,m_sStatusMsgFormat,dRate);
	if(false == sStatusMsg.empty())
	{
		db_set_ts(hContact,LIST_MODULE_NAME,STATUS_MSG_NAME,sStatusMsg.c_str());
	}
	else
	{
		db_unset(hContact,LIST_MODULE_NAME,STATUS_MSG_NAME);
	}

	bool bUseContactSpecific = (db_get_b(hContact,QUOTES_PROTOCOL_NAME,DB_STR_CONTACT_SPEC_SETTINGS,0) > 0);

	CAdvProviderSettings global_settings(this);

	WORD dwMode = (bUseContactSpecific) 
		? db_get_w(hContact,QUOTES_PROTOCOL_NAME,DB_STR_QUOTE_LOG,static_cast<WORD>(lmDisabled))
		: global_settings.GetLogMode();
	if(dwMode&lmExternalFile)
	{
		bool bAdd = true;
		bool bOnlyIfChanged = (bUseContactSpecific)
			? (db_get_w(hContact,QUOTES_PROTOCOL_NAME,DB_STR_QUOTE_LOG_FILE_CONDITION,1) > 0)
			: global_settings.GetLogOnlyChangedFlag();
		if(true == bOnlyIfChanged)
		{
			bAdd = ((false == bValidPrev) || (false == IsWithinAccuracy(dRate,dPrev)));
		}
		if(true == bAdd)
		{
			tstring sLogFileName =  (bUseContactSpecific)
				? Quotes_DBGetStringT(hContact,QUOTES_PROTOCOL_NAME,DB_STR_QUOTE_LOG_FILE,global_settings.GetLogFileName().c_str())
				: global_settings.GetLogFileName();

			if(true == sSymbol.empty())
			{
				sSymbol = Quotes_DBGetStringT(hContact,QUOTES_PROTOCOL_NAME,DB_STR_QUOTE_SYMBOL);
			}

			sLogFileName = GenerateLogFileName(sLogFileName,sSymbol);

			tstring sFormat = global_settings.GetLogFormat();
			if(bUseContactSpecific)
			{
				CQuotesProviderVisitorDbSettings visitor;
				Accept(visitor);
				sFormat = Quotes_DBGetStringT(hContact,QUOTES_PROTOCOL_NAME,DB_STR_QUOTE_FORMAT_LOG_FILE,visitor.m_pszDefLogFileFormat);
			}

			log_to_file(this,hContact,dRate,sLogFileName,sFormat);
		}
	}
	if(dwMode&lmInternalHistory)
	{
		bool bAdd = true;
		bool bOnlyIfChanged = (bUseContactSpecific) 
			? (db_get_w(hContact,QUOTES_PROTOCOL_NAME,DB_STR_QUOTE_HISTORY_CONDITION,1) > 0)
			: global_settings.GetHistoryOnlyChangedFlag();

		if(true == bOnlyIfChanged)
		{
			bAdd = ((false == bValidPrev) || (false == IsWithinAccuracy(dRate,dPrev)));
		}
		if(true == bAdd)
		{
			tstring sFormat =  (bUseContactSpecific)
				? Quotes_DBGetStringT(hContact,QUOTES_PROTOCOL_NAME,DB_STR_QUOTE_FORMAT_HISTORY,global_settings.GetHistoryFormat().c_str())
				: global_settings.GetHistoryFormat();

			log_to_history(this,hContact,dRate,nTime,sFormat);
		}
	}

	if(dwMode&lmPopup)
	{
		bool bOnlyIfChanged = (bUseContactSpecific) 
			? (1 == db_get_b(hContact,QUOTES_PROTOCOL_NAME,DB_STR_QUOTE_POPUP_CONDITION,1) > 0)
			: global_settings.GetShowPopupIfValueChangedFlag();
		if((false == bOnlyIfChanged) 
			|| ((true == bOnlyIfChanged) && (true == bValidPrev) && (false == IsWithinAccuracy(dRate,dPrev))))
		{
			tstring sFormat =  (bUseContactSpecific)
				? Quotes_DBGetStringT(hContact,QUOTES_PROTOCOL_NAME,DB_STR_QUOTE_FORMAT_POPUP,global_settings.GetPopupFormat().c_str())
				: global_settings.GetPopupFormat();

			CPopupSettings ps = *(global_settings.GetPopupSettingsPtr());
			ps.InitForContact(hContact);
			show_popup(this,hContact,dRate,tendency,sFormat,ps);
		}
	}


	if((true == IsOnline()))
	{
		SetContactStatus(hContact,ID_STATUS_ONLINE);
	}
}
// !SMT!-UI
void UserInfoSimple::addSummaryMenu()
{
	// TODO: move obtain information about the user in the UserManager
	if (!getUser())
		return;
		
	CWaitCursor l_cursor_wait; //-V808
	
	UserInfoGuiTraits::userSummaryMenu.InsertSeparatorLast(getUser()->getLastNickT());
	
	ClientManager::UserParams l_params;
	if (ClientManager::getUserParams(getUser(), l_params))
	{
		tstring userInfo = TSTRING(SLOTS) + _T(": ") + Util::toStringW(l_params.m_slots) + _T(", ") + TSTRING(SHARED) + _T(": ") + Util::formatBytesW(l_params.m_bytesShared);
		
		if (l_params.m_limit)
		{
			userInfo += _T(", ") + TSTRING(SPEED_LIMIT) + _T(": ") + Util::formatBytesW(l_params.m_limit) + _T('/') + WSTRING(SEC);
		}
		
		UserInfoGuiTraits::userSummaryMenu.AppendMenu(MF_STRING | MF_DISABLED, IDC_NONE, userInfo.c_str());
		
		const time_t slot = UploadManager::getReservedSlotTime(getUser());
		if (slot)
		{
			const tstring note = TSTRING(EXTRA_SLOT_TIMEOUT) + _T(": ") + Util::formatSecondsW((slot - GET_TICK()) / 1000);
			UserInfoGuiTraits::userSummaryMenu.AppendMenu(MF_STRING | MF_DISABLED, IDC_NONE, note.c_str());
		}
		
		if (!l_params.m_ip.empty())
		{
			UserInfoGuiTraits::userSummaryMenu.AppendMenu(MF_STRING | MF_DISABLED, IDC_NONE, l_params.getTagIP().c_str());
			
			const Util::CustomNetworkIndex l_location = Util::getIpCountry(l_params.m_ip, true); // Не обращаемся в базу данных
			const tstring loc = TSTRING(COUNTRY) + _T(": ") + l_location.getCountry() + _T(", ") + l_location.getDescription();
			UserInfoGuiTraits::userSummaryMenu.AppendMenu(MF_STRING | MF_DISABLED, IDC_NONE, loc.c_str());
			
			HubFrame::addDupeUsersToSummaryMenu(l_params);
		}
		else
		{
			UserInfoGuiTraits::userSummaryMenu.AppendMenu(MF_STRING | MF_DISABLED, IDC_NONE, l_params.getTagIP().c_str());
			HubFrame::addDupeUsersToSummaryMenu(l_params);
		}
	}
	
	//UserInfoGuiTraits::userSummaryMenu.AppendMenu(MF_SEPARATOR);
	
	bool caption = false;
	{
		UploadManager::LockInstanceQueue lockedInstance;
		const auto& users = lockedInstance->getUploadQueueL();
		for (auto uit = users.cbegin(); uit != users.cend(); ++uit)
		{
			if (uit->getUser() == getUser())
			{
				uint8_t l_count_menu = 0; // [+]PPA
				for (auto i = uit->m_waiting_files.cbegin(); i != uit->m_waiting_files.cend(); ++i)
				{
					if (!caption)
					{
						UserInfoGuiTraits::userSummaryMenu.InsertSeparatorLast(TSTRING(USER_WAIT_MENU));
						caption = true;
					}
					const tstring note =
					    _T('[') +
					    Util::toStringW((double)(*i)->getPos() * 100.0 / (double)(*i)->getSize()) +
					    _T("% ") +
					    Util::formatSecondsW(GET_TIME() - (*i)->getTime()) +
					    _T("]\t") +
					    Text::toT((*i)->getFile());
					UserInfoGuiTraits::userSummaryMenu.AppendMenu(MF_STRING | MF_DISABLED, IDC_NONE, note.c_str());
					if (l_count_menu++ == 10) //[+]PPA
					{
						UserInfoGuiTraits::userSummaryMenu.AppendMenu(MF_STRING | MF_DISABLED, IDC_NONE, _T("..."));
						break;
					}
				}
			}
		}
	}
	caption = false;
	{
		uint8_t l_count_menu = 0; // [+]PPA
		RLock(*QueueItem::g_cs);
		QueueManager::LockFileQueueShared l_fileQueue;
		const auto& downloads = l_fileQueue.getQueueL();
		for (auto j = downloads.cbegin(); j != downloads.cend(); ++j)
		{
			const QueueItemPtr& aQI = j->second;
			const bool src = aQI->isSourceL(getUser());
			bool badsrc = false;
			if (!src)
			{
				badsrc = aQI->isBadSourceL(getUser());
			}
			if (src || badsrc)
			{
				if (!caption)
				{
					UserInfoGuiTraits::userSummaryMenu.InsertSeparatorLast(TSTRING(NEED_USER_FILES_MENU));
					caption = true;
				}
				tstring note = Text::toT(aQI->getTarget());
				if (aQI->getSize() > 0)
				{
					note += tstring(_T("\t(")) + Util::toStringW((double)aQI->getDownloadedBytes() * 100.0 / (double)aQI->getSize()) + tstring(_T("%)"));
				}
				const UINT flags = MF_STRING | MF_DISABLED | (badsrc ? MF_GRAYED : 0);
				UserInfoGuiTraits::userSummaryMenu.AppendMenu(flags, IDC_NONE, note.c_str());
				if (l_count_menu++ == 10) //[+]PPA
				{
					UserInfoGuiTraits::userSummaryMenu.AppendMenu(MF_STRING | MF_DISABLED, IDC_NONE, _T("..."));
					break;
				}
			}
		}
	}
}
Example #6
0
void OMenu::appendThis(const tstring& aTitle, bool appendSeparator /*false*/) {
	dcassert(parent);
	parent->AppendMenu(MF_POPUP, (UINT_PTR)(HMENU)*this, aTitle.c_str());
	if (appendSeparator)
		InsertSeparatorFirst(aTitle);
}
Example #7
0
void WindowsRegistry::addAllJreJvms(vector<JVMInfo>* pVecJvmInfo, const tstring& regKey)
{
	try
	{
		LONG result;
		HKEY hKey;

		result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,regKey.c_str(),0,KEY_READ,&hKey);
		if (result != ERROR_SUCCESS)
		{
			// key may not exist so exit
			return;
		}

		TCHAR lpName[MAX_PATH];

		for (DWORD index = 0, result = ERROR_SUCCESS; result == ERROR_SUCCESS; index++) 
		{ 
			DWORD lpcName = MAX_PATH;
			result = RegEnumKeyEx(hKey, 
                     index, 
                     lpName, 
                     &lpcName, 
                     NULL, 
                     NULL, 
                     NULL, 
                     NULL); 

			if( result == ERROR_SUCCESS ) 
			{
				tstring dirName(lpName);	
				if( dirName.empty() )
				{
					continue;
				}

				tstring fullKeyPath = regKey + tstring(_T("\\")) + dirName;

				DEBUG_SHOW( tstring(_T("fullKeyPath=")) + fullKeyPath );
				tstring& javaHome = getStringValue(fullKeyPath, _T("JavaHome"));
				if( javaHome.empty() )
				{
					continue;
				}

				JVMInfo *pJvmInfo = new JVMInfo;
				pJvmInfo->setJavaBundle(Properties::JRE_JAVA_BUNDLE);
				pJvmInfo->setJavaHomePath(javaHome);
				pJvmInfo->setVersion(dirName);

				pVecJvmInfo->push_back(*pJvmInfo);
			}
		} 

		RegCloseKey(hKey);
	}
	catch(tstring& se)
	{
		ErrHandler::severeError( se );
	}
	catch(...)
	{
		DEBUG_SHOW( _T("Exception in WindowsRegistry.addAllJreJvms()") );
		ErrHandler::severeError( _T("Error getting JVM paths from registry.") );
	}
}
PMDModelPtr PMDFileLoader::Open( const tstring& filePath )
{
	m_fileName = filePath;

	TCHAR path[MAX_PATH];
	_tcscpy_s( path,MAX_PATH,filePath.c_str() );
	PathRemoveFileSpec( path );
	PathAddBackslash( path );
	m_path = path;

	FILE* fp=NULL;
	if( _tfopen_s(&fp,m_fileName.c_str(),_T("rb"))!=0 )
	{
		return PMDModelPtr();
	}

	fpos_t fsize = 0;
	fseek(fp,0,SEEK_END);
	fgetpos(fp,&fsize);

	fseek(fp,0,SEEK_SET); 

	size_t sz=(size_t)fsize;

	unsigned char* buffer=new unsigned char[sz];
	fread(buffer,1,sz,fp);

	fclose(fp);

	sPMD* pmd = new sPMD;
	bool ret = PMDLoad(buffer,sz,pmd);
	
	delete[] buffer;

	if( !ret )
	{
		delete pmd;
		return PMDModelPtr();
	}

	sPMD_Skin* skinBase = NULL;

	for( DWORD skinIdx=0;skinIdx<pmd->skin_list.skin_count;skinIdx++ )
	{
		sPMD_Skin* skin = &pmd->skin_list.skin[skinIdx];

		if( skin->skin_type == ePMD_SkinType_Base )
		{
			skinBase = skin;

			for( DWORD vertIdx = 0; vertIdx < skin->skin_vert_count ; vertIdx++ )
			{
				DWORD targetIndex = skin->skin_vert[vertIdx].index;
				memcpy( pmd->vertex_list.vertex[ targetIndex ].pos, skin->skin_vert[vertIdx].pos,sizeof(float)*3 );
			}
			
			break;
		}
	}

	for( DWORD skinIdx=0;skinIdx<pmd->skin_list.skin_count;skinIdx++ )
	{
		sPMD_Skin* skin = &pmd->skin_list.skin[skinIdx];

		if( skin->skin_type != ePMD_SkinType_Base )
		{
			for( DWORD vertIdx = 0; vertIdx < skin->skin_vert_count ; vertIdx++ )
			{
				DWORD targetIndex = skin->skin_vert[vertIdx].index;
				skin->skin_vert[vertIdx].index = skinBase->skin_vert[ targetIndex ].index;
			}
		}
	}

	Graphics* graphics = Graphics::GetInstance();

	sMaterial* pMaterials = new sMaterial[pmd->material_list.material_count];

	for( DWORD i=0;i<pmd->material_list.material_count;i++ )
	{
		sPMD_Material* pmdMat = &pmd->material_list.material[i];
		sMaterial* pMaterial = &pMaterials[i];

		pMaterial->colorDiffuse.r = 0.0f;
		pMaterial->colorDiffuse.g = 0.0f;
		pMaterial->colorDiffuse.b = 0.0f;
		pMaterial->colorDiffuse.a = pmdMat->alpha;

		pMaterial->colorAmbient.r = pmdMat->diffuse_color[0];
		pMaterial->colorAmbient.g = pmdMat->diffuse_color[1];
		pMaterial->colorAmbient.b = pmdMat->diffuse_color[2];
		pMaterial->colorAmbient.a = 0.0f;

		pMaterial->colorSpecular.r = pmdMat->specular_color[0];
		pMaterial->colorSpecular.g = pmdMat->specular_color[1];
		pMaterial->colorSpecular.b = pmdMat->specular_color[2];
		pMaterial->colorSpecular.a = 0.0f;

		pMaterial->colorEmissive.r = pmdMat->ambient_color[0];
		pMaterial->colorEmissive.g = pmdMat->ambient_color[1];
		pMaterial->colorEmissive.b = pmdMat->ambient_color[2];
		pMaterial->colorEmissive.a = 0.0f;

		pMaterial->specularPower = pmdMat->specularity;

		pMaterial->spheremap = eSPHEREMAP_MUL;

		pMaterial->edge = pmdMat->edge_flag!=0;

		TCHAR path[MAX_PATH];
		_tcscpy_s( path,m_path.c_str() );

		tstring texFileName;
		tstring sphereFileName;

		if( strlen(pmdMat->texture_file_name)>0 )
		{
			tstring filename = to_tstring(pmdMat->texture_file_name);

			tstring::size_type index = filename.find( _T("*") );
			if( index != tstring::npos )
			{
				sphereFileName = filename.substr( index+1 );
				PathAppend( path,sphereFileName.c_str() );
				sphereFileName = path;
				PathRemoveFileSpec( path );

				texFileName = filename.erase( index );
				PathAppend( path,texFileName.c_str() );
				texFileName = path;
				PathRemoveFileSpec( path );
			}
			else
			{
				texFileName = filename;
				PathAppend( path,texFileName.c_str() );
				texFileName = path;
				PathRemoveFileSpec( path );
			}

			tstring ext = PathFindExtension( texFileName.c_str() );

			if( ext == _T(".sph" ) || ext == _T(".spa") )
			{
				sphereFileName = texFileName;
				texFileName = _T("");
			}
		}

		if( !texFileName.empty() )
		{
			TexturePtr pTex = ResourceManager::GetInstance().GetResource<Texture>( texFileName );
			if( !pTex )
			{
				pTex = TexturePtr(new Texture);
				pTex->CreateFromFile( texFileName );

				ResourceManager::GetInstance().AddResource( texFileName,pTex );
			}

			pMaterial->textureDiffuse = pTex;
		}

		if( !sphereFileName.empty() )
		{
			TexturePtr pTex = ResourceManager::GetInstance().GetResource<Texture>( sphereFileName );
			if( !pTex )
			{
				pTex = TexturePtr(new Texture);
				pTex->CreateFromFile( sphereFileName );

				ResourceManager::GetInstance().AddResource( sphereFileName,pTex );
			}

			pMaterial->textureSphere = pTex;

			tstring ext = PathFindExtension( sphereFileName.c_str() );
			if( ext == _T(".sph" ) )
			{
				pMaterial->spheremap = eSPHEREMAP_MUL;
			}
			else if( ext == _T(".spa") )
			{
				pMaterial->spheremap = eSPHEREMAP_ADD;
			}
		}

		pMaterial->colorToon = D3DXCOLOR( 1.0f,1.0f,1.0f,1.0f );

		tstring toonTexName = _T("");
		tstring toonTexPath = _T("");

		if( 0<=pmdMat->toon_index && pmdMat->toon_index<10 )
		{
			// TODO:デフォルトのtoonファイルは固定パスか・・・
			toonTexName = to_tstring( pmd->toon_list.toon_file_name[pmdMat->toon_index] );
		}

		TexturePtr pTex;
		
		if( !toonTexName.empty() )
		{
			PathAppend( path,toonTexName.c_str() );
			toonTexPath = path;
			PathRemoveFileSpec( path );

			pTex = ResourceManager::GetInstance().GetResource<Texture>( toonTexPath );
			if( !pTex )
			{
				pTex = TexturePtr(new Texture);
				if( !pTex->CreateFromFile( toonTexPath ) )
				{
					pTex.reset();
				}
			}
		}

		if( !pTex )
		{
			pTex = graphics->GetDefaultToonTexture( pmdMat->toon_index );
			if( !pTex )
			{
				toonTexPath = _T("<FFFFFFFF>");

				pTex = ResourceManager::GetInstance().GetResource<Texture>( toonTexPath );
				if( !pTex )
				{
					pTex = TexturePtr(new Texture);
					if( !pTex->CreateDotColor( 0xFFFFFFFF ) )
					{
						pTex.reset();
					}
				}
			}
		}
		
		if( pTex )
		{
			pMaterial->textureToon = pTex;

			ResourceManager::GetInstance().AddResource( toonTexPath,pTex );

			IDirect3DTexture9Ptr pD3DTexture = pTex->GetTexture();

			D3DSURFACE_DESC desc;
			pD3DTexture->GetLevelDesc( 0,&desc );

			D3DLOCKED_RECT lockRect;
			pD3DTexture->LockRect(0, &lockRect, NULL, 0);

			int x = 0;
			int y = desc.Height-1;

			DWORD color;

			memcpy(&color,(BYTE*)lockRect.pBits + lockRect.Pitch*y + 4*x, sizeof(DWORD) );

			pD3DTexture->UnlockRect(0);

			pMaterial->colorToon = D3DXCOLOR( color );
		}
	}

	return PMDModelPtr( new PMDModel(pmd,pmd->material_list.material_count,pMaterials) );
}
Example #9
0
tstring
TXOwl::MakeMessage(uint resId, const tstring& infoStr, TModule* module)
{
  return MakeMessage(resId, infoStr.c_str(), module);
}
Example #10
0
bool cmd_run_as(const tstring& command,
                const RUN_AS_TYPE& as_type,
                const bool show_window /*= true*/)
{
    InfoLog("begin exec");

    bool execute_success = false;
    const unsigned short sw_flag = show_window ? SW_SHOWNORMAL : SW_HIDE;

    std::vector<HANDLE> processes;

    switch (as_type)
    {
    case AS_LOCAL:
        {
            DWORD created_pid = 0;
            HANDLE hProcess = ProcessCreator::create_process_in_local_context(command,
                created_pid, CREATE_NEW_CONSOLE, TSTR(""), sw_flag);
            if (hProcess)
            {
                InfoLog("create_process_in_local_context success, pid=%lu", created_pid);
                processes.push_back(hProcess);
            }
            else
            {
                ErrorLog("create_process_in_local_context fail");
            }
        }
        break;

    case AS_LOGON_USER:
    case AS_ALL_LOGON_USERS:
        {
            std::vector<DWORD> pids;
            find_pids_by_path(TSTR("explorer.exe"), pids);
            if (pids.empty())
            {
                ErrorLog("can not find any explorer.exe");
            }
            else
            {
                for (std::vector<DWORD>::const_iterator iter_pid = pids.begin();
                    iter_pid != pids.end();
                    ++iter_pid)
                {
                    InfoLog("explorer.exe pid=%lu", *iter_pid);
                    DWORD created_pid = 0;
                    HANDLE hProcess = ProcessCreator::create_process_as_same_token(*iter_pid,
                        command, created_pid, CREATE_NEW_CONSOLE, TSTR(""), sw_flag);
                    if (hProcess)
                    {
                        InfoLog("create_process_as_same_token success, pid=%lu", created_pid);
                        processes.push_back(hProcess);
                        if (as_type == AS_LOGON_USER)
                        {
                            break;
                        }
                    }
                    else
                    {
                        ErrorLog(TSTR("create_process_as_same_token fail, pid=%lu, cmd=[%s]"),
                            *iter_pid, command.c_str());
                    }
                }
            }

            if (processes.empty())
            {
                ErrorLog("no new process in user context was created");
            }
        }
        break;

    default:
        ErrorLog("unknown run_as type: %d", as_type);
        break;
    }

    if (!processes.empty())
    {
        //最多伺候3秒,不必看结果,让守护进程去看
        WaitForMultipleObjects(processes.size(), &processes[0], TRUE, 3 * 1000);
        for (std::vector<HANDLE>::iterator iter_process = processes.begin();
            iter_process != processes.end();
            ++iter_process)
        {
            CloseHandle(*iter_process);
            *iter_process = NULL;
        }

        execute_success = true;
    }
    else
    {
        execute_success = false;
    }

    InfoLog("end exec with %s", execute_success ? "success" : "fail");
    return execute_success;
}
inline ProjectFile::ProjectFile(const tstring& pathName)
	: m_pathName(pathName)
	, m_fileName(CPath(pathName.c_str()).FileName())
	, m_xmlDoc()
{
}
Example #12
0
/////////////////////////////////////////////////////////////////////
// 
// Function:    GetComponentKeyFilename
//
// Description: 
//
/////////////////////////////////////////////////////////////////////
UINT BOINCCABase::GetComponentKeyFilename( 
    const tstring strComponentName, 
    tstring&      strComponentKeyFilename
    )
{
    UINT        uiReturnValue = 0;
    tstring     strMessage;
    tstring     strQuery;
    TCHAR       szBuffer[256];
    DWORD       dwBufferSize = sizeof(szBuffer);
    MSIHANDLE   hDatabase;
    MSIHANDLE   hView;
    MSIHANDLE   hRecComponentName;
    MSIHANDLE   hRec;


	// Get the handle to the MSI package we are executing for.
	hDatabase = MsiGetActiveDatabase(m_hMSIHandle);
	if (!hDatabase) return ERROR_INSTALL_FAILURE;

	// Construct the query that is going to give us the result we need.
    strQuery  = _T("SELECT `KeyPath` FROM `Component` WHERE `Component`= ?");

	// Create the view
    uiReturnValue = MsiDatabaseOpenView(hDatabase, strQuery.c_str(), &hView);
    switch(uiReturnValue)
    {
    case ERROR_BAD_QUERY_SYNTAX:
        MsiCloseHandle(hDatabase);

        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            NULL,
            _T("MsiDatabaseOpenView reports an invalid query was issued")
        );

        return ERROR_INSTALL_FAILURE;
        break;
    case ERROR_INVALID_HANDLE:
        MsiCloseHandle(hDatabase);

        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            NULL,
            _T("MsiDatabaseOpenView reports an invalid handle was used")
        );

        return ERROR_INSTALL_FAILURE;
        break;
    }

    // Create query parameter
    hRecComponentName = MsiCreateRecord(1);
    uiReturnValue = MsiRecordSetString(hRecComponentName, 1, strComponentName.c_str());
    switch(uiReturnValue)
    {
    case ERROR_INVALID_HANDLE:
        MsiCloseHandle(hRecComponentName);
        MsiCloseHandle(hDatabase);

        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            NULL,
            _T("MsiRecordSetString reports an invalid handle was used")
        );

        return ERROR_INSTALL_FAILURE;
        break;
    case ERROR_INVALID_PARAMETER:
        MsiCloseHandle(hRecComponentName);
        MsiCloseHandle(hDatabase);

        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            NULL,
            _T("MsiRecordSetString reports an invalid parameter was used")
        );

        return ERROR_INSTALL_FAILURE;
        break;
    }


    // Execute the query
    uiReturnValue = MsiViewExecute(hView, hRecComponentName);
    switch(uiReturnValue)
    {
    case ERROR_FUNCTION_FAILED:
        MsiViewClose(hView);
        MsiCloseHandle(hDatabase);
        
        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            NULL,
            _T("MsiViewExecute failed to execute the view")
        );

        return ERROR_INSTALL_FAILURE;
        break;
    case ERROR_INVALID_HANDLE:
        MsiViewClose(hView);
        MsiCloseHandle(hDatabase);

        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            NULL,
            _T("MsiViewExecute reports an invalid handle was used")
        );

        return ERROR_INSTALL_FAILURE;
        break;
    }

    // Only one row should be returned by the resultset, so there is no need
    //   to execute MsiViewFetch more than once.
    uiReturnValue = MsiViewFetch(hView, &hRec);
    switch(uiReturnValue)
    {
    case ERROR_FUNCTION_FAILED:
        MsiViewClose(hView);
        MsiCloseHandle(hDatabase);
        
        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            NULL,
            _T("MsiViewFetch: An error occurred during fetching")
        );

        return ERROR_INSTALL_FAILURE;
        break;
    case ERROR_INVALID_HANDLE:
        MsiViewClose(hView);
        MsiCloseHandle(hDatabase);

        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            NULL,
            _T("MsiViewFetch reports an invalid handle was used")
        );

        return ERROR_INSTALL_FAILURE;
        break;
    case ERROR_INVALID_HANDLE_STATE:
        MsiViewClose(hView);
        MsiCloseHandle(hDatabase);

        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            NULL,
            _T("MsiViewFetch reports the handle was in an invalid state")
        );

        return ERROR_INSTALL_FAILURE;
        break;
    }

    // Okay, now it is time to parse the string that was returned.
    uiReturnValue = MsiRecordGetString(hRec, 1, (LPTSTR)&szBuffer, &dwBufferSize);
    switch(uiReturnValue)
    {
    case ERROR_INVALID_HANDLE:
        MsiCloseHandle(hRec);
        MsiViewClose(hView);
        MsiCloseHandle(hDatabase);

        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            NULL,
            _T("MsiRecordGetString reports an invalid handle was used")
        );

        return ERROR_INSTALL_FAILURE;
        break;
    case ERROR_INVALID_PARAMETER:
        MsiCloseHandle(hRec);
        MsiViewClose(hView);
        MsiCloseHandle(hDatabase);

        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            NULL,
            _T("MsiRecordGetString reports an invalid parameter was used")
        );

        return ERROR_INSTALL_FAILURE;
        break;
    }

    // Save the string
    strComponentKeyFilename = szBuffer;

    strMessage  = _T("The key filename for component '");
    strMessage += strComponentName;
    strMessage += _T("' is '");
    strMessage += strComponentKeyFilename;
    strMessage += _T("'");

    LogMessage(
        INSTALLMESSAGE_INFO,
        NULL, 
        NULL,
        NULL,
        NULL,
        strMessage.c_str()
    );

    return ERROR_SUCCESS;
}
Example #13
0
/////////////////////////////////////////////////////////////////////
// 
// Function:    GetProperty
//
// Description: 
//
/////////////////////////////////////////////////////////////////////
UINT BOINCCABase::GetProperty( 
    const tstring strPropertyName, 
    tstring&      strPropertyValue,
    bool          bDisplayValue
    )
{
    LPTSTR  lpszBuffer = NULL;
    DWORD   dwCharacterCount = 0;
    tstring strMessage;
    UINT    uiReturnValue = 0;

    uiReturnValue = MsiGetProperty(m_hMSIHandle, strPropertyName.c_str(), _T(""), &dwCharacterCount);
    switch(uiReturnValue)
    {
    case ERROR_INVALID_HANDLE:
    case ERROR_INVALID_PARAMETER:
        strMessage  = _T("Failed to get '") + strPropertyName;
        strMessage += _T("'");

        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            NULL,
            strMessage.c_str()
        );
        return ERROR_INSTALL_FAILURE;
        break;
    }

    // Allocate memory for the property value return buffer
    lpszBuffer = (LPTSTR) malloc( ((++dwCharacterCount)*sizeof(LPTSTR)) );
    uiReturnValue = MsiGetProperty(m_hMSIHandle, strPropertyName.c_str(), lpszBuffer, &dwCharacterCount);
    switch(uiReturnValue)
    {
    case ERROR_INVALID_HANDLE:
    case ERROR_INVALID_PARAMETER:
        strMessage  = _T("Failed to get '") + strPropertyName;
        strMessage += _T("' after allocating the buffer");

        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            NULL,
            strMessage.c_str()
        );
        if ( lpszBuffer ) free( lpszBuffer );
        return ERROR_INSTALL_FAILURE;
        break;
    }

    strPropertyValue = lpszBuffer;
    free( lpszBuffer );

    strMessage  = _T("Successfully retrieved '") + strPropertyName;
    strMessage += _T("' with a value of '");
    if (bDisplayValue)
        strMessage += strPropertyValue;
    else
        strMessage += _T("<Value Hidden>");
    strMessage += _T("'");

    LogMessage(
        INSTALLMESSAGE_INFO,
        NULL, 
        NULL,
        NULL,
        NULL,
        strMessage.c_str()
    );

    return ERROR_SUCCESS;
}
Example #14
0
/////////////////////////////////////////////////////////////////////
// 
// Function:    GetRegistryValue
//
// Description: 
//
/////////////////////////////////////////////////////////////////////
UINT BOINCCABase::GetRegistryValue( 
    const tstring strName, 
    tstring&      strValue,
    bool          bDisplayValue
    )
{
	LONG lReturnValue;
	HKEY hkSetupHive;
	DWORD dwSize = 0;
    LPTSTR lpszRegistryValue = NULL;
    tstring strMessage;

	lReturnValue = RegOpenKeyEx(
        HKEY_LOCAL_MACHINE, 
        _T("SOFTWARE\\Space Sciences Laboratory, U.C. Berkeley\\BOINC Setup"),  
		0, 
        KEY_READ,
        &hkSetupHive
    );
	if (lReturnValue != ERROR_SUCCESS) return ERROR_INSTALL_FAILURE;

    // How large does our buffer need to be?
    RegQueryValueEx(
        hkSetupHive,
        strName.c_str(),
        NULL,
        NULL,
        NULL,
        &dwSize
    );

    // Allocate the buffer space.
    lpszRegistryValue = (LPTSTR) malloc(dwSize);
    (*lpszRegistryValue) = NULL;

    // Now get the data
    lReturnValue = RegQueryValueEx( 
        hkSetupHive,
        strName.c_str(),
        NULL,
        NULL,
        (LPBYTE)lpszRegistryValue,
        &dwSize
    );

    // Send up the returned value.
    if (lReturnValue == ERROR_SUCCESS) strValue = lpszRegistryValue;

    // Cleanup
	RegCloseKey(hkSetupHive);
    free(lpszRegistryValue);

    // One last check to make sure everything is on the up and up.
    if (lReturnValue != ERROR_SUCCESS) return ERROR_INSTALL_FAILURE;


    strMessage  = _T("Successfully retrieved registry value '") + strName;
    strMessage += _T("' with a value of '");
    if (bDisplayValue)
        strMessage += strValue;
    else
        strMessage += _T("<Value Hidden>");
    strMessage += _T("'");

    LogMessage(
        INSTALLMESSAGE_INFO,
        NULL, 
        NULL,
        NULL,
        NULL,
        strMessage.c_str()
    );

    return ERROR_SUCCESS;
}
Example #15
0
bool CPicture::Load(tstring sFilePathName)
{
	bool bResult = false;
	bIsIcon = false;
	lpIcons = nullptr;
	//CFile PictureFile;
	//CFileException e;
	FreePictureData(); // Important - Avoid Leaks...

	// No-op if no file specified
	if (sFilePathName.empty())
		return true;

	// Load & initialize the GDI+ library if available
	HMODULE hGdiPlusLib = AtlLoadSystemLibraryUsingFullPath(L"gdiplus.dll");
	if (hGdiPlusLib && GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, nullptr) == Ok)
	{
		bHaveGDIPlus = true;
	}
	// Since we loaded the gdiplus.dll only to check if it's available, we
	// can safely free the library here again - GdiplusStartup() loaded it too
	// and reference counting will make sure that it stays loaded until GdiplusShutdown()
	// is called.
	FreeLibrary(hGdiPlusLib);

	// Attempt to load using GDI+ if available
	if (bHaveGDIPlus)
	{
		pBitmap = new Bitmap(sFilePathName.c_str(), FALSE);
		GUID guid;
		pBitmap->GetRawFormat(&guid);

		if (pBitmap->GetLastStatus() != Ok)
		{
			delete pBitmap;
			pBitmap = nullptr;
		}

		// gdiplus only loads the first icon found in an icon file
		// so we have to handle icon files ourselves :(

		// Even though gdiplus can load icons, it can't load the new
		// icons from Vista - in Vista, the icon format changed slightly.
		// But the LoadIcon/LoadImage API still can load those icons,
		// at least those dimensions which are also used on pre-Vista
		// systems.
		// For that reason, we don't rely on gdiplus telling us if
		// the image format is "icon" or not, we also check the
		// file extension for ".ico".
		auto lowerfilename = sFilePathName;
		std::transform(lowerfilename.begin(), lowerfilename.end(), lowerfilename.begin(), ::tolower);
		bIsIcon = (guid == ImageFormatIcon) || (wcsstr(lowerfilename.c_str(), L".ico")) || (wcsstr(lowerfilename.c_str(), L".cur"));
		bIsTiff = (guid == ImageFormatTIFF) || (wcsstr(lowerfilename.c_str(), L".tiff"));
		m_Name = sFilePathName;

		if (bIsIcon)
		{
			// Icon file, get special treatment...
			if (pBitmap)
			{
				// Cleanup first...
				delete (pBitmap);
				pBitmap = nullptr;
				bIsIcon = true;
			}

			CAutoFile hFile = CreateFile(sFilePathName.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
			if (hFile)
			{
				BY_HANDLE_FILE_INFORMATION fileinfo;
				if (GetFileInformationByHandle(hFile, &fileinfo))
				{
					lpIcons = new BYTE[fileinfo.nFileSizeLow];
					DWORD readbytes;
					if (ReadFile(hFile, lpIcons, fileinfo.nFileSizeLow, &readbytes, nullptr))
					{
						// we have the icon. Now gather the information we need later
						if (readbytes >= sizeof(ICONDIR))
						{
							// we are going to open same file second time so we have to close the file now
							hFile.CloseHandle();

							LPICONDIR lpIconDir = (LPICONDIR)lpIcons;
							if ((lpIconDir->idCount) && ((lpIconDir->idCount * sizeof(ICONDIR)) <= fileinfo.nFileSizeLow))
							{
								try
								{
									bResult = false;
									nCurrentIcon = 0;
									hIcons = new HICON[lpIconDir->idCount];
									// check that the pointers point to data that we just loaded
									if (((BYTE*)lpIconDir->idEntries > (BYTE*)lpIconDir) && 
										(((BYTE*)lpIconDir->idEntries) + (lpIconDir->idCount * sizeof(ICONDIRENTRY)) < ((BYTE*)lpIconDir) + fileinfo.nFileSizeLow))
									{
										m_Width = lpIconDir->idEntries[0].bWidth == 0 ? 256 : lpIconDir->idEntries[0].bWidth;
										m_Height = lpIconDir->idEntries[0].bHeight == 0 ? 256 : lpIconDir->idEntries[0].bHeight;
										bResult = true;
										for (int i=0; i<lpIconDir->idCount; ++i)
										{
											hIcons[i] = (HICON)LoadImage(nullptr, sFilePathName.c_str(), IMAGE_ICON,
																		 lpIconDir->idEntries[i].bWidth == 0 ? 256 : lpIconDir->idEntries[i].bWidth,
																		 lpIconDir->idEntries[i].bHeight == 0 ? 256 : lpIconDir->idEntries[i].bHeight,
																		 LR_LOADFROMFILE);
											if (hIcons[i] == nullptr)
											{
												// if the icon couldn't be loaded, the data is most likely corrupt
												delete [] lpIcons;
												lpIcons = nullptr;
												bResult = false;
												break;
											}
										}
									}
								}
								catch (...)
								{
									delete [] lpIcons;
									lpIcons = nullptr;
									bResult = false;
								}
							}
							else
							{
								delete [] lpIcons;
								lpIcons = nullptr;
								bResult = false;
							}
						}
						else
						{
							delete [] lpIcons;
							lpIcons = nullptr;
							bResult = false;
						}
					}
					else
					{
						delete [] lpIcons;
						lpIcons = nullptr;
					}
				}
			}
		}
		else if (pBitmap)	// Image loaded successfully with GDI+
		{
			m_Height = pBitmap->GetHeight();
			m_Width = pBitmap->GetWidth();
			bResult = true;
		}

		// If still failed to load the file...
		if (!bResult)
		{
			// Attempt to load the FreeImage library as an optional DLL to support additional formats

			// NOTE: Currently just loading via FreeImage & using GDI+ for drawing.
			// It might be nice to remove this dependency in the future.
			HMODULE hFreeImageLib = LoadLibrary(L"FreeImage.dll");

			// FreeImage DLL functions
			typedef const char* (__stdcall *FreeImage_GetVersion_t)(void);
			typedef int			(__stdcall *FreeImage_GetFileType_t)(const TCHAR *filename, int size);
			typedef int			(__stdcall *FreeImage_GetFIFFromFilename_t)(const TCHAR *filename);
			typedef void*		(__stdcall *FreeImage_Load_t)(int format, const TCHAR *filename, int flags);
			typedef void		(__stdcall *FreeImage_Unload_t)(void* dib);
			typedef int			(__stdcall *FreeImage_GetColorType_t)(void* dib);
			typedef unsigned	(__stdcall *FreeImage_GetWidth_t)(void* dib);
			typedef unsigned	(__stdcall *FreeImage_GetHeight_t)(void* dib);
			typedef void		(__stdcall *FreeImage_ConvertToRawBits_t)(BYTE *bits, void *dib, int pitch, unsigned bpp, unsigned red_mask, unsigned green_mask, unsigned blue_mask, BOOL topdown);

			//FreeImage_GetVersion_t FreeImage_GetVersion = nullptr;
			FreeImage_GetFileType_t FreeImage_GetFileType = nullptr;
			FreeImage_GetFIFFromFilename_t FreeImage_GetFIFFromFilename = nullptr;
			FreeImage_Load_t FreeImage_Load = nullptr;
			FreeImage_Unload_t FreeImage_Unload = nullptr;
			//FreeImage_GetColorType_t FreeImage_GetColorType = nullptr;
			FreeImage_GetWidth_t FreeImage_GetWidth = nullptr;
			FreeImage_GetHeight_t FreeImage_GetHeight = nullptr;
			FreeImage_ConvertToRawBits_t  FreeImage_ConvertToRawBits = nullptr;

			if (hFreeImageLib)
			{
				bool exportsValid = true;

				//FreeImage_GetVersion = (FreeImage_GetVersion_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_GetVersion@0", valid);
				FreeImage_GetWidth = (FreeImage_GetWidth_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_GetWidth@4", exportsValid);
				FreeImage_GetHeight = (FreeImage_GetHeight_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_GetHeight@4", exportsValid);
				FreeImage_Unload = (FreeImage_Unload_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_Unload@4", exportsValid);
				FreeImage_ConvertToRawBits = (FreeImage_ConvertToRawBits_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_ConvertToRawBits@32", exportsValid);

#ifdef UNICODE
				FreeImage_GetFileType = (FreeImage_GetFileType_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_GetFileTypeU@8", exportsValid);
				FreeImage_GetFIFFromFilename = (FreeImage_GetFIFFromFilename_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_GetFIFFromFilenameU@4", exportsValid);
				FreeImage_Load = (FreeImage_Load_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_LoadU@12", exportsValid);
#else
				FreeImage_GetFileType = (FreeImage_GetFileType_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_GetFileType@8", exportsValid);
				FreeImage_GetFIFFromFilename = (FreeImage_GetFIFFromFilename_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_GetFIFFromFilename@4", exportsValid);
				FreeImage_Load = (FreeImage_Load_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_Load@12", exportsValid);
#endif

				//const char* version = FreeImage_GetVersion();

				// Check the DLL is using compatible exports
				if (exportsValid)
				{
					// Derive file type from file header.
					int fileType = FreeImage_GetFileType(sFilePathName.c_str(), 0);
					if (fileType < 0)
					{
						// No file header available, attempt to parse file name for extension.
						fileType = FreeImage_GetFIFFromFilename(sFilePathName.c_str());
					}

					// If we have a valid file type
					if (fileType >= 0)
					{
						void* dib = FreeImage_Load(fileType, sFilePathName.c_str(), 0);

						if (dib)
						{
							unsigned width = FreeImage_GetWidth(dib);
							unsigned height = FreeImage_GetHeight(dib);

							// Create a GDI+ bitmap to load into...
							pBitmap = new Bitmap(width, height, PixelFormat32bppARGB);

							if (pBitmap && pBitmap->GetLastStatus() == Ok)
							{
								// Write & convert the loaded data into the GDI+ Bitmap
								Rect rect(0, 0, width, height);
								BitmapData bitmapData;
								if (pBitmap->LockBits(&rect, ImageLockModeWrite, PixelFormat32bppARGB, &bitmapData) == Ok)
								{
									FreeImage_ConvertToRawBits((BYTE*)bitmapData.Scan0, dib, bitmapData.Stride, 32, 0xff << RED_SHIFT, 0xff << GREEN_SHIFT, 0xff << BLUE_SHIFT, FALSE);

									pBitmap->UnlockBits(&bitmapData);

									m_Width = width;
									m_Height = height;
									bResult = true;
								}
								else    // Failed to lock the destination Bitmap
								{
									delete pBitmap;
									pBitmap = nullptr;
								}
							}
							else    // Bitmap allocation failed
							{
								delete pBitmap;
								pBitmap = nullptr;
							}

							FreeImage_Unload(dib);
							dib = nullptr;
						}
					}
				}

				FreeLibrary(hFreeImageLib);
				hFreeImageLib = nullptr;
			}
		}
	}
Example #16
0
bool Path::IsAbsolute( const tstring& path )
{
    return Helium::IsAbsolute( path.c_str() );
}
Example #17
0
int CClientSocket::Send(const tstring& sData)
{
	return (Send(sData.c_str(), (size_t)sData.length()));
}
Example #18
0
Path::Path( const tstring& path )
{
    Init( path.c_str() );
}
Example #19
0
void CLevelEntity::SetParameterValue(const tstring& sKey, const tstring& sValue)
{
	auto it = m_asParameters.find(sKey);
	if (it == m_asParameters.end())
	{
		if (!sValue.length())
			return;

		m_asParameters[sKey] = sValue;
	}
	else
	{
		if (!sValue.length())
		{
			m_asParameters.erase(sKey);
			Dirtify();
			return;
		}

		tstring& sCurrentValue = it->second;
		if (sCurrentValue == sValue)
			return;

		sCurrentValue = sValue;
	}

	Dirtify();

	CSaveData oSaveData;
	CSaveData* pSaveData = CBaseEntity::FindSaveDataValuesByHandle(("C" + GetClass()).c_str(), sKey.c_str(), &oSaveData);

	if (!pSaveData)
		TMsg("Level entity " + GetClass() + ":" + GetName() + " has unregistered savedata value: " + sKey + "\n");

	if (pSaveData && pSaveData->m_pszHandle && pSaveData->m_bDefault)
	{
		// Special case.
		if (strcmp(pSaveData->m_pszHandle, "Model") == 0)
		{
			m_hMaterialModel = CMaterialLibrary::AddMaterial(sValue);

			// Don't continue to erasing the default parameters if it's a model, since models have special processing.
			return;
		}

		if (strcmp(pSaveData->m_pszType, "bool") == 0)
		{
			bool bValue = UnserializeString_bool(sValue);

			bool b = *((bool*)&pSaveData->m_oDefault[0]);
			if (bValue == b)
				m_asParameters.erase(sKey);
		}
		else
		{
			if (strcmp(pSaveData->m_pszType, "size_t") == 0)
			{
				size_t i = *((size_t*)&pSaveData->m_oDefault[0]);
				if (stoi(sValue) == i)
					m_asParameters.erase(sKey);
			}
			else if (strcmp(pSaveData->m_pszType, "float") == 0)
			{
				float f = *((float*)&pSaveData->m_oDefault[0]);
				if (stof(sValue) == f)
					m_asParameters.erase(sKey);
			}
			else if (strcmp(pSaveData->m_pszType, "Vector") == 0)
			{
				if (CanUnserializeString_TVector(sValue))
				{
					Vector v = *((Vector*)&pSaveData->m_oDefault[0]);
					if (UnserializeString_TVector(sValue) == v)
						m_asParameters.erase(sKey);
				}
			}
			else if (strcmp(pSaveData->m_pszType, "Vector2D") == 0)
			{
				if (CanUnserializeString_Vector2D(sValue))
				{
					Vector2D v = *((Vector2D*)&pSaveData->m_oDefault[0]);
					if (UnserializeString_Vector2D(sValue) == v)
						m_asParameters.erase(sKey);
				}
			}
			else if (strcmp(pSaveData->m_pszType, "EAngle") == 0)
			{
				if (CanUnserializeString_EAngle(sValue))
				{
					EAngle v = *((EAngle*)&pSaveData->m_oDefault[0]);
					if (UnserializeString_EAngle(sValue) == v)
						m_asParameters.erase(sKey);
				}
			}
			else if (strcmp(pSaveData->m_pszType, "Matrix4x4") == 0)
			{
				if (CanUnserializeString_Matrix4x4(sValue))
				{
					Matrix4x4 m = *((Matrix4x4*)&pSaveData->m_oDefault[0]);
					if (UnserializeString_Matrix4x4(sValue) == m)
						m_asParameters.erase(sKey);
				}
			}
			else if (strcmp(pSaveData->m_pszType, "AABB") == 0)
			{
				if (CanUnserializeString_AABB(sValue))
				{
					AABB b = *((AABB*)&pSaveData->m_oDefault[0]);
					if (UnserializeString_AABB(sValue) == b)
						m_asParameters.erase(sKey);
				}
			}
			else
			{
				TUnimplemented();
			}
		}
	}
}
Example #20
0
void ChatControl::addLine(const Identity& i, const string& nick, const string& extra, const tstring& aLine, CHARFORMAT2& cf, bool bUseEmo/* = true*/) {
  ctrlClient.AdjustTextSize();
  if (timeStamps) {
    ctrlClient.AppendText(i, Text::toT(nick), Text::toT("[" + Util::getShortTimeString() + extra + "] "), aLine.c_str(), cf, bUseEmo);
  } 
  else {
    ctrlClient.AppendText(i, Text::toT(nick), !extra.empty() ? Text::toT("[" + extra + "] ") : _T(""), aLine.c_str(), cf, bUseEmo);
  }
}
Example #21
0
bool CController::InitLogin(tstring& strPhone, tstring& strPwd)
{
	static int init_times(0);
	init_times++;

	//注册 todo
	if (NULL  != m_pLogin)
	{
		delete m_pLogin;
		m_pLogin = NULL;
	}

	//verify
	ostringstream osPost;
	osPost<<"cell_phone="
		<<strPhone.c_str()
		<<"&"
		<<"passwd="
		<<strPwd.c_str();

	tstring strUrl(WEB_SERVER_SITE_URL);
	strUrl += "verify";
	tstring strPost = osPost.str().c_str();
	tstring strResponse;

	CHttpClient reqClient;
	int nSucc = reqClient.Post(strUrl, strPost, strResponse);

	if (strResponse.empty())
	{
		//只有在第一次连接的时候才会弹出对话框,以后为自动重连,不能弹出对话框
		if (init_times <= 1)
		{
			CMsgBox* pMsgBox = new CMsgBox("错误",_T("连接服务器超时!"),MSGBOX_ICON_ERROR, MSGBOX_IDOK);
			pMsgBox->ShowModal(NULL);
		}		
		return false;
	}

	//if (nSucc == 1)	
	tstring strFind("access_token");
	int index = strResponse.find(strFind);
	if (index == -1)
	{
		//解析错误码:"code":"1001"=密码错误,"code":"1003"="用户不存在"
		tstring strErrorPwd("\"code\":\"1001\"");
		tstring strErrorNotExist("\"code\":\"1003\"");
		int nIndex1 = strResponse.find(strErrorPwd);
		int nIndex2 = strResponse.find(strErrorNotExist);

		if (nIndex1 != -1)
		{
			CMsgBox* pMsgBox = new CMsgBox("错误",_T("密码错误!"),MSGBOX_ICON_ERROR, MSGBOX_IDOK);
			pMsgBox->ShowModal(NULL);
		} 
		else if (nIndex2 != -1)
		{
			CMsgBox* pMsgBox = new CMsgBox("错误",_T("账户不存在!"),MSGBOX_ICON_ERROR, MSGBOX_IDOK);
			pMsgBox->ShowModal(NULL);
		}
		else
		{
			CMsgBox* pMsgBox = new CMsgBox("错误",_T("用户验证失败!"),MSGBOX_ICON_ERROR, MSGBOX_IDOK);
			pMsgBox->ShowModal(NULL);
		}

		return false;
	}
	index += strFind.length()+3;

	if (!strResponse.empty())
	{
		tstring strToken = strResponse.substr(index, 32/*strResponse.length()-index-2*/);

		//计算token长度
		if (!strToken.empty())
		{
			m_strToken = strToken;
			m_pLogin = new CLogin(strPhone, strPwd);
			if (NULL != m_pLogin)
			{
				return m_pLogin->LoginToServer();
			}
		}
	}

	return false;
}
Example #22
0
CMemoryView::CTitle::CTitle(int64 ID, const tstring& Name)
:CVSpace2(ID),m_Text(Name.c_str())
{
	m_ObjectCount = 0;
	SetAreaSize(200,20);
}
Example #23
0
 void SetText(const tstring& s) {SetText(s.c_str());}
Example #24
0
Describe::objectType TROTL_EXPORT Describe::getObjectType(OciConnection &con, const tstring &objectName)
{
	sword res;
	OciDescribe desc(con._env);

	try
	{
		res = OCICALL(OCIDescribeAny(con._svc_ctx, con._env._errh,
		                             (dvoid*)objectName.c_str(),  // objptr (IN) (string containing the name of the object, pointer to a REF to the TDO, pointer to a TDO
		                             (ub4)objectName.size(),  // objnm_len (IN)
		                             OCI_OTYPE_NAME,   // objptr_typ (IN) points to the name of a schema object
		                             (ub1)OCI_DEFAULT, // info_level (IN) for future extensions. Pass OCI_DEFAULT.
		                             OCI_PTYPE_UNK,    // OCI_PTYPE_TABLE,  //
		                             desc
		                            ));
		oci_check_error(__TROTL_HERE__, con._env._errh, res);
	}
	catch(OciException const &e)
	{
		if(e.get_code() == 4043)
		{
			sb4 val = -1; // ub2 val = 1; /* size of OCI_ATTR_DESC_PUBLIC is undocumented. */
			desc.set_attribute(OCI_ATTR_DESC_PUBLIC, &val);

			res = OCICALL(OCIDescribeAny(con._svc_ctx, con._env._errh,
			                             (dvoid*)objectName.c_str(),  // objptr (IN) (string containing the name of the object, pointer to a REF to the TDO, pointer to a TDO
			                             (ub4)objectName.size(),  // objnm_len (IN)
			                             OCI_OTYPE_NAME,   // objptr_typ (IN) points to the name of a schema object
			                             (ub1)OCI_DEFAULT, // info_level (IN) for future extensions. Pass OCI_DEFAULT.
			                             OCI_PTYPE_UNK,    // OCI_PTYPE_TABLE,  //
			                             desc
			                            ));
			oci_check_error(__TROTL_HERE__, con._env._errh, res);
		}
		else
		{
			throw e;
		}
	}

	OciParam param = desc.get_param();
	ub1 obj_type = param.get_attribute<ub1>(OCI_ATTR_PTYPE);
	switch(obj_type)
	{
	case OCI_PTYPE_SYN:
		return O_SYNONYM;
	case OCI_PTYPE_TABLE:
		return O_TABLE;
	case OCI_PTYPE_VIEW:
		return O_VIEW;
	case OCI_PTYPE_PROC:
		return O_PROCEDURE;
	case OCI_PTYPE_FUNC:
		return O_FUNCTION;
	case OCI_PTYPE_PKG:
		return O_PACKAGE;
	case OCI_PTYPE_TYPE:
		return O_TYPE;
	case OCI_PTYPE_SEQ:
		return O_SEQUENCE;
	case OCI_PTYPE_TYPE_ATTR:
	case OCI_PTYPE_TYPE_COLL:
	case OCI_PTYPE_TYPE_METHOD:
	case OCI_PTYPE_COL: // - column of a table or view
	case OCI_PTYPE_ARG: // - argument of a function or procedure
	case OCI_PTYPE_TYPE_ARG: // - argument of a type method
	case OCI_PTYPE_TYPE_RESULT: // - results of a method
	case OCI_PTYPE_LIST: // - column list for tables and views, argument list for functions and procedures, or subprogram list for packages
	case OCI_PTYPE_SCHEMA: // - schema
	case OCI_PTYPE_DATABASE: // - database
	case OCI_PTYPE_UNK: // - unknown schema object
		throw_oci_exception(OciException(__TROTL_HERE__, "Error describing object: %d\n").arg(obj_type));
		//no break here
	default:
		throw_oci_exception(OciException(__TROTL_HERE__, "Error describing object: %d\n").arg(obj_type));
		//no break here
	}
};
Example #25
0
void PopupManager::Show(const tstring &aMsg, const tstring &aTitle, int Icon, bool preview /*= false*/)
{
	dcassert(ClientManager::isStartup() == false);
	dcassert(ClientManager::isShutdown() == false);
	if (ClientManager::isShutdown())
		return;
	if (ClientManager::isStartup())
		return;
		
	if (!m_is_activated)
		return;
		
		
	if (!Util::getAway() && BOOLSETTING(POPUP_AWAY) && !preview)
		return;
		
	if (!MainFrame::isAppMinimized() && BOOLSETTING(POPUP_MINIMIZED) && !preview)
		return;
		
	tstring msg = aMsg;
	if (int(aMsg.length()) > SETTING(MAX_MSG_LENGTH))
	{
		msg = aMsg.substr(0, (SETTING(MAX_MSG_LENGTH) - 3));
		msg += _T("...");
	}
#ifdef _DEBUG
	msg += Text::toT(" m_popups.size() = " + Util::toString(m_popups.size()));
#endif
	
	if (SETTING(POPUP_TYPE) == BALLOON && MainFrame::getMainFrame())
	{
		NOTIFYICONDATA m_nid = {0};
		m_nid.cbSize = sizeof(NOTIFYICONDATA);
		m_nid.hWnd = MainFrame::getMainFrame()->m_hWnd;
		m_nid.uID = 0;
		m_nid.uFlags = NIF_INFO;
		m_nid.uTimeout = (SETTING(POPUP_TIME) * 1000);
		m_nid.dwInfoFlags = Icon;
		_tcsncpy(m_nid.szInfo, msg.c_str(), 255);
		_tcsncpy(m_nid.szInfoTitle, aTitle.c_str(), 63);
		Shell_NotifyIcon(NIM_MODIFY, &m_nid);
		return;
	}
	
	if (m_popups.size() > 10)
	{
		//LogManager::message("PopupManager - m_popups.size() > 10! Ignore");
		return;
	}
	
	if (SETTING(POPUP_TYPE) == CUSTOM && PopupImage != SETTING(POPUPFILE))
	{
		PopupImage = SETTING(POPUPFILE);
		m_popuptype = SETTING(POPUP_TYPE);
		m_hBitmap = (HBITMAP)::LoadImage(NULL, Text::toT(PopupImage).c_str(), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION);
	}
	
	height = SETTING(POPUP_H);
	width = SETTING(POPUP_W);
	
	CRect rcDesktop;
	
	//get desktop rect so we know where to place the popup
	::SystemParametersInfo(SPI_GETWORKAREA, 0, &rcDesktop, 0);
	
	int screenHeight = rcDesktop.bottom;
	int screenWidth = rcDesktop.right;
	
	//if we have popups all the way up to the top of the screen do not create a new one
	if ((offset + height) > screenHeight)
		return;
		
	//get the handle of the window that has focus
	dcassert(WinUtil::g_mainWnd);
	HWND gotFocus = ::SetFocus(WinUtil::g_mainWnd);
	
	//compute the window position
	CRect rc(screenWidth - width , screenHeight - height - offset, screenWidth, screenHeight - offset);
	
	//Create a new popup
	PopupWnd *p = new PopupWnd(msg, aTitle, rc, m_id++, m_hBitmap);
	p->height = height; // save the height, for removal
	
	if (SETTING(POPUP_TYPE) != /*CUSTOM*/ BALLOON)
	{
		typedef bool (CALLBACK * LPFUNC)(HWND hwnd, COLORREF crKey, BYTE bAlpha, DWORD dwFlags);
		LPFUNC _d_SetLayeredWindowAttributes = (LPFUNC)GetProcAddress(LoadLibrary(_T("user32")), "SetLayeredWindowAttributes");
		if (_d_SetLayeredWindowAttributes)
		{
			p->SetWindowLongPtr(GWL_EXSTYLE, p->GetWindowLongPtr(GWL_EXSTYLE) | WS_EX_LAYERED | WS_EX_TRANSPARENT);
			_d_SetLayeredWindowAttributes(p->m_hWnd, 0, SETTING(POPUP_TRANSP), LWA_ALPHA);
		}
	}
	
	//move the window to the top of the z-order and display it
	p->SetWindowPos(HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
	p->ShowWindow(SW_SHOWNA);
	
	//restore focus to window
	::SetFocus(gotFocus);
	
	//increase offset so we know where to place the next popup
	offset = offset + height;
	
	m_popups.push_back(p);
}
void Alert(const tstring& sMessage)
{
	fputs(sMessage.c_str(), stderr);
}
Example #27
0
Extract::ARC_RESULT Extract::operator()(const tstring& arc_path,tstring& err_msg){
	if(IS_TERMINATED)return ARC_USER_CANCEL;

	bool split_file=false;
	tstring join_file_name;

	if(str::locateLastCharacter(arc_path.c_str(),'.')!=-1){
		switch(splitfile::joinFile(arc_path.c_str(),m_split_temp_dir.c_str())){
			case splitfile::join::SUCCESS:{
				split_file=true;
				msg::info(_T("ファイルを結合しました。\n"));
				join_file_name=path::addTailSlash(m_split_temp_dir);
				join_file_name+=path::removeExtension(path::getFileName(arc_path));
				break;
			}
			case splitfile::join::NOT_SPLIT:
			default:
				//分割された書庫ではない
				break;
			case splitfile::join::CANNOT_CREATE:
			case splitfile::join::MALLOC_ERR:
				err_msg=_T("ファイルの結合に失敗しました。\n");
			return ARC_FAILURE;
		}
	}

	m_arc_dll=NULL;

	msg::info(_T("ライブラリを読み込んでいます..."));

	loadArcLib();

	//ファイルがロックされていないかテスト
	if(ARCCFG->m_wait){
		bool success=false;
		int retries=0;
		const int max_retries=5;

		do{
			HANDLE handle=::CreateFile(arc_path.c_str(),
									   GENERIC_READ,
									   0,
									   NULL,
									   OPEN_EXISTING,
									   FILE_ATTRIBUTE_NORMAL,
									   NULL);

			if(handle==INVALID_HANDLE_VALUE){
				retries++;
				::Sleep(ARCCFG->m_wait);
				continue;
			}
			success=true;
			SAFE_CLOSE_EX(handle,INVALID_HANDLE_VALUE);
			break;
		}while(retries<max_retries);

		if(!success){
			msg::info(_T("\n"));
			err_msg+=_T("ファイルを開くことが出来ません。");
			err_msg+=arc_path.c_str();
			err_msg+=_T("\n");
			return ARC_FAILURE;
		}
	}

	{
		bool loaded_library=false;

		tstring current_dir(path::getCurrentDirectory());

		::SetCurrentDirectory(m_original_cur_dir.c_str());

		if(!CFG.general.selected_library_name.empty()){
			//ライブラリが指定されている場合
			m_arc_dll=loadAndCheck(m_arcdll_list.begin(),
								   m_arcdll_list.end(),
								   arc_path.c_str(),
								   &loaded_library,
								   NULL,
								   path::removeExtension(path::getFileName(CFG.general.selected_library_name)).c_str(),
								   CFG.general.selected_library_name.c_str());
		}else{
			//拡張子からの推測
			m_arc_dll=loadAndCheck(m_arcdll_list.begin(),
								   m_arcdll_list.end(),
								   arc_path.c_str(),
								   &loaded_library,
								   path::getExtension(arc_path).c_str());

			//総当たり
			if(!m_arc_dll){
				m_arc_dll=loadAndCheck(m_arcdll_list.begin(),
									   m_arcdll_list.end(),
									   arc_path.c_str(),
									   &loaded_library);
			}
		}

		if(!m_arc_dll){
			if(!CFG.general.selected_library_name.empty()){
				//ライブラリが指定されている場合
				m_arc_dll=loadAndCheckPlugin(&m_spi_list,
											 arc_path.c_str(),
											 &loaded_library,
											 CFG.general.spi_dir,
											 CFG.general.selected_library_name.c_str(),
											 Archiver::SPI_AM);
			}else{
				m_arc_dll=loadAndCheck(m_spi_list.begin(),
									   m_spi_list.end(),
									   arc_path.c_str(),
									   &loaded_library);
			}
		}

		if(!m_arc_dll){
			if(!CFG.general.selected_library_name.empty()){
				//ライブラリが指定されている場合
				m_arc_dll=loadAndCheckPlugin(&m_wcx_list,
											 arc_path.c_str(),
											 &loaded_library,
											 CFG.general.wcx_dir,
											 CFG.general.selected_library_name.c_str(),
											 Archiver::WCX);
			}else{
				m_arc_dll=loadAndCheck(m_wcx_list.begin(),
									   m_wcx_list.end(),
									   arc_path.c_str(),
									   &loaded_library);
			}
		}

		::SetCurrentDirectory(current_dir.c_str());

		if(!m_arc_dll){
			if(ARCCFG->m_password_input_cancelled){
				STDOUT.outputString(_T("\n"));
				err_msg=_T("パスワードの入力がキャンセルされました。\n");
				return ARC_INPUT_PASSWORD_CANCEL;
			}else if(!CFG.general.selected_library_name.empty()&&!loaded_library){
				STDOUT.outputString(_T("\n"));
				err_msg=format(_T("ライブラリ '%s' の読み込みに失敗しました。\n"),CFG.general.selected_library_name.c_str());
				return ARC_CANNOT_LOAD_LIBRARY;
			}else{
				STDOUT.outputString(_T("\n"));
				err_msg=_T("対応していない圧縮形式かファイルが壊れています。\n");
				return ARC_NOT_SUPPORTED_METHOD;
			}
		}
	}

	if(IS_TERMINATED)return ARC_USER_CANCEL;

	msg::info(_T(" %s\n"),m_arc_dll->getInformation().c_str());

	if(m_arc_dll->type()==Archiver::CAL&&
	   static_cast<ArcDll*>(m_arc_dll)->getRunning()){
		err_msg=_T("他のプロセスで使用中です。\n");
		return ARC_LIBRARY_IS_BUSY;
	}else{
		if(CFG.general.background_mode&&
		   m_arc_dll->setBackgroundMode(true)){
			msg::info(_T("バックグラウンドモードに設定しました。\n"));
		}

		if(CFG.mode==MODE_RECOMPRESS){
			//'@'の処理で
			if(CFG.compress.compression_type.c_str()[0]=='@'&&
			   //一括再圧縮の一度目か
			   ((!CFG.compress.each_file&&m_cur_file.recompress_mhd.empty())||
				//'/e'
			   CFG.compress.each_file)){
				DWORD mhd_opt=0;

				if(CFG.compress.compression_type.find(_T("pw"))!=tstring::npos){
					mhd_opt|=ArcDll::MHD_PASSWORD;
				}

				if(CFG.compress.compression_type.find(_T("he"))!=tstring::npos){
					mhd_opt|=ArcDll::MHD_HEADERENCRYPTION;
				}

				if(CFG.compress.compression_type.find(_T("sfx"))!=tstring::npos){
					mhd_opt|=ArcDll::MHD_SFX;
				}

				if(m_arc_dll->type()==Archiver::CAL){
					if(m_arc_dll){
						m_cur_file.recompress_mhd.assign(static_cast<ArcDll*>(m_arc_dll)->getCompressionMethod((!split_file)?arc_path.c_str():join_file_name.c_str()));
					}
				}else{
					//統合アーカイバ以外
					for(size_t i=0,list_size=m_arcdll_list.size();i<list_size;i++){
						if(!(!m_arcdll_list[i]->isLoaded()&&!m_arcdll_list[i]->load())){
							if(m_arcdll_list[i]->isSupportedArchive((!split_file)?arc_path.c_str():join_file_name.c_str())){
								if(!(m_cur_file.recompress_mhd.assign(m_arcdll_list[i]->getCompressionMethod((!split_file)?arc_path.c_str():join_file_name.c_str()))).empty()){
									break;
								}
							}
						}
					}
				}

				if(m_cur_file.recompress_mhd.empty())m_cur_file.recompress_mhd=_T("zip");
				if(mhd_opt&ArcDll::MHD_PASSWORD)m_cur_file.recompress_mhd+=_T("pw");
				if(mhd_opt&ArcDll::MHD_HEADERENCRYPTION)m_cur_file.recompress_mhd+=_T("he");
				if(mhd_opt&ArcDll::MHD_SFX)m_cur_file.recompress_mhd+=_T("sfx");
			}
		}

		if(IS_TERMINATED)return ARC_USER_CANCEL;

		tstring output_dir(path::getParentDirectory(arc_path));
		bool created_dir=false;

		if(!CFG.general.output_dir.empty()){
			std::vector<TCHAR> buffer(MAX_PATHW);

			path::getFullPath(&buffer[0],
							  buffer.size(),
							  CFG.general.output_dir.c_str(),
							  ((!CFG.general.default_base_dir)?
							   output_dir.c_str():
							   m_original_cur_dir.c_str()));
			output_dir.assign(&buffer[0]);
			if(!path::fileExists(output_dir.c_str())){
				if(!fileoperation::createDirectory(output_dir.c_str())){
					err_msg.assign(format(_T("ディレクトリ '%s' の作成に失敗しました。\n"),output_dir.c_str()));
					return ARC_CANNOT_CREATE_DIRECTORY;
				}
			}
		}

		if(CFG.mode==MODE_RECOMPRESS){
			output_dir=ARCCFG->m_recmp_temp_dir.c_str();
		}

		//新規ディレクトリ作成
		if(CFG.extract.create_dir){
			bool redundant_dir=false;

			//ディレクトリ階層を無視する場合は二重ディレクトリを考慮しない
			if(CFG.general.ignore_directory_structures){
				CFG.extract.create_dir_optimization.remove_redundant_dir.double_dir=false;
			}

			//パスを二つ以上除く場合であれば二重ディレクトリ防止を無効に
			if(CFG.compress.exclude_base_dir==-1||
			   CFG.compress.exclude_base_dir){
				CFG.extract.create_dir_optimization.remove_redundant_dir.double_dir=false;
			}

			if(CFG.extract.create_dir_optimization.remove_redundant_dir.double_dir||
			   CFG.extract.create_dir_optimization.remove_redundant_dir.only_file){
				redundant_dir=
					m_arc_dll->isRedundantDir((!split_file)?arc_path.c_str():join_file_name.c_str(),
														 CFG.extract.create_dir_optimization.remove_redundant_dir.double_dir,
														 CFG.extract.create_dir_optimization.remove_redundant_dir.only_file);
			}

			if(!redundant_dir){
				//新規ディレクトリ名作成
				tstring new_dir_name(path::getFileName((!split_file)?arc_path:join_file_name));

				//tar系を考慮しつつ拡張子削除
				new_dir_name=removeExtensionEx(new_dir_name);

				if(CFG.extract.create_dir_optimization.omit_number_and_symbol.number&&
				   CFG.extract.create_dir_optimization.omit_number_and_symbol.symbol){
					//ディレクトリ名末尾の数字と記号を削除
					new_dir_name=path::removeLastNumberAndSymbol(new_dir_name);
				}else if(CFG.extract.create_dir_optimization.omit_number_and_symbol.number){
					//ディレクトリ名末尾の数字を削除
					new_dir_name=path::removeLastNumber(new_dir_name);
				}else if(CFG.extract.create_dir_optimization.omit_number_and_symbol.symbol){
					//ディレクトリ名末尾の記号を削除
					new_dir_name=path::removeLastSymbol(new_dir_name);
				}

				output_dir=path::addTailSlash(output_dir)+=new_dir_name;

				created_dir=fileoperation::createDirectory(output_dir.c_str());
				if(!created_dir){
					err_msg=format(_T("ディレクトリ '%s' の作成に失敗しました。\n"),output_dir.c_str());
					return ARC_CANNOT_CREATE_DIRECTORY;
				}
			}
		}

		//区切り文字を末尾に追加
		output_dir=path::addTailSlash(output_dir);

		if(!STDOUT.isRedirected()&&
		   !CFG.no_display.no_information){
			misc::thread::post(m_progressbar_thread.id,WM_CREATE_PROGRESSBAR);
		}
		//コールバック関数を登録
		m_arc_dll->setCallback(m_progressbar_thread.id);

		if(IS_TERMINATED)return ARC_USER_CANCEL;

		//解凍
		tstring log;
		bool result=false;

		switch(m_arc_dll->extract((!split_file)?arc_path.c_str():join_file_name.c_str(),
											 output_dir.c_str(),
											 &log)){
			case Archiver::ARC_SUCCESS:
				result=true;
				break;
			case Archiver::ARC_CANNOT_OPEN_LISTFILE:
				msg::err(_T("リストファイルを開くことが出来ませんでした。\n"));
				break;
			case Archiver::ARC_NO_MATCHES_FOUND:
				msg::err(_T("フィルタに一致するファイルはありません。\n"));
				break;
			case Archiver::ARC_FAILURE:
			default:
				err_msg=_T("エラーが発生しました。\n");
				break;
		}

		if(!STDOUT.isRedirected()&&
		   !CFG.no_display.no_information){
			misc::thread::post(m_progressbar_thread.id,WM_DESTROY_PROGRESSBAR);
		}
		//コールバック関数の登録を解除
		m_arc_dll->clearCallback();

		if(created_dir&&
		   CFG.extract.create_dir_optimization.copy_timestamp){
			//作成したディレクトリの更新日時を書庫と同じにする
			File arc(arc_path.c_str(),
						  OPEN_EXISTING,
						  GENERIC_READ,
						  FILE_SHARE_READ);
			File dir(output_dir.c_str());
			FILETIME ft={};

			arc.getFileTime(&ft);
			dir.setFileTime(&ft);
		}

		if(!result){
			msg::lasterr();
		}

		if(!CFG.no_display.no_log){
			STDOUT.outputString(Console::LOW_GREEN,Console::NONE,_T("%s\n"),log.c_str());
		}
		return (result)?ARC_SUCCESS:ARC_FAILURE;
	}
	return ARC_FAILURE;
}
void CreateDirectoryNonRecursive(const tstring& sPath)
{
	TUnimplemented();

	mkdir(sPath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
Example #29
0
 gcc_pure
 tstring::const_pointer GetPath() const {
   return filename.c_str();
 }
Example #30
0
int Win32DebugAppender::append(const tstring &logMsg)
{
	OutputDebugString(logMsg.c_str());
	return 0;
}