Example #1
0
// do lastchecked(file(X)) returns amount of chars to add to str pointer
int lastChecked(CMStringA &szNewStr, const char *str)
{
	char *szPattern = "lastchecked(file(";
	size_t cbPattern = mir_strlen(szPattern);

	if (!strncmp(str, szPattern, cbPattern)) {
		int file;
		char tszFileName[MAX_PATH], temp[MAX_PATH], szSetting[20];
		sscanf(&str[cbPattern], "%d", &file);
		mir_snprintf(szSetting, "fn%d", file);

		char *szVar = db_get_sa(NULL, MODNAME, szSetting);
		if (szVar == NULL)
			return 0;

		if (!strncmp("http://", szVar, 7) || !strncmp("https://", szVar, 8))
			mir_snprintf(tszFileName, _countof(tszFileName), "%s\\plugins\\fn%d.html", getMimDir(temp), file);
		else
			mir_strncpy(tszFileName, szVar, _countof(tszFileName));
		mir_free(szVar);

		HANDLE hFile = CreateFileA(tszFileName, 0, FILE_SHARE_READ, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
		if (hFile == INVALID_HANDLE_VALUE)
			return 0;

		if (GetLastWriteTime(hFile, tszFileName)) {
			CloseHandle(hFile);
			szNewStr.Append(tszFileName);
			mir_snprintf(tszFileName, _countof(tszFileName), "%s%d))", szPattern, file);
			return (int)mir_strlen(tszFileName);
		}
		CloseHandle(hFile);
	}
	return 0;
}
Example #2
0
bool BufferTimeList::IsChanged(unsigned long bufferId, FILETIME *pTime)
{
    AutoLock lock(&_sync);
    BufferTime *pFile = Find(bufferId);
    if (pFile == NULL)
        return false;
    return GetLastWriteTime(pFile->Path, pTime) && memcmp(pTime, &pFile->LastWriteTime, sizeof(FILETIME)) != 0;
}
Example #3
0
const TCHAR * CRegistryKey::GetLastWriteTime()
{
	SYSTEMTIME st;
	if (GetLastWriteTime(st) != ERROR_SUCCESS)
    return _T("(Cannot get time last write time)");

	static TCHAR Buffer[256];
	_stprintf(Buffer,_T("%d.%d.%d %02d:%02d:%02d"),st.wDay,st.wMonth,st.wYear,st.wHour,st.wMinute,st.wSecond);
	return Buffer;
}
Example #4
0
int main(int argc, char** argv)
{
  int Result = 0;
  if (argc < 4)
  {
    PrintHelp(argv);
    Result = 1;
  }
  else
  {
    GLSettings Settings = {};
    if (ParseCommandLine(&Settings, argc, argv))
    {
      Settings.WriteTimestamp = GetLastWriteTime(Settings.Output);
      unsigned long long MaxTimestamp = 0;
      for (int Index = 0; Index < Settings.InputCount; ++Index)
      {
        const char* InputFilename = Settings.Inputs[Index];
        unsigned long long LastWriteTime = GetLastWriteTime(InputFilename);
        if (LastWriteTime > MaxTimestamp)
        {
          MaxTimestamp = LastWriteTime;
        }
      }
      if (Settings.ForceGenerate || MaxTimestamp > Settings.WriteTimestamp)
      {
        Result = GenerateOpenGLHeader(&Settings);
      }
    }
    else
    {
      PrintHelp(argv);
      Result = 1;
    }
    FreeMemory(&Settings);
  }

  return Result;
}
Example #5
0
int	CompareTime(LPCSTR szL, LPCSTR szR) {
	assert(szL!=NULL && szR!=NULL);
	
	SYSTEMTIME	stL, stR;
	BOOL		fexistL, fexistR;
	
	// 更新日付を得る。
	fexistL = GetLastWriteTime(szL, stL);
	fexistR	= GetLastWriteTime(szR, stR);
	// 存在しないファイルは「古い」と見なす。
	if ( fexistL ) {
		if ( !fexistR)
			return	1;
	} else {
		if ( fexistR )
			return	-1;
		else
			return	0;	// どっちもありゃしねぇ
	}
	
	// 最終更新日付を比較
	if ( stL.wYear > stR.wYear )	return	1;
	else if ( stL.wYear < stR.wYear )	return	-1;
	if ( stL.wMonth > stR.wMonth )	return	1;
	else if ( stL.wMonth < stR.wMonth )	return	-1;
	if ( stL.wDay > stR.wDay )	return	1;
	else if ( stL.wDay < stR.wDay )	return	-1;
	if ( stL.wHour > stR.wHour )	return	1;
	else if ( stL.wHour < stR.wHour )	return	-1;
	if ( stL.wMinute > stR.wMinute )	return	1;
	else if ( stL.wMinute < stR.wMinute )	return	-1;
	if ( stL.wSecond > stR.wSecond )	return	1;
	else if ( stL.wSecond < stR.wSecond )	return	-1;
	if ( stL.wMilliseconds > stR.wMilliseconds )	return	1;
	else if ( stL.wMilliseconds < stR.wMilliseconds )	return	-1;
	// 制作日時の完全一致
	return	0;
}
Example #6
0
File: File.cpp Project: yagi/satori
/*----------------------------------------------------------------------
	ファイルの更新日時を比較。
	返値が正ならば前者、負ならば後者のほうが新しいファイル。
----------------------------------------------------------------------*/
int	CompareTime(LPCSTR szL, LPCSTR szR) {
    assert(szL!=NULL && szR!=NULL);

    SYSTEMTIME	stL, stR;
    BOOL		fexistL, fexistR;

    // 更新日付を得る。
    fexistL = GetLastWriteTime(szL, stL);
    fexistR	= GetLastWriteTime(szR, stR);
    // 存在しないファイルは「古い」と見なす。
    if ( fexistL ) {
        if ( !fexistR)
            return	1;
    } else {
        if ( fexistR )
            return	-1;
        else
            return	0;	// どっちもありゃしねぇ
    }

    // 最終更新日付を比較
    return	CompareTime(stL, stR);
}
Example #7
0
void BufferTimeList::Add(unsigned long bufferId)
{
    AutoLock lock(&_sync);
    TCHAR path[MAX_PATH];
    GetBufferFullPath(bufferId, path);

    BufferTime  *pFile = Find(bufferId);
    if (pFile == NULL)
    {
        pFile = new BufferTime();
        pFile->BufferId = bufferId;
        generic_strcpy(pFile->Path, path);
        if (GetLastWriteTime(path, &pFile->LastWriteTime))
            _files.push_back(pFile);
        else
            delete pFile;
    }
    else
    {
        generic_strcpy(pFile->Path, path);
        GetLastWriteTime(path, &pFile->LastWriteTime);
    }
}
int main(int argc, char *argv[])
{
	if (::SetFileAttributes("hidden.txt", 0x2))			//设置文件属性
		printf("设置文件隐藏属性成功!\n");
	else
		printf("设置文件隐藏属性失败!\n");

	WIN32_FIND_DATA FindFileData;
	HANDLE hFind;
	LPTSTR lpszLastWriteTime = new TCHAR[MAX_PATH];
	HANDLE hReadFile;
	
	printf ("Target file is %s.\n\n", argv[1]);
	hFind = FindFirstFile(argv[1], &FindFileData);
	if (hFind == INVALID_HANDLE_VALUE) 
	{
		printf ("Invalid File Handle. GetLastError reports %d\n", 
            GetLastError ());
		return -1;
	} 
	printf("%-30s%15s%30s\t%s","FileName","FileSize","LastWriteTime","Hidden\n");
	if('.' != FindFileData.cFileName[0])
	{
		hReadFile = CreateReadFile(FindFileData	.cFileName);
		GetLastWriteTime(hReadFile, lpszLastWriteTime, MAX_PATH);		
		printf ("%-30s%-10dBytes%30s\t", FindFileData.cFileName, GetFileSize(hReadFile, NULL), lpszLastWriteTime);
		
	}
	while (FindNextFile(hFind, &FindFileData) != 0)
	{
		if ('.' != FindFileData.cFileName[0]/* && IsHiddenFile(FindFileData.cFileName) == FALSE*/)
		{
			hReadFile = CreateReadFile(FindFileData	.cFileName);
			GetCreateTime(hReadFile, lpszLastWriteTime, MAX_PATH);
			printf ("%-30s%10dBytes%30s\t", FindFileData.cFileName, GetFileSize(hReadFile, NULL), lpszLastWriteTime);
		if (IsHiddenFile(FindFileData.cFileName) == TRUE)
			printf("隐藏\n");
		else
			printf("非隐藏\n");	
		}
		
	}
	//int n = -1;
	//FindClose((void*)&n);
	FindClose(hFind);
	return 0;
}
Example #9
0
BOOL NotifyFileChange(TCHAR *szPathName, HWND hwndNotify, HANDLE hQuitEvent)
{
	NOTIFY_DATA *pnd = malloc(sizeof(NOTIFY_DATA));

	ZeroMemory(pnd, sizeof(NOTIFY_DATA));

	pnd->hQuitEvent = 0;
	pnd->hwndNotify = hwndNotify;
	pnd->uMsg		= WM_USER;
	lstrcpy(pnd->szFile, szPathName);

	GetLastWriteTime(pnd->szFile, &pnd->lastChange);

	CreateThread(0, 0, ChangeNotifyThread, pnd, 0, 0);

	return TRUE;
}
Example #10
0
Game_Code LoadGameCode(char *path, char *temp)
{
	Game_Code result = {};

	result.LastWriteTimeDLL = GetLastWriteTime(path);

	CopyFile(path, temp, FALSE);

	result.GameCodeDLL = LoadLibraryA(temp);

	if (result.GameCodeDLL)
	{
		result.Game_Init = (game_init *)GetProcAddress(result.GameCodeDLL, "Game_Init");
		result.Game_Update = (game_update *)GetProcAddress(result.GameCodeDLL, "Game_Update");
		result.Game_Render = (game_render *)GetProcAddress(result.GameCodeDLL, "Game_Render");
	}

	return result;
}
Example #11
0
BOOL CALLBACK LoadedModules64(LPCSTR, DWORD64 ModuleBase, ULONG ModuleSize, PVOID UserContext)
{
	CMString& buffer = *(CMString*)UserContext;

	const HMODULE hModule = (HMODULE)ModuleBase;

	TCHAR path[MAX_PATH];
	GetModuleFileName(hModule, path, MAX_PATH);

	buffer.AppendFormat(TEXT("%s  %p - %p"), path, (LPVOID)ModuleBase, (LPVOID)(ModuleBase + ModuleSize));

	GetVersionInfo(hModule, buffer);

	TCHAR timebuf[30] = TEXT("");
	GetLastWriteTime(path, timebuf, 30);

	buffer.AppendFormat(TEXT(" [%s]\r\n"), timebuf);

	return TRUE;
}
Example #12
0
static void GetIconStrings(CMString& buffer)
{
	TCHAR path[MAX_PATH];
	GetModuleFileName(NULL, path, MAX_PATH);

	LPTSTR fname = _tcsrchr(path, TEXT('\\'));
	if (fname == NULL) fname = path;
	mir_sntprintf(fname, MAX_PATH - (fname - path), TEXT("\\Icons\\*.*"));

	WIN32_FIND_DATA FindFileData;
	HANDLE hFind = FindFirstFile(path, &FindFileData);
	if (hFind == INVALID_HANDLE_VALUE) return;

	do {
		if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;

		TCHAR timebuf[30] = TEXT("");
		GetLastWriteTime(&FindFileData.ftLastWriteTime, timebuf, 30);

		buffer.AppendFormat(TEXT(" %s [%s]\r\n"), FindFileData.cFileName, timebuf);
	} while (FindNextFile(hFind, &FindFileData));
	FindClose(hFind);
}
Example #13
0
void PrintVersionInfo(CMString& buffer, unsigned flags)
{
	GetProcessorString(buffer);
	buffer.Append(TEXT("\r\n"));

	GetFreeMemoryString(buffer);
	buffer.Append(TEXT("\r\n"));

	GetOSDisplayString(buffer);
	buffer.Append(TEXT("\r\n"));

	GetInternetExplorerVersion(buffer);
	buffer.Append(TEXT("\r\n"));

	GetAdminString(buffer);
	buffer.Append(TEXT("\r\n"));

	GetLanguageString(buffer);
	buffer.Append(TEXT("\r\n"));

	TCHAR *profpathfull = Utils_ReplaceVarsT(profpath);
	if (flags & VI_FLAG_PRNVAR) {
		GetFreeDiskString(profpathfull, buffer);
		buffer.Append(TEXT("\r\n"));
	}

	buffer.AppendFormat(TEXT("\r\nMiranda NG Version: %s"), vertxt);
	GetWow64String(buffer);
	buffer.Append(TEXT("\r\n"));

	TCHAR path[MAX_PATH], mirtime[30];
	GetModuleFileName(NULL, path, MAX_PATH);
	GetLastWriteTime(path, mirtime, 30);
	buffer.AppendFormat(TEXT("Build time: %s\r\n"), mirtime);

	TCHAR profpn[MAX_PATH];
	mir_sntprintf(profpn, _countof(profpn), TEXT("%s\\%s"), profpathfull, profname);

	buffer.AppendFormat(TEXT("Profile: %s\r\n"), profpn);

	if (flags & VI_FLAG_PRNVAR) {
		WIN32_FIND_DATA FindFileData;

		HANDLE hFind = FindFirstFile(profpn, &FindFileData);
		if (hFind != INVALID_HANDLE_VALUE) {
			FindClose(hFind);

			unsigned __int64 fsize = (unsigned __int64)FindFileData.nFileSizeHigh << 32 | FindFileData.nFileSizeLow;
			buffer.AppendFormat(TEXT("Profile size: %I64u Bytes\r\n"), fsize),

				GetLastWriteTime(&FindFileData.ftCreationTime, mirtime, 30);
			buffer.AppendFormat(TEXT("Profile creation date: %s\r\n"), mirtime);
		}
	}
	mir_free(profpathfull);

	GetLanguagePackString(buffer);
	buffer.Append(TEXT("\r\n"));

	// buffer.AppendFormat(TEXT("Nightly: %s\r\n"), _tcsstr(vertxt, TEXT("alpha")) ? TEXT("Yes") : TEXT("No")); 
	// buffer.AppendFormat(TEXT("Unicode: %s\r\n"), _tcsstr(vertxt, TEXT("Unicode")) ? TEXT("Yes") : TEXT("No")); 

	GetPluginsString(buffer, flags);

	if (flags & VI_FLAG_WEATHER) {
		buffer.AppendFormat(TEXT("\r\n%sWeather ini files:%s\r\n-------------------------------------------------------------------------------\r\n"),
			(flags & VI_FLAG_FORMAT) ? TEXT("[b]") : TEXT(""),
			(flags & VI_FLAG_FORMAT) ? TEXT("[/b]") : TEXT(""));
		GetWeatherStrings(buffer, flags);
	}

	if (flags & VI_FLAG_PRNVAR && !servicemode) {
		buffer.AppendFormat(TEXT("\r\n%sProtocols and Accounts:%s\r\n-------------------------------------------------------------------------------\r\n"),
			(flags & VI_FLAG_FORMAT) ? TEXT("[b]") : TEXT(""),
			(flags & VI_FLAG_FORMAT) ? TEXT("[/b]") : TEXT(""));
		GetProtocolStrings(buffer);
	}

	if (flags & VI_FLAG_PRNVAR) {
		buffer.AppendFormat(TEXT("\r\n%sIcon Packs:%s\r\n-------------------------------------------------------------------------------\r\n"),
			(flags & VI_FLAG_FORMAT) ? TEXT("[b]") : TEXT(""),
			(flags & VI_FLAG_FORMAT) ? TEXT("[/b]") : TEXT(""));
		GetIconStrings(buffer);
	}

	if (flags & VI_FLAG_PRNDLL) {
		__try {
			buffer.Append(TEXT("\r\nLoaded Modules:\r\n-------------------------------------------------------------------------------\r\n"));
			EnumerateLoadedModules64(GetCurrentProcess(), LoadedModules64, &buffer);
		}
		__except (EXCEPTION_EXECUTE_HANDLER) {}
	}
Example #14
0
static void GetWeatherStrings(CMString& buffer, unsigned flags)
{
	TCHAR path[MAX_PATH];
	GetModuleFileName(NULL, path, MAX_PATH);

	LPTSTR fname = _tcsrchr(path, TEXT('\\'));
	if (fname == NULL) fname = path;
	mir_sntprintf(fname, MAX_PATH - (fname - path), TEXT("\\plugins\\weather\\*.ini"));

	WIN32_FIND_DATA FindFileData;
	HANDLE hFind = FindFirstFile(path, &FindFileData);
	if (hFind == INVALID_HANDLE_VALUE) return;

	do {
		if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;

		mir_sntprintf(fname, MAX_PATH - (fname - path), TEXT("\\plugins\\weather\\%s"), FindFileData.cFileName);
		HANDLE hDumpFile = CreateFile(path, GENERIC_READ, FILE_SHARE_READ, NULL,
			OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

		if (hDumpFile != INVALID_HANDLE_VALUE) {
			char buf[8192];

			DWORD bytes = 0;
			ReadFile(hDumpFile, buf, 8190, &bytes, NULL);
			buf[bytes] = 0;

			char* ver = strstr(buf, "Version=");
			if (ver != NULL) {
				char *endid = strchr(ver, '\r');
				if (endid != NULL) *endid = 0;
				else {
					endid = strchr(ver, '\n');
					if (endid != NULL) *endid = 0;
				}
				ver += 8;
			}

			char *id = strstr(buf, "Name=");
			if (id != NULL) {
				char *endid = strchr(id, '\r');
				if (endid != NULL) *endid = 0;
				else {
					endid = strchr(id, '\n');
					if (endid != NULL) *endid = 0;
				}
				id += 5;
			}

			TCHAR timebuf[30] = TEXT("");
			GetLastWriteTime(&FindFileData.ftLastWriteTime, timebuf, 30);


			static const TCHAR format[] = TEXT(" %s v.%s%S%s [%s] - %S\r\n");

			buffer.AppendFormat(format, FindFileData.cFileName,
				(flags & VI_FLAG_FORMAT) ? TEXT("[b]") : TEXT(""),
				ver,
				(flags & VI_FLAG_FORMAT) ? TEXT("[/b]") : TEXT(""),
				timebuf, id);
			CloseHandle(hDumpFile);
		}
	} while (FindNextFile(hFind, &FindFileData));
	FindClose(hFind);
}
Example #15
0
static void GetPluginsString(CMString& buffer, unsigned& flags)
{
	buffer.AppendFormat(TEXT("Service Mode: %s\r\n"), servicemode ? TEXT("Yes") : TEXT("No"));

	TCHAR path[MAX_PATH];
	GetModuleFileName(NULL, path, MAX_PATH);

	LPTSTR fname = _tcsrchr(path, TEXT('\\'));
	if (fname == NULL) fname = path;
	mir_sntprintf(fname, MAX_PATH - (fname - path), TEXT("\\plugins\\*.dll"));

	WIN32_FIND_DATA FindFileData;
	HANDLE hFind = FindFirstFile(path, &FindFileData);
	if (hFind == INVALID_HANDLE_VALUE) return;

	size_t count = 0, ucount = 0;

	CMString ubuffer;
	ListItem* dlllist = NULL;

	static const TCHAR format[] = TEXT("%c %s v.%s%d.%d.%d.%d%s [%s] - %S %s\r\n");

	do {
		bool loaded = false;
		mir_sntprintf(fname, MAX_PATH - (fname - path), TEXT("\\plugins\\%s"), FindFileData.cFileName);
		HMODULE hModule = GetModuleHandle(path);
		if (hModule == NULL && servicemode) {
			hModule = LoadLibrary(path);
			loaded = true;
		}
		if (hModule == NULL) {
			if ((flags & VI_FLAG_PRNVAR) && IsPluginEnabled(FindFileData.cFileName)) {
				TCHAR timebuf[30] = TEXT("");
				GetLastWriteTime(&FindFileData.ftLastWriteTime, timebuf, 30);

				ubuffer.AppendFormat(format, TEXT(' '), FindFileData.cFileName,
					(flags & VI_FLAG_FORMAT) ? TEXT("[b]") : TEXT(""),
					0, 0, 0, 0,
					(flags & VI_FLAG_FORMAT) ? TEXT("[/b]") : TEXT(""),
					timebuf, "<unknown>", TEXT(""));

				GetLinkedModulesInfo(path, ubuffer);
				ubuffer.Append(TEXT("\r\n"));

				++ucount;
			}
			continue;
		}

		PLUGININFOEX* pi = GetMirInfo(hModule);
		if (pi != NULL) {
			TCHAR timebuf[30] = TEXT("");
			GetLastWriteTime(&FindFileData.ftLastWriteTime, timebuf, 30);

			bool ep = (size_t)pi->cbSize > sizeof(PLUGININFOEX);
			const TCHAR *unica = (ep && ((PLUGININFOEX*)pi)->flags & 1) ? TEXT("|Unicode aware|") : TEXT("");

			ListItem* lst = new ListItem;
			int v1, v2, v3, v4;

			DWORD unused, verInfoSize = GetFileVersionInfoSize(path, &unused);
			if (verInfoSize != 0) {
				UINT blockSize;
				VS_FIXEDFILEINFO* fi;
				void* pVerInfo = mir_alloc(verInfoSize);
				GetFileVersionInfo(path, 0, verInfoSize, pVerInfo);
				VerQueryValue(pVerInfo, _T("\\"), (LPVOID*)&fi, &blockSize);
				v1 = HIWORD(fi->dwProductVersionMS), v2 = LOWORD(fi->dwProductVersionMS),
					v3 = HIWORD(fi->dwProductVersionLS), v4 = LOWORD(fi->dwProductVersionLS);
				mir_free(pVerInfo);
			}
			else {
				DWORD ver = pi->version;
				v1 = HIBYTE(HIWORD(ver)), v2 = LOBYTE(HIWORD(ver)), v3 = HIBYTE(LOWORD(ver)), v4 = LOBYTE(LOWORD(ver));
			}

			lst->str.AppendFormat(format, ep ? TEXT('\xa4') : TEXT(' '), FindFileData.cFileName,
				(flags & VI_FLAG_FORMAT) ? TEXT("[b]") : TEXT(""),
				v1, v2, v3, v4,
				(flags & VI_FLAG_FORMAT) ? TEXT("[/b]") : TEXT(""),
				timebuf, pi->shortName ? pi->shortName : "", unica);

			ListItem* lsttmp = dlllist;
			ListItem* lsttmppv = NULL;
			while (lsttmp != NULL) {
				if (lsttmp->str.CompareNoCase(lst->str) > 0)
					break;
				lsttmppv = lsttmp;
				lsttmp = lsttmp->next;
			}
			lst->next = lsttmp;
			if (lsttmppv == NULL)
				dlllist = lst;
			else
				lsttmppv->next = lst;

			if (mir_tstrcmpi(FindFileData.cFileName, TEXT("weather.dll")) == 0)
				flags |= VI_FLAG_WEATHER;

			++count;
		}
		if (loaded) FreeLibrary(hModule);
	} while (FindNextFile(hFind, &FindFileData));
	FindClose(hFind);

	buffer.AppendFormat(TEXT("\r\n%sActive Plugins (%u):%s\r\n"),
		(flags & VI_FLAG_FORMAT) ? TEXT("[b]") : TEXT(""), count, (flags & VI_FLAG_FORMAT) ? TEXT("[/b]") : TEXT(""));

	ListItem* lsttmp = dlllist;
	while (lsttmp != NULL) {
		buffer.Append(lsttmp->str);
		ListItem* lsttmp1 = lsttmp->next;
		delete lsttmp;
		lsttmp = lsttmp1;
	}

	if (ucount) {
		buffer.AppendFormat(TEXT("\r\n%sUnloadable Plugins (%u):%s\r\n"),
			(flags & VI_FLAG_FORMAT) ? TEXT("[b]") : TEXT(""), ucount, (flags & VI_FLAG_FORMAT) ? TEXT("[/b]") : TEXT(""));
		buffer.Append(ubuffer);
	}
}
Example #16
0
int _tmain(int argc, _TCHAR* argv[])
{
	string strSkinPath;	//皮肤路径,相对于程序的.rc文件
	vector<string> vecIdMaps;
	string strRes;		//rc2文件名
	string strHead;		//资源头文件,如winres.h
	string strName2ID;	//名字-ID映射表XML
	char   cYes=0;		//强制改写标志
	
	int c;

	printf("%s\n",GetCommandLineA());
	while ((c = getopt(argc, argv, _T("i:r:h:n:y:p:"))) != EOF)
	{
		switch (c)
		{
		case _T('i'):vecIdMaps.push_back(optarg);break;
		case _T('r'):strRes=optarg;break;
		case _T('h'):strHead=optarg;break;
		case _T('n'):strName2ID=optarg;break;
		case _T('y'):cYes=1;optind--;break;
		case _T('p'):strSkinPath=optarg;break;
		}
	}

	if(vecIdMaps.size()==0 && strName2ID.length()==0)
	{
		printf("error: not specify valid idmap file\n");
		return 3;
	}

	if(strName2ID.length() && vecIdMaps.size())
	{//自动更新name2id表
		TiXmlDocument xmlName2ID;
		xmlName2ID.LoadFile(strName2ID.c_str());
		map<string,int> mapNamedID;
		TiXmlElement *pXmlName2ID=xmlName2ID.FirstChildElement("name2id");
		int nCurID=ID_AUTO_START;
		while(pXmlName2ID)
		{
			string strName=pXmlName2ID->Attribute("name");
			int uID=0;
			pXmlName2ID->Attribute("id",&uID);
			mapNamedID[strName]=uID;

			if(uID>nCurID) nCurID=uID;	//获得当前的最大ID

			pXmlName2ID=pXmlName2ID->NextSiblingElement("name2id");
		}

		int nNewNamedID=0;
		for(vector<string>::iterator it=vecIdMaps.begin();it!=vecIdMaps.end();it++)
		{
			TiXmlDocument xmlDocIdMap;
			xmlDocIdMap.LoadFile(it->c_str());
			TiXmlElement *pXmlIdmap=xmlDocIdMap.FirstChildElement("resid");
			while(pXmlIdmap)
			{
				int layer=0;
				pXmlIdmap->Attribute("layer",&layer);
				if(layer && _stricmp(pXmlIdmap->Attribute("type"),"xml")==0)
				{
					string strXmlLayer=pXmlIdmap->Attribute("file");
					if(!strSkinPath.empty()) strXmlLayer=strSkinPath+"\\"+strXmlLayer;
					if(strXmlLayer.length())
					{//找到一个窗口描述XML
						TiXmlDocument xmlDocLayer;
						xmlDocLayer.LoadFile(strXmlLayer.c_str());
						nNewNamedID+=UpdateName2ID(&mapNamedID,&xmlName2ID,xmlDocLayer.RootElement(),nCurID);
					}
				}
				pXmlIdmap=pXmlIdmap->NextSiblingElement("resid");
			}
		}
		if(nNewNamedID)
		{//有新的命名控件加入,更新Name2ID表
			FILE *f=fopen(strName2ID.c_str(),"w");
			if(f)
			{
				xmlName2ID.Print(f);
				fclose(f);
			}
		}
	}
	__time64_t fs1=0;
	__time64_t fs2=0;
	string strTimeStamp;
	FILE *fts=NULL;

	if(vecIdMaps.size())
	{
		//check modify flag
		strTimeStamp=strRes+".ts";
		FILE *fts=fopen(strTimeStamp.c_str(),"r+b");
		if(fts)
		{
			fread(&fs1,1,sizeof(fs1),fts);
			fclose(fts);
		}

		vector<string>::iterator it=vecIdMaps.begin();
		while(it!=vecIdMaps.end())
		{
			fs2+=GetLastWriteTime(it->c_str());
			it++;
		}

		//build xml id map
		if(fs1==fs2 || vecIdMaps.size()==0)
		{
			if(vecIdMaps.size()) printf("idmap files have not been modified.\n");
		}else
		{
			DWORD dwAttr=GetFileAttributesA(strRes.c_str());
			if(dwAttr & FILE_ATTRIBUTE_READONLY)
			{
				if(!cYes)
				{
					printf("error: resource file is readonly. set -y to make sure to do it.\n");
					return 2;
				}
				SetFileAttributesA(strRes.c_str(),dwAttr&~FILE_ATTRIBUTE_READONLY);
			}

			fts=fopen(strTimeStamp.c_str(),"wb");
			if(fts)
			{//record time stamp
				fwrite(&fs2,1,sizeof(fs2),fts);
				fclose(fts);
			}

			vector<IDMAPRECORD> vecIdMapRecord;
			//load xml description of resource to vector
			vector<string>::iterator it=vecIdMaps.begin();
			while(it!=vecIdMaps.end())
			{
				TiXmlDocument xmlDoc;
				if(xmlDoc.LoadFile(it->c_str()))
				{
					TiXmlElement *xmlEle=xmlDoc.RootElement();
					while(xmlEle)
					{
						if(strcmp(xmlEle->Value(),"resid")==0)
						{
							IDMAPRECORD rec={0};
							const char *pszValue;
							pszValue=xmlEle->Attribute("type");
							if(pszValue) MultiByteToWideChar(CP_UTF8,0,pszValue,-1,rec.szType,100);
							pszValue=xmlEle->Attribute("id");
							if(pszValue) rec.nID=atoi(pszValue);
							pszValue=xmlEle->Attribute("id_name");
							if(pszValue) MultiByteToWideChar(CP_UTF8,0,pszValue,-1,rec.szID,200);
							pszValue=xmlEle->Attribute("file");
							if(pszValue)
							{
								string str;
								if(!strSkinPath.empty()){ str=strSkinPath+"\\"+pszValue;}
								else str=pszValue;
								MultiByteToWideChar(CP_UTF8,0,str.c_str(),str.length(),rec.szPath,MAX_PATH);
							}

							if(rec.szType[0] && rec.nID && rec.szPath[0])
							{
								if(rec.szID[0]==0) swprintf(rec.szID,L"IDC_%s_%d",rec.szType,rec.nID);
								vecIdMapRecord.push_back(rec);
							}
						}
						xmlEle=xmlEle->NextSiblingElement();
					}
				}
				it++;
			}

			//build output string by wide char
			wstring strOut;
			strOut+=RB_HEADER_W;
			strOut+=L"\n";

			vector<IDMAPRECORD>::iterator it2=vecIdMapRecord.begin();
			while(it2!=vecIdMapRecord.end())
			{
				WCHAR szRec[2000];
				wstring strFile=BuildPath(it2->szPath);
				swprintf(szRec,L"DEFINE_%s(%s,\t%d,\t\"%s\")\n",it2->szType,it2->szID,it2->nID,strFile.c_str());
				strOut+=szRec;
				it2++;
			}
			strOut+=RB_TAILOR_W;

			//write output string to target res file
			FILE * f=fopen(strRes.c_str(),"r+b");
			if(f)
			{
				BYTE szFlag[2]={0};
				int nReaded=fread(szFlag,1,2,f);
				if(nReaded==2 && szFlag[0]==0xFF && szFlag[1]==0xFE)//detect utf32
				{
					InsertBlockToFileW(f,strOut);
				}else
				{//multibyte
					int nLen=WideCharToMultiByte(CP_ACP,0,strOut.c_str(),strOut.length(),NULL,0,NULL,NULL);
					char *pBuf=new char[nLen+1];
					WideCharToMultiByte(CP_ACP,0,strOut.c_str(),strOut.length(),pBuf,nLen,NULL,NULL);
					pBuf[nLen]=0;
					fseek(f,0,SEEK_SET);
					InsertBlockToFileA(f,pBuf);
					delete []pBuf;
				}
				fclose(f);
			}

			printf("build resouce successed!\n");
		}

	}

	//build resource head
	if(strName2ID.length())
	{
		fs1=0;
		strTimeStamp=strHead+".ts";
		fts=fopen(strTimeStamp.c_str(),"rb");
		if(fts)
		{
			fread(&fs1,sizeof(__time64_t),1,fts);
			fclose(fts);
		}

		fs2=GetLastWriteTime(strName2ID.c_str());

		if(fs1==fs2 || strName2ID.length()==0)
		{
			if(strName2ID.length()) printf("name2id xml descriptor is not changed!\n");
		}else
		{
			DWORD dwAttr=GetFileAttributesA(strHead.c_str());
			if(dwAttr & FILE_ATTRIBUTE_READONLY)
			{
				if(!cYes)
				{
					printf("error: head file is readonly. set -y to make sure to do it.\n");
					return 2;
				}
				SetFileAttributesA(strHead.c_str(),dwAttr&~FILE_ATTRIBUTE_READONLY);
			}

			fts=fopen(strTimeStamp.c_str(),"wb");
			if(fts)
			{//record time stamp
				fwrite(&fs2,1,sizeof(fs2),fts);
				fclose(fts);
			}

			vector<NAME2IDRECORD> vecName2ID;
			//load xml description of resource to vector
			TiXmlDocument xmlDoc;
			if(xmlDoc.LoadFile(strName2ID.c_str()))
			{
				TiXmlElement *xmlEle=xmlDoc.RootElement();
				while(xmlEle)
				{
					if(strcmp(xmlEle->Value(),"name2id")==0)
					{
						NAME2IDRECORD rec={0};
						const char *pszValue;
						pszValue=xmlEle->Attribute("name");
						if(pszValue) MultiByteToWideChar(CP_UTF8,0,pszValue,-1,rec.szName,100);
						pszValue=xmlEle->Attribute("id");
						if(pszValue) rec.nID=atoi(pszValue);
						pszValue=xmlEle->Attribute("remark");
						if(pszValue) MultiByteToWideChar(CP_UTF8,0,pszValue,-1,rec.szRemark,300);

						if(rec.szName[0] && rec.nID) vecName2ID.push_back(rec);
					}
					xmlEle=xmlEle->NextSiblingElement();
				}
			}

			//build output string by wide char
			wstring strOut;
			strOut+=RB_HEADER_W;
			strOut+=L"\n";

			vector<NAME2IDRECORD>::iterator it2=vecName2ID.begin();
			while(it2!=vecName2ID.end())
			{
				WCHAR szRec[2000];
				if(it2->szRemark[0])
					swprintf(szRec,L"#define\t%s\t\t%d	\t//%s\n",it2->szName,it2->nID,it2->szRemark);
				else
					swprintf(szRec,L"#define\t%s\t\t%d\n",it2->szName,it2->nID);
				strOut+=szRec;
				it2++;
			}
			strOut+=RB_TAILOR_W;

			//write output string to target res file
			FILE * f=fopen(strHead.c_str(),"r+b");
			if(f)
			{
				BYTE szFlag[2]={0};
				int nReaded=fread(szFlag,1,2,f);
				if(nReaded==2 && szFlag[0]==0xFF && szFlag[1]==0xFE)//detect utf32
				{
					InsertBlockToFileW(f,strOut);
				}else
				{//multibyte
					int nLen=WideCharToMultiByte(CP_ACP,0,strOut.c_str(),strOut.length(),NULL,0,NULL,NULL);
					char *pBuf=new char[nLen+1];
					WideCharToMultiByte(CP_ACP,0,strOut.c_str(),strOut.length(),pBuf,nLen,NULL,NULL);
					pBuf[nLen]=0;
					fseek(f,0,SEEK_SET);
					InsertBlockToFileA(f,pBuf);
					delete []pBuf;
				}
				fclose(f);
			}

			printf("build header file successed!\n");
		}
	}

	return 0;
}
Example #17
0
DWORD WINAPI ChangeNotifyThread(NOTIFY_DATA *pnd)
{
	HANDLE hChange;
	DWORD  dwResult;
	TCHAR  szDirectory[MAX_PATH];

	//FILE_NOTIFY_INFORMATION notifyinfo;
	//HANDLE hDirectory;

	//OVERLAPPED overlapped = { 0 };

	//hChange = CreateEvent(0, FALSE, FALSE, 0);
	//overlapped.hEvent = hChange;


	lstrcpy(szDirectory, pnd->szFile);

	// get the directory name from filename
	if(GetFileAttributes(szDirectory) != FILE_ATTRIBUTE_DIRECTORY)
	{
		TCHAR *slash = _tcsrchr(szDirectory, _T('\\'));
		if(slash) *slash = '\0';
	}

	//hDirectory = CreateFile(szDirectory, FILE_LIST_DIRECTORY, FILE_SHARE_READ|FILE_SHARE_DELETE,
	//	NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OVERLAPPED , NULL);

	//ReadDirectoryChangesW(hDirectory, &notifyinfo, sizeof(notifyinfo), FALSE, FILE_NOTIFY_CHANGE_LAST_WRITE, 0, &overlapped, 0);
	
	// watch the specified directory for changes
	hChange = FindFirstChangeNotification(szDirectory, FALSE, FILE_NOTIFY_CHANGE_LAST_WRITE);

	do
	{
		HANDLE hEventList[2] = { hChange, pnd->hQuitEvent };
		
		if((dwResult = WaitForMultipleObjects(1, hEventList, FALSE, INFINITE)) == WAIT_OBJECT_0)
		{
			NMFILECHANGE nmfc = { { pnd->hwndNotify, 0, FCN_FILECHANGE }, pnd->szFile };
			FILETIME wt;
			ULONG64 n1, n2;
			//PostMessage(pnd->hwndNotify, WM_NOTIFY, 0, (LPARAM)pnd);

			GetLastWriteTime(pnd->szFile, &wt);

			//GetSystemTimeAsFileTime(&ft);


			n1 = (((ULONG64)wt.dwHighDateTime) << 32) + wt.dwLowDateTime;
			n2 = (((ULONG64)pnd->lastChange.dwHighDateTime) << 32) + pnd->lastChange.dwLowDateTime;

			TRACEA("%I64x %I64x (%d)\n", n1, n2, GetCurrentThreadId());

			//if(*(ULONG64 *)&ft > *(ULONG64 *)&pnd->lastChange + (10000000 * 5))
			if(n1 > n2 + (10000000 * 3))
			{
				PostMessage(pnd->hwndNotify, WM_NOTIFY, 0, (LPARAM)&nmfc);
			}

			pnd->lastChange = wt;
		}

		FindNextChangeNotification(hChange);
	} 
	while(dwResult == WAIT_OBJECT_0);

	// cleanup
	FindCloseChangeNotification(hChange);
	free(pnd);

	return 0;
}
Example #18
0
int ThumbCacheUpdate() {
	TCHEADER tch;
	int status = 0;
	time_t dirlastmod;
	FILE *tc;

	if (verbose)
		printf(" - Updating thumb cache\n");

	tc = fopen(thumb_cache_fn, "rb+");
	if (!tc) {
		if (errno == ENOENT) {
			tc = fopen(thumb_cache_fn, "wb+");
			if (!tc) {
				perror("fopen wb+");
				return 0;
			}

			tch.signature  = 'TMBC';
			tch.lastupdate = 0;
			fwrite(&tch, sizeof(TCHEADER), 1, tc);
			
			tc = freopen(thumb_cache_fn, "rb+", tc);
			if (!tc) {
				perror("freopen rb+");
				return 0;
			}
		} else {
			perror("fopen rb+");
			return 0;
		}
	}

	fread(&tch, sizeof(TCHEADER), 1, tc);

	if (tch.signature != 'TMBC') {
		fprintf(stderr, "ERROR: thumbcache signature does not match\n");
		goto done;
	}
	
	dirlastmod = GetLastWriteTime(".");
	if (tch.lastupdate >= dirlastmod) {
		if (tch.lastupdate > dirlastmod) {
			fprintf(stderr, "WARNING: thumbcache recorded last "
				"mtime > directory last mtime\n");
		}
		if (verbose)
			printf("Cache is up-to-date.\n");
		
		status = 1;
		goto done;
	}
	
	_ThumbCacheBuildHt(tc);

	if (fseek(tc, sizeof(TCHEADER) - sizeof(time_t), SEEK_SET) == -1) {
		perror("fseek");
		goto done;
	}
	fwrite(&dirlastmod, sizeof(time_t), 1, tc);

	_ThumbCacheUpdateDirScan(tc, "");

	printf("Added %d entries successfully.\n", nadded);

	status = 1;
done:
	if (tc)
		fclose(tc);
	return status;
}
Example #19
0
//Our main loop which should continue running as long as we don't quite the game
static void MainLoop()
{
	char DLLFilePath[MAX_PATH];
	char *onePastLastSlash;

	DWORD pathSize = GetModuleFileNameA(NULL, DLLFilePath, sizeof(DLLFilePath));
	onePastLastSlash = DLLFilePath;

	for (char *scan = DLLFilePath; *scan; scan++)
	{
		if (*scan == '\\')
		{
			onePastLastSlash = scan + 1;
		}
	}
	char DLLFullPath[MAX_PATH];
	BuildFileFullPath(&state, "playground game.dll", DLLFullPath, sizeof(DLLFullPath));

	char tempDLLFullPath[MAX_PATH];
	BuildFileFullPath(&state, "playground game_temp.dll", tempDLLFullPath, sizeof(tempDLLFullPath));

	char PDBFullPath[MAX_PATH];
	BuildFileFullPath(&state, "playground game.pdb", PDBFullPath, sizeof(PDBFullPath));

	char tempPDBFullPath[MAX_PATH];
	BuildFileFullPath(&state, "playground game_temp.pdb", tempPDBFullPath, sizeof(tempPDBFullPath));

	Input = {};
	Input.UP.Button = VK_UP;
	Input.DOWN.Button = VK_DOWN;
	Input.RIGHT.Button = VK_RIGHT;
	Input.LEFT.Button = VK_LEFT;

	LARGE_INTEGER performanceFrequency;
	QueryPerformanceFrequency(&performanceFrequency);
	TicksPerSecond = performanceFrequency.QuadPart;

	int monitorRefreshHZ = 60;
	HDC deviceContext = GetDC(Window.Window);
	int refreshHz = GetDeviceCaps(deviceContext, VREFRESH);
	ReleaseDC(Window.Window, deviceContext);

	if (refreshHz > 1)
	{
		monitorRefreshHZ = refreshHz;
	}

	float gameUpdateHZ = (float)(monitorRefreshHZ);
	float targetSecondsPerFrame = 1.0f / gameUpdateHZ;

	UINT desiredSchedulerTime = 1;
	bool sleepIsSmaller = true;//timeBeginPeriod(desiredSchedulerTime) == TIMERR_NOERROR;

	LARGE_INTEGER lastTick = GetTicks();
	float updateTime = 0;
	int updates = 0;
	double frames = 0;
	double frameTime = 0;

	while (IsRunning)
	{
		/*
		start_loop = clock();
		*/

		FILETIME newWriteTimeDLL = GetLastWriteTime(DLLFullPath);
		FILETIME newWriteTimePDB = GetLastWriteTime(PDBFullPath);
		
		if (CompareFileTime(&newWriteTimeDLL, &Game.LastWriteTimeDLL) != 0 && CompareFileTime(&newWriteTimeDLL, &Game.LastWriteTimePDB) != 0)
		{
			UnloadGameCode(&Game);
			CopyFile(PDBFullPath, tempPDBFullPath, FALSE);
			Game = LoadGameCode(DLLFullPath, tempDLLFullPath);
			Game.Game_Init(Dimensions);
		}

		LARGE_INTEGER gameTimerStart = GetTicks();
		ProcessPendingMessages(&Keys);

		ProcessInput(&Input);

		//Update everything
		//Update the game
		Game.Game_Update(&Input);

		/*NOTE(kai): TEST ONLY*/
		//Testing if A button is pressed
		if (IsKeyDown(&Keys, 'A'))
		{
			OutputDebugString("Key: a is pressed\n");
		}
		//Testing if A button is released
		if (IsKeyUp(&Keys, 'A'))
		{
			OutputDebugString("Key: a is released\n");
		}		

		//Render everything
		//Clear the window
		ClearWindow();
		//Render the game
		Game.Game_Render();
		LARGE_INTEGER gameTimerEnd = GetTicks();
		frameTime += (double)(1000.0f * GetSecondsElapsed(gameTimerStart, gameTimerEnd));
		frames++;
		//frames += 1000.0f / (double)(1000.0f * GetSecondsElapsed(gameTimerStart, gameTimerEnd));
		//PrintTimeElapsed(lastTick, gameTimerEnd);

		float secondsElapsedForFrame = GetSecondsElapsed(lastTick, GetTicks());

		if (secondsElapsedForFrame < targetSecondsPerFrame)
		{
			if (sleepIsSmaller)
			{
				DWORD sleepTime = (DWORD)(1000.0f * (targetSecondsPerFrame - secondsElapsedForFrame));

				if (sleepTime > 0)
				{
					Sleep(sleepTime);
				}
			}

			while (secondsElapsedForFrame < targetSecondsPerFrame)
			{
				secondsElapsedForFrame = GetSecondsElapsed(lastTick, GetTicks());
			}
			updates++;
		}

		updateTime += GetSecondsElapsed(lastTick, GetTicks());

		if (updateTime >= 1.0f)
		{
			double avgFPS = 1000.0f / ((frameTime) / frames);
			std::cout << "UPS: " << updates << ", average FPS: " << avgFPS << ", average work/frame: " << (frameTime) / frames << "\n";
			
			frames = 0;
			frameTime = 0;
			updates = 0;
			updateTime = 0;
		}
		
		LARGE_INTEGER endTick = GetTicks();
		//PrintTimeElapsed(lastTick, endTick);
		lastTick = endTick;
		
		//Render the window
		RenderWindow(Window.Window);

		/*
		//calc fps 
		calcfps();
		static int framecount = 0;
		framecount++;
		if (framecount == 10) {
			framecount = 0;
			std::cout << "frame per second is : " << (fps) << std::endl;

		}
		//QueryPerformanceCounter(&t_current_loop);
		end_loop = clock();

		//float frameticks = (t_current_loop.QuadPart - t_previous_loop.QuadPart) / ((frequency_loop.QuadPart) / 1000.0);

		float frameticks = ((float)(end_loop - start_loop) / CLOCKS_PER_SEC) * 1000.0f;

		//print the current fps 

		// std::cout << 1000/frameticks << std::endl;

		if (1000.0f / max_fps > frameticks){

			Sleep(1000.0f / max_fps - frameticks);
		}
		*/

	}

	//Release resources (if there is any) and destory  the window
	Release();

}