Exemplo n.º 1
0
void CInstallPathDlg::OnOK() 
{
	UpdateData(TRUE);

	m_strPath.TrimRight();
	if (m_strPath.IsEmpty())
	{
		MessageBox("You need to enter the path to Shadows of Amn.","No Path");
		return;
	}

	if (m_strPath.Right(1) != "\\")
	{
		m_strPath += "\\";
		UpdateData(FALSE);
	}

	// Verify that the game is really there. If IDMain.exe is not there allow them
	// to continue, but warn them.
	CString strFile(m_strPath+"BGMain.exe");
	DWORD dwAttr = GetFileAttributes(strFile);
	if (dwAttr == 0xFFFFFFFF)
	{
		CString strMessage = "The Shadows of Amn executable was not found at this location. "
			"Are you sure this is the correct directory?";
		if (MessageBox(strMessage,"BGMain.exe Not Found",MB_YESNO|MB_ICONQUESTION) == IDNO)
			return;
	}

	EndDialog(IDOK);
}
Exemplo n.º 2
0
void MciPlayer::Open(const char* pFileName, UINT uId)
{
//     WCHAR * pBuf = NULL;
    do 
    {
        BREAK_IF(! pFileName || ! _wnd);
        int nLen = (int)strlen(pFileName);
        BREAK_IF(! nLen);
//         pBuf = new WCHAR[nLen + 1];
//         BREAK_IF(! pBuf);
//         MultiByteToWideChar(CP_ACP, 0, pFileName, nLen + 1, pBuf, nLen + 1);
        
        std::string strFile(pFileName);
        int nPos = strFile.rfind(".") + 1;
        strExt = strFile.substr(nPos, strFile.length() - nPos);

        Close();

        MCI_OPEN_PARMS mciOpen = {0};
        MCIERROR mciError;
        mciOpen.lpstrDeviceType = (LPCTSTR)MCI_ALL_DEVICE_ID;
		WCHAR* fileNameWideChar = new WCHAR[nLen + 1];
		BREAK_IF(! fileNameWideChar);
		MultiByteToWideChar(CP_ACP, 0, pFileName, nLen + 1, fileNameWideChar, nLen + 1);
        mciOpen.lpstrElementName = fileNameWideChar;

        mciError = mciSendCommand(0,MCI_OPEN, MCI_OPEN_ELEMENT, reinterpret_cast<DWORD_PTR>(&mciOpen));
		CC_SAFE_DELETE_ARRAY(mciOpen.lpstrElementName);
        BREAK_IF(mciError);

        _dev = mciOpen.wDeviceID;
        _soundID = uId;
        _playing = false;
    } while (0);
}
Exemplo n.º 3
0
static JSBool
AfxGlobal_load(JSContext *cx, unsigned argc, JS::Value *vp)
{
    JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
	if(1 > args.length())
		return JS_FALSE;

    JSString *str = JS_ValueToString(cx, args[0]);
    if (!str)
        return JS_FALSE;

    char *filename = JS_EncodeString(cx, str);
	if(!filename)
		return JS_FALSE;

	std::string strFile(filename);

	JS_free(cx, filename);

    JS::RootedObject thisobj(cx, JS_THIS_OBJECT(cx, vp));
    if (!thisobj)
        return false;

	JSScript *script = JS::Compile(cx, thisobj, JS::CompileOptions(cx), strFile.c_str());
	if(!script)
		return JS_FALSE;

	jsval result;

	if(!JS_ExecuteScript(cx, thisobj, script, &result))
		return JS_FALSE;

	args.rval().set(result);
	return JS_TRUE;
}
Exemplo n.º 4
0
void QSPCallBacks::PlayFile(QSPString file, int volume)
{
	FMOD_SOUND *newSound;
	FMOD_CHANNEL *newChannel;
	QSPSound snd;
	if (SetVolume(file, volume)) return;
	CloseFile(file);
	wxString strFile(wxFileName(wxString(file.Str, file.End), wxPATH_DOS).GetFullPath());
	#if defined(__WXMSW__) || defined(__WXOSX__)
	if (!FMOD_System_CreateSound(m_sys, wxConvFile.cWX2MB(strFile.c_str()), FMOD_SOFTWARE | FMOD_CREATESTREAM, 0, &newSound))
	#else
	FMOD_CREATESOUNDEXINFO exInfo;
	memset(&exInfo, 0, sizeof(FMOD_CREATESOUNDEXINFO));
	exInfo.cbsize = sizeof(FMOD_CREATESOUNDEXINFO);
	wxString dlsPath(QSPTools::GetAppPath() + QSP_MIDIDLS);
	wxCharBuffer dlsCharPath(wxConvFile.cWX2MB(dlsPath.c_str()));
	exInfo.dlsname = dlsCharPath;
	if (!FMOD_System_CreateSound(m_sys, wxConvFile.cWX2MB(strFile.c_str()), FMOD_SOFTWARE | FMOD_CREATESTREAM, &exInfo, &newSound))
	#endif
	{
		UpdateSounds();
		FMOD_System_PlaySound(m_sys, FMOD_CHANNEL_FREE, newSound, FALSE, &newChannel);
		snd.Channel = newChannel;
		snd.Sound = newSound;
		snd.Volume = volume;
		m_sounds.insert(QSPSounds::value_type(strFile.Upper(), snd));
		SetVolume(file, volume);
	}
}
Exemplo n.º 5
0
int CFileName::FindFiles (LPCTSTR pszDir,CFileNameArray &ar,LPCTSTR pszPattern/*=_T("*.*")*/,bool bRecurse/*=true*/,DWORD dwExclude/*=FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_HIDDEN*/)
{
  ar.RemoveAll();
  CFileFind finder;
  BOOL bMore=finder.FindFile(CFileName(pszDir)+pszPattern);
  while (bMore)    {
    bMore = finder.FindNextFile();
    if(!finder.IsDots() && !finder.MatchesMask(dwExclude)){
      CFileName strFile(finder.GetFilePath());
      ar.Add(strFile);
    }
  }
  if(bRecurse){
    CFileFind finder;
    BOOL bMore=finder.FindFile(CFileName(pszDir)+_T("*.*"));
    while (bMore)    {
      bMore = finder.FindNextFile();
      if(!finder.IsDots() && finder.IsDirectory()){
        CFileNameArray ar2;
        FindFiles(finder.GetFilePath(),ar2,pszPattern,bRecurse,dwExclude);
        ar.Append(ar2);
      }
    }
  }
  return ar.GetSize();
}
Exemplo n.º 6
0
/*
   SaveForbid - принудительно запретить запись добавляемой строки.
                Используется на панели плагина
*/
void History::AddToHistory(const string& Str, history_record_type Type, const GUID* Guid, const wchar_t *File, const wchar_t *Data, bool SaveForbid)
{
	_ASSERTE(this!=NULL);
	if (!m_EnableAdd || SaveForbid)
		return;

	if (Global->CtrlObject->Macro.IsExecuting() && Global->CtrlObject->Macro.IsHistoryDisable((int)m_TypeHistory))
		return;

	if (m_TypeHistory!=HISTORYTYPE_DIALOG && (m_TypeHistory!=HISTORYTYPE_FOLDER || !Guid || *Guid == FarGuid) && Str.empty())
		return;

	bool Lock = false;
	string strName(Str),strGuid,strFile(NullToEmpty(File)),strData(NullToEmpty(Data));
	if(Guid) strGuid=GuidToStr(*Guid);

	unsigned __int64 DeleteId = 0;

	const bool ignore_data = m_TypeHistory == HISTORYTYPE_CMD;

	if (m_RemoveDups) // удалять дубликаты?
	{
		DWORD index=0;
		string strHName,strHGuid,strHFile,strHData;
		history_record_type HType;
		bool HLock;
		unsigned __int64 id;
		unsigned __int64 Time;
		while (HistoryCfgRef()->Enum(index++,m_TypeHistory,m_HistoryName,&id,strHName,&HType,&HLock,&Time,strHGuid,strHFile,strHData))
		{
			if (EqualType(Type,HType))
			{
				typedef int (*CompareFunction)(const string&, const string&);
				CompareFunction CaseSensitive = StrCmp, CaseInsensitive = StrCmpI;
				CompareFunction CmpFunction = (m_RemoveDups == 2 ? CaseInsensitive : CaseSensitive);

				if (!CmpFunction(strName, strHName) &&
					!CmpFunction(strGuid, strHGuid) &&
					!CmpFunction(strFile, strHFile) &&
					(ignore_data || !CmpFunction(strData, strHData)))
				{
					Lock = Lock || HLock;
					DeleteId = id;
					break;
				}
			}
		}
	}

	HistoryCfgRef()->DeleteAndAddAsync(DeleteId, m_TypeHistory, m_HistoryName, strName, Type, Lock, strGuid, strFile, strData);  //Async - should never be used in a transaction

	ResetPosition();
}
Exemplo n.º 7
0
void CRC32Test::testFile()
{
	//Test Existing file
	StdString strFile(_T("C:\\WINDOWS\\system32\\cmd.exe"));
	StdString strValue = pHash->GetFileHash(strFile);
	strFile = _T("Z:\\a.TXT");
	strValue = pHash->GetFileHash(strFile);
	//Test Unexisting file
	strFile = _T("XX.xx");
	strValue = pHash->GetFileHash(strFile);
	CPPUNIT_ASSERT(strValue == _T(""));
}
Exemplo n.º 8
0
XL_BITMAP_HANDLE XmlDataLoader::LoadImage(const char* lpFile)
{
	std::string strFile(lpFile);
	std::wstring wlpFile;
	Win32Transcode::UTF8_to_Unicode(lpFile, strlen(lpFile), wlpFile);
	const wchar_t* lpExt = ::PathFindExtension(wlpFile.c_str());
	if (lpExt && ::lstrcmpi(lpExt, L".png") == 0)
	{
		XL_BITMAP_HANDLE hBitmap = XL_LoadBitmapFromFile(wlpFile.c_str(), XLGRAPHIC_CT_ARGB32);
		assert(hBitmap);
		return hBitmap;
	}
	return NULL;
}
Exemplo n.º 9
0
uint8 UMcf::loadFromFile(const wchar_t* file)
{
    gcString strFile(file);
    XML::gcXMLDocument doc(strFile.c_str());

    if (!doc.IsValid())
        return MCF_ERR_INVALIDHANDLE;

    parseUpdateXml(doc);

    if (m_pFileList.size() == 0)
        return MCF_ERR_FAILEDREAD;

    return MCF_OK;
}
Exemplo n.º 10
0
BOOL CCeWatchDlg::Load(LPCTSTR file) 
{
    ASSERT(file);
	if(!file)
	{
        return FALSE;
	}

    CString strFile(file);
    if(strFile.IsEmpty())
    {
        return FALSE;
    }
    return m_VarList.Load(strFile); 
}
Exemplo n.º 11
0
void CTestList::OnSelectionChanged(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
	UINT u = m_treeList.GetItemData( pNMTreeView->itemNew.hItem );

	CString strFile( m_arrFile[ u ] );

	if( strFile.Find( _T(".html") ) != -1 )
	{
		m_strLastLoaded = m_arrFile[ u ];
		AfxGetApp()->OpenDocumentFile( m_arrFile[ u ] );
	}

	*pResult = 0;
}
/*!
 * \brief Launch external file viewer.
 */
bool CConfigItem::ViewHeaderFile()
{
    bool rc = false;
    wxString strFile(GetFilename());

    if (!strFile.IsEmpty()) {
        CNutConfDoc *pDoc = wxGetApp().GetNutConfDoc();
        if (pDoc->GetBuildTree().IsEmpty()) {
            wxMessageBox(wxT("Cannot display header file until configuration is saved"));
        } else {
            strFile.Prepend(wxT("/"));
            strFile.Prepend(pDoc->GetBuildTree());
            //rc = wxGetApp().Launch(strFile, "notepad.exe");
            rc = wxGetApp().Launch(strFile, wxEmptyString);
        }
    }
    return rc;
}
Exemplo n.º 13
0
static void DiffDir_WalkDir(LPCTSTR strDirIn, CDiffer& D)
{
	std::string strDir(strDirIn);
	if( '\\' != (strDir.at(strDir.length()-1)) )
	{
		strDir.append("\\");
	}

	std::string strSearch(strDir);
	strSearch.append("*");

	//printf("Scanning \"%s\"...\n", strDir.c_str());

	WIN32_FIND_DATA FD;
	HANDLE hFind = FindFirstFile(strSearch.c_str(), &FD);
	if(INVALID_HANDLE_VALUE == hFind)
		return;

	do
	{
		//If we have a directory we behave a little differently.
		if(((FILE_ATTRIBUTE_DIRECTORY&FD.dwFileAttributes) != 0))
		{
			//printf("Found directory.\n");
			if('.' == FD.cFileName[0])
				continue;

			std::string strSubDir(strDir);
			strSubDir.append(FD.cFileName);
			DiffDir_WalkDir(strSubDir.c_str(), D);
		}
		else
		{
			std::string strFile(strDir);
			strFile.append(FD.cFileName);
			//printf("Found %s.\n", strFile.c_str());
			D.AddFile(strFile.c_str(), FD);
		}

	}while(FindNextFile(hFind, &FD));

	FindClose(hFind);
}
Exemplo n.º 14
0
void CMainFrame::OnDestroy() 
{
    
    WINDOWPLACEMENT wp;
	memset (&wp, 0 , sizeof(wp));
	wp.length = sizeof(wp);
	GetWindowPlacement(&wp);
	if ( wp.showCmd == SW_SHOWMINIMIZED ) 
		wp.showCmd = SW_SHOW;
    ::WritePrivateProfileBinary("View" , "WindowPlacement" ,(LPBYTE)&wp, sizeof(wp), szGLOBAL_PROFILE);

	CWinApp* pApp = AfxGetApp();
    const char* pProfSave= pApp->m_pszProfileName;
	pApp->m_pszProfileName = szGLOBAL_PROFILE;
	SaveBarState("View");
	pApp->m_pszProfileName = pProfSave;
	
    if ( m_wndSplitter.GetRowCount() > 1 ) {
        m_wndSplitter.SavePosition();
    }

    SaveBarState("JMC");
//vls-begin// multiple output
//    m_coolBar.Save();
    for (int i = 0; i < MAX_OUTPUT; i++)
        m_coolBar[i].Save();
//vls-end//

    // save history 
    CFile histFile;
//vls-begin// base dir
//    if ( histFile.Open("history.dat", CFile::modeCreate | CFile::modeWrite ) ) {
    CString strFile(szBASE_DIR);
    strFile += "\\history.dat";
    if ( histFile.Open(strFile, CFile::modeCreate | CFile::modeWrite ) ) {
//vls-end//
        CArchive ar(&histFile, CArchive::store);
        m_editBar.GetHistory().Serialize (ar);
    }

    pMainWnd = NULL;
    CFrameWnd::OnDestroy();
}
Exemplo n.º 15
0
void MciPlayer::Open(const char* pFileName, UINT uId)
{
    BEATS_ASSERT(pFileName != NULL && _wnd != NULL);
    BEATS_ASSERT(strlen(pFileName) > 0);

    std::string strFile(pFileName);
    int nPos = strFile.rfind(".") + 1;
    strExt = strFile.substr(nPos, strFile.length() - nPos);

    Close();

    MCI_OPEN_PARMS mciOpen = {0};
    MCIERROR mciError;
    mciOpen.lpstrDeviceType = (LPCTSTR)MCI_ALL_DEVICE_ID;
    mciOpen.lpstrElementName = pFileName;

    mciError = mciSendCommand(0,MCI_OPEN, MCI_OPEN_ELEMENT, reinterpret_cast<DWORD_PTR>(&mciOpen));
    BEATS_ASSERT(mciError == 0, _T("mciSendCommand failed!"));
    _dev = mciOpen.wDeviceID;
    _soundID = uId;
    _playing = false;
}
Exemplo n.º 16
0
BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
					 )
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
	{
		char FileName[MAX_PATH + 1] = { 0 };
		GetModuleFileNameA(hModule, FileName, MAX_PATH);
		std::string strFile(FileName);
		int index = strFile.rfind("dll\\");
		dllPath = strFile.substr(0, index);
		break;
	}
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		break;
	}
	return TRUE;
}
Exemplo n.º 17
0
CAtom *DecodeFile( const char *szFile )
{
	FILE *pFile = NULL;

	if( ( pFile = fopen( szFile, "rb" ) ) == NULL )
	{
		UTIL_LogPrint( "warning - unable to open %s for reading\n", szFile );

		return NULL;
	}

	fseek( pFile, 0, SEEK_END );
	unsigned long ulFileSize = ftell( pFile );
	fseek( pFile, 0, SEEK_SET );
	char *pData = (char *)malloc( sizeof( char ) * ulFileSize );
	memset( pData, 0, sizeof( char ) * ulFileSize );
	fread( (void *)pData, sizeof( char ), ulFileSize, pFile );
	fclose( pFile );
	string strFile( pData, ulFileSize );
	free( pData );

	return Decode( strFile );
}
Exemplo n.º 18
0
// Load config info
bool ecSettings::LoadConfig()
{
    wxConfig config(wxGetApp().GetSettings().GetConfigAppName());
    
    config.Read(_("/Window Status/FrameStatus"), & m_frameStatus);
    config.Read(_("/Window Status/ShowToolBar"), (bool*) & m_showToolBar);
    config.Read(_("/Window Status/ShowSplashScreen"), (bool*) & m_showSplashScreen);
    config.Read(_("/Window Status/ShowConflictsWindow"), (bool*) & m_showConflictsWindow);
    config.Read(_("/Window Status/ShowPropertiesWindow"), (bool*) & m_showPropertiesWindow);
    config.Read(_("/Window Status/ShowShortDescrWindow"), (bool*) & m_showShortDescrWindow);
    config.Read(_("/Window Status/ShowMemoryWindow"), (bool*) & m_showMemoryWindow);
    config.Read(_("/Window Status/ShowOutputWindow"), (bool*) & m_showOutputWindow);
    
    config.Read(_("/Files/LastFile"), & m_lastFilename);
    
    config.Read(_("/Window Size/WindowX"), & m_frameSize.x);
    config.Read(_("/Window Size/WindowY"), & m_frameSize.y);
    config.Read(_("/Window Size/WindowWidth"), & m_frameSize.width);
    config.Read(_("/Window Size/WindowHeight"), & m_frameSize.height);

    config.Read(_("/Window Size/TreeSashWidth"), & m_treeSashSize.x);
    config.Read(_("/Window Size/TreeSashHeight"), & m_treeSashSize.y);
    config.Read(_("/Window Size/ConfigPaneWidth"), & m_configPaneWidth);
    config.Read(_("/Window Size/ConflictsWidth"), & m_conflictsSashSize.x);
    config.Read(_("/Window Size/ConflictsHeight"), & m_conflictsSashSize.y);
    config.Read(_("/Window Size/PropertiesWidth"), & m_propertiesSashSize.x);
    config.Read(_("/Window Size/PropertiesHeight"), & m_propertiesSashSize.y);
    config.Read(_("/Window Size/ShortDescrWidth"), & m_shortDescrSashSize.x);
    config.Read(_("/Window Size/ShortDescrHeight"), & m_shortDescrSashSize.y);
    config.Read(_("/Window Size/OutputWidth"), & m_outputSashSize.x);
    config.Read(_("/Window Size/OutputHeight"), & m_outputSashSize.y);
    config.Read(_("/Window Size/MemoryWidth"), & m_memorySashSize.x);
    config.Read(_("/Window Size/MemoryHeight"), & m_memorySashSize.y);

    config.Read(_("/Options/ShowMacroNames"), (bool*) & m_showMacroNames);
    config.Read(_("/Options/UseCustomViewer"), (bool*) & m_bUseCustomViewer);
    config.Read(_("/Options/UseExternalBrowser"), (bool*) & m_bUseExternalBrowser);
    
    int tmp = (int) m_eUseCustomBrowser;
    config.Read(_("/Options/UseCustomBrowser"), & tmp);
    m_eUseCustomBrowser = (ecBrowserType) tmp;
    
    config.Read(_("/Options/Browser"), & m_strBrowser);
    config.Read(_("/Options/Viewer"), & m_strViewer);
    config.Read(_("/Options/HexDisplay"), (bool*) & m_bHex);
    config.Read(_("/Options/UseDefaultFonts"), (bool*) & m_windowSettings.m_useDefaults);
    config.Read(_("/Rule/Checking"), & m_nRuleChecking);

    // Find dialog settings
    config.Read(_("/Find/Text"), & m_findText);
    config.Read(_("/Find/MatchWholeWord"), (bool*) & m_findMatchWholeWord);
    config.Read(_("/Find/MatchCase"), & m_findMatchCase);
    config.Read(_("/Find/Direction"), (bool*) & m_findDirection);
    config.Read(_("/Find/SearchWhat"), & m_findSearchWhat);
    config.Read(_("/Find/DialogX"), & m_findDialogPos.x);
    config.Read(_("/Find/DialogY"), & m_findDialogPos.y);

    // Package dialog settings
    config.Read(_("/Packages/OmitHardwarePackages"), & m_omitHardwarePackages);
    config.Read(_("/Packages/MatchPackageNamesExactly"), & m_matchPackageNamesExactly);

    // Run tests settings
    m_runTestsSettings.LoadConfig(config);

    // Fonts
    m_windowSettings.LoadConfig(config);   
    
    if (!config.Read(_("/Paths/UserToolsDir"), & m_userToolsDir))
    {
        // Use the default provided by the installer
        config.Read(_("Default User Tools Path"), & m_userToolsDir);
    }

    // Only to be used if we fail to find the information installed
    // with the Configuration Tool.
    config.Read(_("/Paths/BuildToolsDir"), & m_buildToolsDir);
    if (m_buildToolsDir.IsEmpty()) // first invocation by this user
    {
        // we have no clues as to the location of the build tools so
        // test for ../../../gnutools relative to the configtool location
        wxFileName gnutools = wxFileName (wxGetApp().GetAppDir(), wxEmptyString);
        gnutools.Normalize(); // remove trailing "./" if present
		if (2 < gnutools.GetDirCount())
        {
            gnutools.RemoveDir (gnutools.GetDirCount()-1);
            gnutools.RemoveDir (gnutools.GetDirCount()-1);
            gnutools.RemoveDir (gnutools.GetDirCount()-1);
            gnutools.AppendDir (wxT("gnutools"));
            if (gnutools.DirExists()) // we've found the gnutools
                m_buildToolsDir = gnutools.GetFullPath();
        }
    }

    // look for *objcopy in and under the build tools directory
    if (! m_buildToolsDir.IsEmpty())
    {
        wxArrayString objcopyFiles;
        wxString objcopyFileSpec(wxT("objcopy"));
#ifdef __WXMSW__
        objcopyFileSpec += wxT(".exe");
#endif
        size_t objcopyCount = wxDir::GetAllFiles(m_buildToolsDir, &objcopyFiles, wxT("*") + objcopyFileSpec, wxDIR_FILES | wxDIR_DIRS);
        for (int count=0; count < objcopyCount; count++)
        {
            wxFileName file (objcopyFiles [count]);
            wxString new_prefix (file.GetFullName().Left (file.GetFullName().Find(objcopyFileSpec)));
            if ((! new_prefix.IsEmpty()) && ('-' == new_prefix.Last()))
                new_prefix = new_prefix.Left (new_prefix.Len() - 1); // strip off trailing hyphen
            m_arstrBinDirs.Set(new_prefix, file.GetPath(wxPATH_GET_VOLUME));
        }
    }

    if (!config.Read(_("/Build/Make Options"), & m_strMakeOptions))
    {
#ifdef __WXMSW__
        SYSTEM_INFO SystemInfo;
        GetSystemInfo(&SystemInfo);
//        disable -j option for now due to problem with Cygwin 1.3.18
//        m_strMakeOptions.Printf(_T("-j%d"),SystemInfo.dwNumberOfProcessors);
#endif
    }
    
    // Set default build tools binary directories as specified by the installer
    ecFileName strDefaultBuildToolsPath;

#ifdef __WXMSW__
    {
        // This should look in HKEY_LOCAL_MACHINE

        wxConfig config2(wxT("eCos"), wxEmptyString, wxEmptyString, wxEmptyString, wxCONFIG_USE_GLOBAL_FILE|wxCONFIG_USE_LOCAL_FILE);

        wxString versionKey = GetInstallVersionKey();
        wxConfigPathChanger path(& config2, wxString(wxT("/")) + versionKey + wxT("/"));

        if (!versionKey.IsEmpty() && config2.Read(wxT("Default Build Tools Path"), & strDefaultBuildToolsPath))
        {
#ifdef __WXMSW__
            wxString gccExe(wxT("*-gcc.exe"));
#else
            wxString gccExe(wxT("*-gcc"));
#endif
            
            // Note that this is not a recursive search. Compilers for
            // different targets may be in the same directory. This finds all targets.
            
            // look for *-gcc[.exe] in the default build tools directory
            wxLogNull log;
            wxDir finder(strDefaultBuildToolsPath);
            wxString filename;
            
            if (finder.IsOpened())
            {
                bool bMore = finder.GetFirst(& filename, gccExe);
                while (bMore)
                {
                    wxString targetName = filename.Left(filename.Find(wxT("-gcc")));
                    m_arstrBinDirs.Set(targetName, strDefaultBuildToolsPath);
                    
                    bMore = finder.GetNext(& filename);
                }
            }
        }
    }
#endif

#ifndef __WXMSW__
    // Look in the PATH for build tools, under Unix
    {
        wxString strPath;
        if (wxGetEnv(wxT("PATH"), & strPath))
        {
	    wxString gccExe(wxT("*-gcc"));

	    wxArrayString arstrPath;
            ecUtils::Chop(strPath, arstrPath, wxT(':'));

            for (int i = arstrPath.GetCount()-1;i >= 0; --i)
            { // Reverse order is important to treat path correctly
                if (wxT(".") != arstrPath[i] && !arstrPath[i].IsEmpty())
                {
                    wxLogNull log;
                    wxDir finder(arstrPath[i]);
                    wxString filename;

                    if (finder.IsOpened())
                    {
                        bool bMore = finder.GetFirst(& filename, gccExe);
                        while (bMore)
                        {
                            wxString targetName = filename.Left(filename.Find(wxT("-gcc")));
                            m_arstrBinDirs.Set(targetName, arstrPath[i]);

                            bMore = finder.GetNext(& filename);
                        }
                    }
                }
            }
        }
    }
#endif
    
    // Read build tools directories (current user)
    
    {
        wxConfigPathChanger path(& config, wxT("/Build Tools/"));
        //config.SetPath(wxT("/Build Tools"));
        wxString key(wxT(""));
        long index;
        bool bMore = config.GetFirstEntry(key, index);
        while (bMore)
        {
            wxString value;
            if (config.Read(key, & value))
            {
                m_arstrBinDirs.Set(key, value);
            }
            bMore = config.GetNextEntry(key, index);
        }
    }
    
    // Read toolchain paths (local machine again)
#ifdef __WXMSW__    
    wxArrayString arstrToolChainPaths;

    // Use eCos just as a test.
    //GetRepositoryRegistryClues(arstrToolChainPaths,_T("eCos"));
    GetRepositoryRegistryClues(arstrToolChainPaths,_T("GNUPro eCos"));
    
    size_t i;
    for (i = (size_t) 0; i < arstrToolChainPaths.GetCount(); i++)
    {
        ecFileName strDir(arstrToolChainPaths[i]);
        strDir += wxT("H-i686-cygwin32\\bin");
        
        if (strDir.IsDir())
        {
            // This is a potential toolchain location. Look for *-gcc.exe
            wxLogNull log;
            wxDir finder(strDefaultBuildToolsPath);
            wxString filename;
            
            if (finder.IsOpened())
            {
                bool bMore = finder.GetFirst(& filename, wxT("*-gcc.exe"));
                while (bMore)
                {
                    // TODO: if there is more than one path, we will have to
                    // check the existance of this target name in m_arstrBinDirs and
                    // append to the end, or something.
                    wxString targetName = filename.Left(filename.Find(wxT("-gcc")));
                    m_arstrBinDirs.Set(targetName, strDefaultBuildToolsPath);
                    
                    bMore = finder.GetNext(& filename);
                }
            }
        }
    }

    // The official user tools are now Cygwin 00r1. If you can't find these,
    // try GNUPro unsupported.
    GetRepositoryRegistryClues(m_userToolPaths, wxT("GNUPro 00r1"));
    if (m_userToolPaths.GetCount() == 0)
    {
        GetRepositoryRegistryClues(m_userToolPaths, wxT("Cygwin 00r1"));
    }

    if (m_userToolPaths.GetCount() > 0)
    {
        for ( i = (size_t) 0 ; i < m_userToolPaths.GetCount(); i++)
        {
            ecFileName str(m_userToolPaths[i]);
            str += "H-i686-cygwin32\\bin";
            if(str.IsDir())
            {
                m_userToolPaths[i] = str;
            } else
            {
                m_userToolPaths.Remove(i);
                i--;
            }
        }
    }
    else
    {
        GetRepositoryRegistryClues(m_userToolPaths, wxT("GNUPro unsupported"));
        
        for ( i = (size_t) 0 ; i < m_userToolPaths.GetCount(); i++)
        {
            ecFileName str(m_userToolPaths[i]);
            str += "H-i686-cygwin32\\bin";
            if(str.IsDir())
            {
                m_userToolPaths[i] = str;
            } else
            {
                m_userToolPaths.Remove(i);
                i--;
            }
        }
    }
#endif
    
    // Include the path in the set of potential user paths
    {
        wxString strPath;
        if (wxGetEnv(wxT("PATH"), & strPath))
        {
            wxArrayString arstrPath;
            ecUtils::Chop(strPath, arstrPath, wxT(';'));
            
            for (int i = arstrPath.GetCount()-1;i >= 0; --i)
            { // Reverse order is important to treat path correctly

                const ecFileName &strFolder = arstrPath[i];
                if (wxT(".") != strFolder && !strFolder.IsEmpty())
                {
                    ecFileName strFile(strFolder);
                    strFile += wxT("ls.exe");
                    if ( strFile.Exists() )
                    {
                        if (!wxArrayStringIsMember(m_userToolPaths, strFolder))
                        {
                            m_userToolPaths.Add(strFolder);
                        }

                        if ( m_userToolsDir.IsEmpty() )
                        {
                            m_userToolsDir = strFolder;
                        }
                    }
                }
            }
        }
    }
    
    // Load current repository from eCos Configuration Tool/Paths/RepositoryDir
    {
        wxConfig eCosConfig(wxGetApp().GetSettings().GetConfigAppName(), wxEmptyString, wxEmptyString, wxEmptyString, wxCONFIG_USE_GLOBAL_FILE|wxCONFIG_USE_LOCAL_FILE);
        wxConfigPathChanger path(& config, wxT("/Repository/"));

        //if (!eCosConfig.Read(wxT("Folder"), & m_strRepository))
        if (!eCosConfig.Read(wxT("/Paths/RepositoryDir"), & m_strRepository))
        {
#ifdef __WXMSW__
            // If we can't find the current folder, look for clues in the registry.
            wxArrayString arstr;
            switch (GetRepositoryRegistryClues(arstr, wxT("eCos")))
            {
            case 0:
                break;
            case 1:
            default:
                m_strRepository = arstr[0];
                break;
            }
#elif defined(__WXGTK__)
            // If we can't find the current folder, look for the latest version
            // in /opt/ecos
            m_strRepository = FindLatestVersion();
#else
            // Unsupported platform
            m_strRepositor = wxEmptyString;
#endif
        }

        // If we have set ECOS_REPOSITORY, this overrides whatever we have
        // read or found.
        wxString envVarValue = wxGetenv(wxT("ECOS_REPOSITORY"));
        if (!envVarValue.IsEmpty())
        {
            // Note that ECOS_REPOSITORY has the packages (or ecc) folder in the name.
            // In order to be in the form that is compatible with configtool operation,
            // it needs to have that stripped off.
            envVarValue = ecUtils::PosixToNativePath(envVarValue); // accommodate posix-style ECOS_REPOSITORY value under Cygwin
            wxString packagesName = wxFileNameFromPath(envVarValue);
            if (packagesName == wxT("ecc") || packagesName == wxT("packages"))
                envVarValue = wxPathOnly(envVarValue);

            m_strRepository = envVarValue;
        }
    }

#ifdef __WXMSW__
    if (m_userToolsDir.IsEmpty())
        m_userToolsDir = GetCygwinInstallPath() + wxT("\\bin");
#else
    if (m_userToolsDir.IsEmpty())
        m_userToolsDir = wxT("/bin");
#endif
    
    return TRUE;
}
Exemplo n.º 19
0
//获取文件列表
bool AnalyseClassCallRelation::GetFileList(vector<ClassSource> &vFileList)
{
	HANDLE file;
	WIN32_FIND_DATA fileData;
//	wchar_t fn[1000];
	char szFilename[1024]; 
//	mbstowcs(fn, m_strProjectPath.c_str() ,999);
	string strFind = m_strProjectPath + string("\\*.*"); 
	file = FindFirstFile(strFind.c_str(), &fileData);

	ClassSource clsClassSource; 
	clsClassSource.Init(); 
	//找到文件返回0  否则返回-1
	while(FindNextFile(file, &fileData))
	{
		// 只对普通文件做处理
		if (!(fileData.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE))
		{
			continue; 
		}
		sprintf(szFilename, "%s", fileData.cFileName); 
		//判读是头文件 还是源文件  判断名称是否存在
		//获取后缀
		char *pTemp = szFilename + strlen(szFilename); 
		while( pTemp > szFilename && *pTemp-- != '.') ; 
		if (pTemp == szFilename)
		{
			continue; 
		}
		++ pTemp ; 
		string strSuffix(pTemp); 
		if (strSuffix == ".cpp")
		{
			clsClassSource.byHasImplementation = 1; 
		}
		else if(strSuffix == ".h" || strSuffix == ".hpp")
		{
			clsClassSource.byHasHeader = 1;
		}
		else
			continue;
		string strFile(szFilename, pTemp-szFilename);
		clsClassSource.strName = strFile; 
		vector<ClassSource>::iterator iter = vFileList.begin(); 
		while (iter != vFileList.end() )
		{
			if (iter->strName == strFile)
			{
				iter->byHasHeader = clsClassSource.byHasHeader?1:iter->byHasHeader; 
				iter->byHasImplementation = clsClassSource.byHasImplementation?1:iter->byHasImplementation; 
				break;; 
			}
			++ iter; 
		}
		if (iter == vFileList.end() )
		{
			vFileList.push_back(clsClassSource);
			clsClassSource.Init(); 
		}
	}
	return true; 
}
Exemplo n.º 20
0
void ModifyStartupFile(GString &strStartupKey,GString &strServerPassword,GString &strRoot,GString &strPort)
{
	///////////////////////////////////////////////////////////////////
	// load the following values fron the startup file:
	//////////////////////////////////////////////////////////////////
	GString strCurrentPassword;
	GString strCurrentRoot;
	GString strCurrentPort;
	
	GString strThisEXEName(GetThisEXEName());
	GString strStartupData;
	if (strStartupKey.Length())
	{
		// look for a file in the root of the file system (c:\)
		// with the same name as this .exe
		GString strFile("c:\\");
		strFile += strThisEXEName;


		// load the crypted disk file into clear text memory
		char *pDest;
		int nDestLen;
		GString strErrorOut;
		if (FileDecryptToMemory(strStartupKey, strFile, &pDest, &nDestLen, strErrorOut))
		{
			// parse into the profile data structures
			pDest[7 + nDestLen] = 0; // null terminate it
			strStartupData.write(&pDest[7], nDestLen + 1); // and cap the GString 
		}
		else
		{
			// if the file was not in the root of the file system
			// see if there is an environment setting directing
			// this server to look for the file in another location
			// The variable name is dynamic, matching this .exe name
			// and the environment variable value must be a fully
			// qualified path and file name to the startup file.
			if (getenv(strThisEXEName))
			{
				if (FileDecryptToMemory(strStartupKey, getenv(strThisEXEName), &pDest, &nDestLen, strErrorOut))
				{
					// parse into the profile data structures
					strStartupData.write(&pDest[7], nDestLen-7);
				}
			}
		}

		// parse stored settings in startup file to startup variables
		if (strStartupData.Length())
		{
			GStringList lstOptions("&&",strStartupData);
			GStringIterator it(&lstOptions);
			
			if (it()) strCurrentPassword = it++;
			if (it()) strCurrentRoot = it++;
			if (it()) strCurrentPort = it++;
		}
	}
	//////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////


	// new values over write the old ones
	if (strServerPassword.Length())
		strCurrentPassword = strServerPassword;

	if (strPort.Length())
		strCurrentPort = strPort;

	if (strRoot.Length() && strRoot.CompareNoCase("none") != 0)
		strCurrentRoot = strRoot;
	else if (strRoot.CompareNoCase("none") == 0)
	{
		strCurrentRoot = "";
	}
	


	// use root of file system to store the startup file 
	// unless specified otherwise by environment setting
	GString strOutFile("c:\\");
	strOutFile += strThisEXEName;
	if (getenv(strThisEXEName))
	{
		strOutFile += getenv(strThisEXEName);
	}
	
	
	// create the new startup file
	GString strTempFile;
	strTempFile << strServerPassword << "&&" << strRoot << "&&" << strPort;
	strTempFile.ToFile("tempfile");
	GString strErrorOut;
	unlink(strOutFile);
	FileEncrypt(strStartupKey, "tempfile", strOutFile, strErrorOut);
	unlink("tempfile");
}
Exemplo n.º 21
0
void WINAPI TimeServiceMain(DWORD dwArgc, LPTSTR *lpszArgv) 
{
#ifdef _WIN64
   unsigned __int64 dwCompKey  = CK_SERVICECONTROL;
#else
   DWORD dwCompKey  = CK_SERVICECONTROL;
#endif
   DWORD fdwControl = SERVICE_CONTROL_RUN;
   DWORD dwBytesTransferred;
   OVERLAPPED *po;
   SERVICE_STATUS ss;
   SERVICE_STATUS_HANDLE hSS;
   BOOL bPasswordCompileEmbedded = 0;

// We must get the private password for connecting to this machine.
// The password can be compiled into the server any of the following ways......


//  1 way - the easiest way, just uncomment and put any value between the quotes
//  then remove the code between --Load External Password Begin & End-- below
//  ***** example of very simple integrated password ********
//  GString strPassword("Password");
//	GString strPort("80");
//	GString strRoot;
//	bPasswordCompileEmbedded = 1;


//  Another way - a most secure way to embed the password.
//  ***** example of integrated password ********
//  GString strPassword;
//	MakePassword(strPassword);    // Go read the MakePassword() routine above.
//	GString strPort("80");
//	GString strRoot;
//	bPasswordCompileEmbedded = 1;


//              OR

// The password can be retrieved from an external disk location.
// Passwords can be obtained from disk in two different ways.
// Either in a registry key matching the (probably renamed) 
// executable file that is this server, OR by loading a 
// predefined file name at a predefined location. 
// This file must be present while starting the server, but can be
// removed once this process has fully started.


//  --Load External Password Begin--
GString strPassword;
GString strPort;
GString strRoot;

if (!bPasswordCompileEmbedded)
{
	GString strThisEXEName(GetThisEXEName());
	GString strStartupKey;

	// use our runtime image name as the registry key
	char buf[512];
	long lSize = sizeof(buf);
	if (RegQueryValue(HKEY_CLASSES_ROOT,(const char *)strThisEXEName,buf,&lSize) == ERROR_SUCCESS)
	{
		// uudecode the startup key
		BUFFER b;
		BufferInit(&b);
		unsigned int nDecoded;
		uudecode(buf, &b, &nDecoded, false);
		strStartupKey.write((const char *)b.pBuf,nDecoded);
		BufferTerminate(&b);
	}

	GString strStartupData;
	if (strStartupKey.Length())
	{
		// look for a file in the root of the file system (c:\)
		// with the same name as this .exe
		GString strFile("c:\\");
		strFile += strThisEXEName;


		// load the crypted disk file into clear text memory
		char *pDest;
		int nDestLen;
		GString strErrorOut;
		if (FileDecryptToMemory(strStartupKey, strFile, &pDest, &nDestLen, strErrorOut))
		{
			// parse into the profile data structures
			pDest[7 + nDestLen] = 0; // null terminate it
			strStartupData.write(&pDest[7], nDestLen + 1); // and cap the GString 
		}
		else
		{
			// if the file was not in the root of the file system
			// see if there is an environment setting directing
			// this server to look for the file in another location
			// The variable name is dynamic, matching this .exe name
			// and the environment variable value must be a fully
			// qualified path and file name to the startup file.
			if (getenv(strThisEXEName))
			{
				if (FileDecryptToMemory(strStartupKey, getenv(strThisEXEName), &pDest, &nDestLen, strErrorOut))
				{
					// parse into the profile data structures
					strStartupData.write(&pDest[7], nDestLen-7);
				}
			}
		}

		// parse stored settings in startup file to startup variables
		if (strStartupData.Length())
		{
			GStringList lstOptions("&&",strStartupData);
			GStringIterator it(&lstOptions);

			if (it()) strPassword = it++;
			if (it()) strRoot = it++; // currently not used
			if (it()) strPort = it++;
		}
	}
}

//  --Load External Password End--

	GString strFile;
	GString strConfigFileDefault;
	GString strErrorOut;
	int bSetStartupFile = 0;

#ifdef _WIN32
	SetPriorityClass(GetCurrentProcess(),HIGH_PRIORITY_CLASS); // = 1 point above normal
#endif


   // Create the completion port and save its handle in a global
   // variable so that the Handler function can access it.
   g_hIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, CK_PIPE, 0);

   // Give SCM the address of this service's Handler
   // NOTE: hSS does not have to be closed.
   hSS = RegisterServiceCtrlHandler((const char *)strServerName, TimeServiceHandler);

   // Do what the service should do.
   // Initialize the members that never change
   ss.dwServiceType = SERVICE_WIN32_OWN_PROCESS; 
   ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | 
      SERVICE_ACCEPT_PAUSE_CONTINUE | SERVICE_ACCEPT_SHUTDOWN;

   do {
      switch (dwCompKey) {
      case CK_SERVICECONTROL:
         // We got a new control code
         ss.dwWin32ExitCode = NO_ERROR; 
         ss.dwServiceSpecificExitCode = 0; 
         ss.dwCheckPoint = 0; 
         ss.dwWaitHint = 0;

         if (fdwControl == SERVICE_CONTROL_INTERROGATE) {
            SetServiceStatus(hSS, &ss);
            break;
         }

         // Determine which PENDING state to return
         if (dwSrvCtrlToPend[fdwControl] != 0) {
            ss.dwCurrentState = dwSrvCtrlToPend[fdwControl]; 
            ss.dwCheckPoint = 0;
            ss.dwWaitHint = 500;   // half a second
            SetServiceStatus(hSS, &ss);
         }

         switch (fdwControl) {
            case SERVICE_CONTROL_RUN:
            case SERVICE_CONTROL_CONTINUE:
				try
				{
					if (strRoot.Length() && strPort.Length())
					{
						GString strCfgData;
						strCfgData.Format(pzBoundStartupConfig,(const char *)strRoot,(const char *)strPort);
						SetProfile(new GProfile((const char *)strCfgData, (int)strCfgData.Length(), 0));

						if (!server_start())
						{
							ss.dwCurrentState = SERVICE_STOPPED; 
							ss.dwCheckPoint = ss.dwWaitHint = 0;
							SetServiceStatus(hSS, &ss);
							break;
						}
					}
					else
					{
						// No password compiled in - and no valid startup file found
						for(int i=0; i<3;i++)
						{
							// three beeps
							MessageBeep(0);
							Sleep(1000);
						}
						ss.dwCurrentState = SERVICE_STOPPED; 
						ss.dwCheckPoint = ss.dwWaitHint = 0;
						SetServiceStatus(hSS, &ss);
						break;
					}
				}
				catch ( GException &)
				{
					ss.dwCurrentState = SERVICE_STOPPED; 
					ss.dwCheckPoint = ss.dwWaitHint = 0;
					SetServiceStatus(hSS, &ss);
					break;
				}



				if (dwSrvPendToState[ss.dwCurrentState] != 0) 
				{
					ss.dwCurrentState = dwSrvPendToState[ss.dwCurrentState]; 
					ss.dwCheckPoint = ss.dwWaitHint = 0;
					SetServiceStatus(hSS, &ss);
				}
				break;

            case SERVICE_CONTROL_PAUSE:
            case SERVICE_CONTROL_STOP:
            case SERVICE_CONTROL_SHUTDOWN:
                server_stop();
				if (dwSrvPendToState[ss.dwCurrentState] != 0) 
				{
					ss.dwCurrentState = dwSrvPendToState[ss.dwCurrentState]; 
					ss.dwCheckPoint = ss.dwWaitHint = 0;
					SetServiceStatus(hSS, &ss);
				}
				break;
         }

         // Determine which complete state to return
         break;

      }

      if (ss.dwCurrentState != SERVICE_STOPPED) {
         // Sleep until a control code comes in or a client connects
         GetQueuedCompletionStatus(g_hIOCP, &dwBytesTransferred,
            &dwCompKey, &po, INFINITE);
         fdwControl = dwBytesTransferred;
      }
   } while (ss.dwCurrentState != SERVICE_STOPPED);

   // Cleanup and stop this service
   CloseHandle(g_hIOCP);   
}
Exemplo n.º 22
0
void Conf::loadwindows()
{

QFile *file1 = new QFile(this);

file1->setFileName("config_resguardo");

file1->open(QFile::ReadOnly);

QString strFile(file1->readAll());

QStringList lista;

lista = strFile.split(",");

file1->close();


QString r1 = lista[0];
ui->lineEdit->setText(r1);

QString r2 = lista[1];
ui->lineEdit_3->setText(r2);

QString r3 = lista[2];
ui->lineEdit_2->setText(r3);



QString s1 = lista[3];
int x1 = s1.toInt();
ui->checkBox_3->setChecked(x1);


QString s2 = lista[4];
int x2 = s2.toInt();
ui->checkBox->setChecked(x2);


QString s3 = lista[5];
int x3 = s3.toInt();
ui->checkBox_2->setChecked(x3);


QString s4 = lista[6];
int x4 = s4.toInt();
ui->checkBox_4->setChecked(x4);


QString s5 = lista[7];
int x5 = s5.toInt();
ui->checkBox_5->setChecked(x5);


QString s6 = lista[8];
int x6 = s6.toInt();
ui->checkBox_6->setChecked(x6);


QString s7 = lista[9];
int x7 = s7.toInt();
ui->checkBox_13->setChecked(x7);


QString s8 = lista[10];
int x8 = s8.toInt();
ui->checkBox_14->setChecked(x8);


QString s9 = lista[11];
int x9 = s9.toInt();
ui->checkBox_15->setChecked(x9);


QString s10 = lista[12];
int x10 = s10.toInt();
ui->checkBox_7->setChecked(x10);


QString s11 = lista[13];
int x11 = s11.toInt();
ui->checkBox_8->setChecked(x11);


QString s12 = lista[14];
int x12 = s12.toInt();
ui->checkBox_9->setChecked(x12);


QString s13 = lista[15];
int x13 = s13.toInt();
ui->checkBox_10->setChecked(x13);


QString s14 = lista[16];
int x14 = s14.toInt();
ui->checkBox_11->setChecked(x14);


QString s15 = lista[17];
int x15 = s15.toInt();
ui->checkBox_12->setChecked(x15);


}
Exemplo n.º 23
0
int PakLoadAnyFile(const char *filename, void **bufferptr)
{
  char cWork[WORK_LEN];
  if (g_bPK3)
  {
    PK3FileInfo *pInfo;
    Str strKey;
    // need to lookup the file without the base/texture path on it
    Str strBase(g_strBasePath);
    AddSlash(strBase);
    __ConvertDOSToUnixName(cWork, strBase);
    Str strFile(filename);
    __ConvertDOSToUnixName(strFile, strFile);
    strFile.MakeLower();
    strlwr(cWork);
    FindReplace(strFile, cWork, "");

    PK3FileInfo infoFind;
    infoFind.m_pName = __StrDup(strFile.GetBuffer());
    PK3List *pList = g_PK3Files.Find(&infoFind);
    if (pList)
    {
      pInfo = pList->Ptr();
      memcpy(pInfo->m_zFile, &pInfo->m_zInfo, sizeof(unz_s));
      if (unzOpenCurrentFile(pInfo->m_zFile) == UNZ_OK)
      {
        void *buffer = __qblockmalloc(pInfo->m_lSize+1);
        int n = unzReadCurrentFile(pInfo->m_zFile , buffer, pInfo->m_lSize);
        *bufferptr = buffer;
        unzCloseCurrentFile(pInfo->m_zFile);
        return n;
      }
    }
#ifdef LOG_PAKFAIL
    sprintf(cWork, "PAK failed on %s\n", filename);
    g_LogFile.Log(cWork);
#endif
    return -1;
  }

	for (int i = 0; i < dirsize; i++)
	{
		if(!stricmp(filename, pakdirptr[i].name))
		{
			if (fseek(pakfile[m_nPAKIndex], pakdirptr[i].offset, SEEK_SET) >= 0)
      {
	      void *buffer = __qmalloc (pakdirptr[i].size+1);
	      ((char *)buffer)[pakdirptr[i].size] = 0;
			  if (fread(buffer, 1, pakdirptr[i].size, pakfile[m_nPAKIndex]) == pakdirptr[i].size)
        {
          *bufferptr = buffer;
          return pakdirptr[i].size;
        }
      }
		}
	}
#ifdef LOG_PAKFAIL
    sprintf(cWork, "PAK failed on %s\n", filename);
    g_LogFile.Log(cWork);
#endif
  return -1;
}
Exemplo n.º 24
0
void CPigEngine::ProcessScriptDirChanges()
{
  XLock lock(this);

  // Copy the map of scripts
  XScriptMap mapScripts(m_mapScripts);

  // Loop thru the "*.pig" files in the script directory
  WIN32_FIND_DATA ffd;
  USES_CONVERSION;
  LPSTR pszScriptDirPatt = OLE2A(m_bstrScriptDir + "*.pig");
  TCFileFindHandle hff = FindFirstFile(pszScriptDirPatt, &ffd);
  bool bContinue = !hff.IsNull() && INVALID_HANDLE_VALUE != hff;
  while (bContinue)
  {
    // Do not process directories, temporary or hidden files
    const DWORD dwIgnoreAttributes = FILE_ATTRIBUTE_DIRECTORY |
      FILE_ATTRIBUTE_TEMPORARY | FILE_ATTRIBUTE_HIDDEN;
    if (!(ffd.dwFileAttributes & dwIgnoreAttributes))
    {
      // Attempt to find the file name in the map of scripts
      tstring strFile(ffd.cFileName);
      XScriptMapIt it = mapScripts.find(strFile);
      if (mapScripts.end() == it)
        AddScriptFile(&ffd, strFile);
      else
      {
        if (it->second->IsModified(&ffd))
          ReloadScriptFile(&ffd, it);
        mapScripts.erase(it);
      }
    }

    // Get the next file in the directory
    bContinue = !!FindNextFile(hff, &ffd);
  }

  // Unload all files remaining in the local copy of the map of Scripts
  for (XScriptMapIt it = mapScripts.begin(); it != mapScripts.end(); ++it)
    UnloadScriptFile(it->first);

  ///////////////////////////////////////////////////////////////////////////
  // File Reconcilation is complete, now validate the files
  ///////////////////////////////////////////////////////////////////////////

  // Create a map of all behavior names, invalid or not
  XBehaviorMap mapGoodBadUgly;
  for (XScriptMapIt it = m_mapScripts.begin(); it != m_mapScripts.end(); ++it)
  {
    CPigBehaviorScriptType* pType = it->second;

    // Get the collection of invoke commands for the new object
    XBehaviorMap mapCommands;
    ZSucceeded(GetInvokeCommands(pType, mapCommands));

    // Add each invoke command to the map
    for (XBehaviorMapIt itCmd = mapCommands.begin(); itCmd != mapCommands.end(); ++itCmd)
    {
      mapGoodBadUgly.insert(*itCmd);
      debugf("inv command: %s\n", itCmd->first.c_str());
    }
  }

  // Check for base behaviors that don't exist
  for (XScriptMapIt it = m_mapScripts.begin(); it != m_mapScripts.end(); ++it)
  {
    CPigBehaviorScriptType* pType = it->second;
    if (pType->IsValid())
    {
      tstring strBaseBehavior(pType->GetBaseBehaviorName());
      if (strBaseBehavior.size() && _tcslen(strBaseBehavior.c_str()))
      {
        XBehaviorMapIt itFind = mapGoodBadUgly.find(strBaseBehavior);
        if (mapGoodBadUgly.end() == itFind)
        {
          RemoveInvokeCommands(pType);
          pType->SetBaseNonExistant();
        }
      }
    }
  }

  // Check for recursive behavior derivations
  for (XScriptMapIt it = m_mapScripts.begin(); it != m_mapScripts.end(); ++it)
  {
    CPigBehaviorScriptType* pType = it->second;
    if (pType->IsValid())
    {
      std::set<tstring, ci_less> setNames;
      CPigBehaviorScriptType* pTypeBase = pType;
      while (!pTypeBase->GetBaseBehaviorName().empty())
      {
        setNames.insert(pTypeBase->GetName());
        if (setNames.end() == setNames.find(pTypeBase->GetBaseBehaviorName()))
        {
          XScriptMapIt itBase = mapGoodBadUgly.find(pTypeBase->GetBaseBehaviorName());
          if (mapGoodBadUgly.end() != itBase) // KG- fix debug assert - was : m_mapBehaviors.end() != itBase
          {
            pTypeBase = itBase->second;
            continue;
          }
        }

        RemoveInvokeCommands(pType);
        pType->SetRecursionError();
        break;
      }
    }
  }

  // Check for behaviors that have base behaviors with errors
  for (XScriptMapIt it = m_mapScripts.begin(); it != m_mapScripts.end(); ++it)
  {
    CPigBehaviorScriptType* pType = it->second;
    if (pType->IsValid())
    {
      std::vector<CPigBehaviorScriptType*> vecBaseTypes;
      vecBaseTypes.push_back(pType);
      tstring strBaseBehavior(pType->GetBaseBehaviorName());
      while (strBaseBehavior.size() && _tcslen(strBaseBehavior.c_str()))
      {
        XBehaviorMapIt itBase = mapGoodBadUgly.find(strBaseBehavior);
        assert(mapGoodBadUgly.end() != itBase);
        pType = itBase->second;
        vecBaseTypes.push_back(pType);
        strBaseBehavior = pType->GetBaseBehaviorName();
      }

      std::vector<CPigBehaviorScriptType*>::reverse_iterator rit1, rit2;
      rit1 = rit2 = vecBaseTypes.rbegin();
      for (++rit2; rit2 != vecBaseTypes.rend(); ++rit1, ++rit2)
      {
        CPigBehaviorScriptType* pTypeBase = *rit1;
        CPigBehaviorScriptType* pType     = *rit2;
        if (!pTypeBase->IsValid() && pType->IsValid())
        {
          RemoveInvokeCommands(pType);
          pType->SetBaseError();
        }
      }
    }
  }

  // Compute the stats on how many good and bad scripts are available
  int nValid = 0;
  for (XScriptMapIt it = m_mapScripts.begin(); it != m_mapScripts.end(); ++it)
    if (it->second->IsValid())
      ++nValid;

  // Display the stats on how many good and bad scripts are available
  #ifdef _DEBUG
    _TRACE_BEGIN
      _TRACE_PART1("CPigEngine::ProcessScriptDirChanges(): %d scripts loaded, ",
        m_mapScripts.size());
      _TRACE_PART1("%d appear to be valid.\n", nValid);
    _TRACE_END
  #endif // _DEBUG

  // Trigger an event
  _AGCModule.TriggerEvent(NULL, PigEventID_ScriptsLoaded,
    L"", -1, -1, -1, 2,
    "TotalCount", VT_I4, m_mapScripts.size(),
    "ValidCount", VT_I4, nValid);
}