Exemplo n.º 1
0
bool FolderTree::EnumNetwork(HTREEITEM hParent)
{
	//What will be the return value from this function
	bool bGotChildren = false;

	//Check if the item already has a network resource and use it.
	FolderTreeItemInfo* pItem = (FolderTreeItemInfo*) GetItemData(hParent);
	
	NETRESOURCE* pNetResource = pItem->m_pNetResource;

	//Setup for the network enumeration
	HANDLE hEnum;
	DWORD dwResult = WNetOpenEnum(pNetResource ? RESOURCE_GLOBALNET : RESOURCE_CONTEXT, m_dwNetworkItemTypes,
      											0, pNetResource ? pNetResource : NULL, &hEnum);

	//Was the read sucessful
	if (dwResult != NO_ERROR)
	{
		//TRACE(_T("Cannot enumerate network drives, Error:%d\n"), dwResult);
		return FALSE;
	}

	//Do the network enumeration
	DWORD cbBuffer = 16384;

	bool bNeedMoreMemory = true;
	bool bSuccess = false;
	LPNETRESOURCE lpnrDrv = NULL;
	DWORD cEntries = 0;
	while (bNeedMoreMemory && !bSuccess)
	{
		//Allocate the memory and enumerate
  		lpnrDrv = (LPNETRESOURCE) new BYTE[cbBuffer];
		cEntries = 0xFFFFFFFF;
		dwResult = WNetEnumResource(hEnum, &cEntries, lpnrDrv, &cbBuffer);

		if (dwResult == ERROR_MORE_DATA)
		{
			//Free up the heap memory we have used
			delete [] lpnrDrv;

			cbBuffer *= 2;
		}
		else if (dwResult == NO_ERROR)
			bSuccess = true;
		else
			bNeedMoreMemory = false;
	}

	//Enumeration successful?
	if (bSuccess)
	{
		//Scan through the results
		for (DWORD i=0; i<cEntries; i++)
		{
			tstring sNameRemote;
			if(lpnrDrv[i].lpRemoteName != NULL)
				sNameRemote = lpnrDrv[i].lpRemoteName;
			else
				sNameRemote = lpnrDrv[i].lpComment;

			//Remove leading back slashes
			if (sNameRemote.size() > 0 && sNameRemote[0] == _T('\\'))
				sNameRemote = sNameRemote.substr(1);
			if (sNameRemote.size() > 0 && sNameRemote[0] == _T('\\'))
				sNameRemote = sNameRemote.substr(1);

			//Setup the item data for the new item
			pItem = new FolderTreeItemInfo;
			pItem->m_pNetResource = new NETRESOURCE;
			memzero(pItem->m_pNetResource, sizeof(NETRESOURCE));
			*pItem->m_pNetResource = lpnrDrv[i];
			
			if (lpnrDrv[i].lpLocalName)
				pItem->m_pNetResource->lpLocalName	= _tcsdup(lpnrDrv[i].lpLocalName);
			if (lpnrDrv[i].lpRemoteName)
				pItem->m_pNetResource->lpRemoteName = _tcsdup(lpnrDrv[i].lpRemoteName);
			if (lpnrDrv[i].lpComment)
				pItem->m_pNetResource->lpComment	= _tcsdup(lpnrDrv[i].lpComment);
			if (lpnrDrv[i].lpProvider)
				pItem->m_pNetResource->lpProvider	= _tcsdup(lpnrDrv[i].lpProvider);
			if (lpnrDrv[i].lpRemoteName)
				pItem->m_sFQPath = lpnrDrv[i].lpRemoteName;
			else
				pItem->m_sFQPath = sNameRemote;
			
			pItem->m_sRelativePath = sNameRemote;
			pItem->m_bNetworkNode = true;

			//Display a share and the appropiate icon
			if (lpnrDrv[i].dwDisplayType == RESOURCEDISPLAYTYPE_SHARE)
			{
				//Display only the share name
				int nPos = pItem->m_sRelativePath.find(_T('\\'));
				if (nPos >= 0)
					pItem->m_sRelativePath = pItem->m_sRelativePath.substr(nPos+1);

				//Now add the item into the control
				InsertFileItem(hParent, pItem, m_bShowSharedUsingDifferentIcon, GetIconIndex(pItem->m_sFQPath), GetSelIconIndex(pItem->m_sFQPath), false);
			}
			else if (lpnrDrv[i].dwDisplayType == RESOURCEDISPLAYTYPE_SERVER)
			{
				//Now add the item into the control
				tstring sServer = _T("\\\\");
				sServer += pItem->m_sRelativePath;
				InsertFileItem(hParent, pItem, false, GetIconIndex(sServer), GetSelIconIndex(sServer), false);
			}
			else
			{
				//Now add the item into the control
				//Just use the generic Network Neighborhood icons for everything else
				LPITEMIDLIST lpNNPidl;
				int nIcon = 0xFFFF;
				int nSelIcon = nIcon;
				if (SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_NETWORK, &lpNNPidl)))
				{
					nIcon = GetIconIndex(lpNNPidl);
					nSelIcon = GetSelIconIndex(lpNNPidl);

					//Free up the pidl now that we are finished with it
					//ASSERT(m_pMalloc);
					m_pMalloc->Free(lpNNPidl);
					m_pMalloc->Release();
				}

				InsertFileItem(hParent, pItem, false, nIcon, nSelIcon, false);
			}
			bGotChildren = true;
		}
	}
/*	else
		TRACE(_T("Cannot complete network drive enumeration, Error:%d\n"), dwResult);
*/
	//Clean up the enumeration handle
	WNetCloseEnum(hEnum);

	//Free up the heap memory we have used
	delete [] lpnrDrv;

	//Return whether or not we added any items
	return bGotChildren;
}
Exemplo n.º 2
0
BOOL CTortoiseProcApp::InitInstance()
{
	CheckUpgrade();
	CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
	CMFCButton::EnableWindowsTheming();

	Gdiplus::GdiplusStartupInput gdiplusStartupInput;
	Gdiplus::GdiplusStartup(&m_gdiplusToken,&gdiplusStartupInput,NULL);

	//set the resource dll for the required language
	CRegDWORD loc = CRegDWORD(_T("Software\\TortoiseGit\\LanguageID"), 1033);
	long langId = loc;
	{
		CString langStr;
		langStr.Format(_T("%ld"), langId);
		CCrashReport::Instance().AddUserInfoToReport(L"LanguageID", langStr);
	}
	CString langDll;
	CStringA langpath = CStringA(CPathUtils::GetAppParentDirectory());
	langpath += "Languages";
	HINSTANCE hInst = NULL;
	do
	{
		langDll.Format(_T("%sLanguages\\TortoiseProc%ld.dll"), (LPCTSTR)CPathUtils::GetAppParentDirectory(), langId);

		hInst = LoadLibrary(langDll);

		CString sVer = _T(STRPRODUCTVER);
		CString sFileVer = CPathUtils::GetVersionFromFile(langDll);
		if (sFileVer.Compare(sVer)!=0)
		{
			FreeLibrary(hInst);
			hInst = NULL;
		}
		if (hInst != NULL)
		{
			AfxSetResourceHandle(hInst);
		}
		else
		{
			DWORD lid = SUBLANGID(langId);
			lid--;
			if (lid > 0)
			{
				langId = MAKELANGID(PRIMARYLANGID(langId), lid);
			}
			else
				langId = 0;
		}
	} while ((hInst == NULL) && (langId != 0));
	TCHAR buf[6];
	_tcscpy_s(buf, _T("en"));
	langId = loc;
	// MFC uses a help file with the same name as the application by default,
	// which means we have to change that default to our language specific help files
	CString sHelppath = CPathUtils::GetAppDirectory() + _T("TortoiseGit_en.chm");
	free((void*)m_pszHelpFilePath);
	m_pszHelpFilePath=_tcsdup(sHelppath);
	sHelppath = CPathUtils::GetAppParentDirectory() + _T("Languages\\TortoiseGit_en.chm");
	do
	{
		CString sLang = _T("_");
		if (GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf)))
		{
			sLang += buf;
			sHelppath.Replace(_T("_en"), sLang);
			if (PathFileExists(sHelppath))
			{
				free((void*)m_pszHelpFilePath);
				m_pszHelpFilePath=_tcsdup(sHelppath);
				break;
			}
		}
		sHelppath.Replace(sLang, _T("_en"));
		if (GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf)))
		{
			sLang += _T("_");
			sLang += buf;
			sHelppath.Replace(_T("_en"), sLang);
			if (PathFileExists(sHelppath))
			{
				free((void*)m_pszHelpFilePath);
				m_pszHelpFilePath=_tcsdup(sHelppath);
				break;
			}
		}
		sHelppath.Replace(sLang, _T("_en"));

		DWORD lid = SUBLANGID(langId);
		lid--;
		if (lid > 0)
		{
			langId = MAKELANGID(PRIMARYLANGID(langId), lid);
		}
		else
			langId = 0;
	} while (langId);
	setlocale(LC_ALL, "");

	if (!g_Git.CheckMsysGitDir())
	{
		UINT ret = CMessageBox::Show(NULL, IDS_PROC_NOMSYSGIT, IDS_APPNAME, 3, IDI_HAND, IDS_PROC_SETMSYSGITPATH, IDS_PROC_GOTOMSYSGITWEBSITE, IDS_ABORTBUTTON);
		if(ret == 2)
		{
			ShellExecute(NULL, NULL, _T("http://code.google.com/p/msysgit/"), NULL, NULL, SW_SHOW);
		}
		else if(ret == 1)
		{
			// open settings dialog
			CSinglePropSheetDlg(CString(MAKEINTRESOURCE(IDS_PROC_SETTINGS_TITLE)), new CSetMainPage(), this->GetMainWnd()).DoModal();
		}
		return FALSE;
	}
	if (CAppUtils::GetMsysgitVersion() < 0x01070a00)
	{
		int ret = CMessageBox::ShowCheck(NULL, IDS_PROC_OLDMSYSGIT, IDS_APPNAME, 1, IDI_EXCLAMATION, IDS_PROC_GOTOMSYSGITWEBSITE, IDS_ABORTBUTTON, IDS_IGNOREBUTTON, _T("OldMsysgitVersionWarning"), IDS_PROC_NOTSHOWAGAINIGNORE);
		if (ret == 1)
		{
			CMessageBox::RemoveRegistryKey(_T("OldMsysgitVersionWarning")); // only store answer if it is "Ignore"
			ShellExecute(NULL, NULL, _T("http://code.google.com/p/msysgit/"), NULL, NULL, SW_SHOW);
			return FALSE;
		}
		else if (ret == 2)
		{
			CMessageBox::RemoveRegistryKey(_T("OldMsysgitVersionWarning")); // only store answer if it is "Ignore"
			return FALSE;
		}
	}

	{
		CCrashReport::Instance().AddUserInfoToReport(L"msysGitDir", CGit::ms_LastMsysGitDir);
		CString versionString;
		versionString.Format(_T("%d"), CGit::ms_LastMsysGitVersion);
		CCrashReport::Instance().AddUserInfoToReport(L"msysGitVersion", versionString);
	}

	// InitCommonControls() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.

	INITCOMMONCONTROLSEX used = {
		sizeof(INITCOMMONCONTROLSEX),
			ICC_ANIMATE_CLASS | ICC_BAR_CLASSES | ICC_COOL_CLASSES | ICC_DATE_CLASSES |
			ICC_HOTKEY_CLASS | ICC_INTERNET_CLASSES | ICC_LISTVIEW_CLASSES |
			ICC_NATIVEFNTCTL_CLASS | ICC_PAGESCROLLER_CLASS | ICC_PROGRESS_CLASS |
			ICC_TAB_CLASSES | ICC_TREEVIEW_CLASSES | ICC_UPDOWN_CLASS |
			ICC_USEREX_CLASSES | ICC_WIN95_CLASSES
	};
	InitCommonControlsEx(&used);
	AfxOleInit();
	AfxEnableControlContainer();
	AfxInitRichEdit2();
	CWinAppEx::InitInstance();
	SetRegistryKey(_T("TortoiseGit"));
	AfxGetApp()->m_pszProfileName = _tcsdup(_T("TortoiseProc")); // w/o this ResizableLib will store data under TortoiseGitProc which is not compatible with older versions

	CCmdLineParser parser(AfxGetApp()->m_lpCmdLine);

	hWndExplorer = NULL;
	CString sVal = parser.GetVal(_T("hwnd"));
	if (!sVal.IsEmpty())
		hWndExplorer = (HWND)_ttoi64(sVal);

	while (GetParent(hWndExplorer)!=NULL)
		hWndExplorer = GetParent(hWndExplorer);
	if (!IsWindow(hWndExplorer))
	{
		hWndExplorer = NULL;
	}

	// if HKCU\Software\TortoiseGit\Debug is not 0, show our command line
	// in a message box
	if (CRegDWORD(_T("Software\\TortoiseGit\\Debug"), FALSE)==TRUE)
		AfxMessageBox(AfxGetApp()->m_lpCmdLine, MB_OK | MB_ICONINFORMATION);

	if (parser.HasKey(_T("urlhandler")))
	{
		CString url = parser.GetVal(_T("urlhandler"));
		if (url.Find(_T("tgit://clone/")) == 0)
		{
			url = url.Mid(13); // 21 = "tgit://clone/".GetLength()
		}
		else if (url.Find(_T("github-windows://openRepo/")) == 0)
		{
			url = url.Mid(26); // 26 = "github-windows://openRepo/".GetLength()
			int questioMark = url.Find('?');
			if (questioMark > 0)
				url = url.Left(questioMark);
		}
		else if (url.Find(_T("smartgit://cloneRepo/")) == 0)
		{
			url = url.Mid(21); // 21 = "smartgit://cloneRepo/".GetLength()
		}
		else
		{
			CMessageBox::Show(NULL, IDS_ERR_INVALIDPATH, IDS_APPNAME, MB_ICONERROR);
			return FALSE;
		}
		CString newCmd;
		newCmd.Format(_T("/command:clone /url:\"%s\" /hasurlhandler"), url);
		parser = CCmdLineParser(newCmd);
	}

	if ( parser.HasKey(_T("path")) && parser.HasKey(_T("pathfile")))
	{
		CMessageBox::Show(NULL, IDS_ERR_INVALIDPATH, IDS_APPNAME, MB_ICONERROR);
		return FALSE;
	}

	CTGitPath cmdLinePath;
	CTGitPathList pathList;
	if (g_sGroupingUUID.IsEmpty())
		g_sGroupingUUID = parser.GetVal(L"groupuuid");
	if ( parser.HasKey(_T("pathfile")) )
	{

		CString sPathfileArgument = CPathUtils::GetLongPathname(parser.GetVal(_T("pathfile")));

		cmdLinePath.SetFromUnknown(sPathfileArgument);
		if (pathList.LoadFromFile(cmdLinePath)==false)
			return FALSE;		// no path specified!
		if ( parser.HasKey(_T("deletepathfile")) )
		{
			// We can delete the temporary path file, now that we've loaded it
			::DeleteFile(cmdLinePath.GetWinPath());
		}
		// This was a path to a temporary file - it's got no meaning now, and
		// anybody who uses it again is in for a problem...
		cmdLinePath.Reset();

	}
	else
	{

		CString sPathArgument = CPathUtils::GetLongPathname(parser.GetVal(_T("path")));
		if (parser.HasKey(_T("expaths")))
		{
			// an /expaths param means we're started via the buttons in our Win7 library
			// and that means the value of /expaths is the current directory, and
			// the selected paths are then added as additional parameters but without a key, only a value

			// because of the "strange treatment of quotation marks and backslashes by CommandLineToArgvW"
			// we have to escape the backslashes first. Since we're only dealing with paths here, that's
			// a save bet.
			// Without this, a command line like:
			// /command:commit /expaths:"D:\" "D:\Utils"
			// would fail because the "D:\" is treated as the backslash being the escape char for the quotation
			// mark and we'd end up with:
			// argv[1] = /command:commit
			// argv[2] = /expaths:D:" D:\Utils
			// See here for more details: http://blogs.msdn.com/b/oldnewthing/archive/2010/09/17/10063629.aspx
			CString cmdLine = GetCommandLineW();
			cmdLine.Replace(L"\\", L"\\\\");
			int nArgs = 0;
			LPWSTR *szArglist = CommandLineToArgvW(cmdLine, &nArgs);
			if (szArglist)
			{
				// argument 0 is the process path, so start with 1
				for (int i = 1; i < nArgs; ++i)
				{
					if (szArglist[i][0] != '/')
					{
						if (!sPathArgument.IsEmpty())
							sPathArgument += '*';
						sPathArgument += szArglist[i];
					}
				}
				sPathArgument.Replace(L"\\\\", L"\\");
			}
			LocalFree(szArglist);
		}
		if (sPathArgument.IsEmpty() && parser.HasKey(L"path"))
		{
			CMessageBox::Show(hWndExplorer, IDS_ERR_INVALIDPATH, IDS_APPNAME, MB_ICONERROR);
			return FALSE;
		}
		int asterisk = sPathArgument.Find('*');
		cmdLinePath.SetFromUnknown(asterisk >= 0 ? sPathArgument.Left(asterisk) : sPathArgument);
		pathList.LoadFromAsteriskSeparatedString(sPathArgument);
	}

	if (pathList.GetCount() == 0) {
		pathList.AddPath(CTGitPath::CTGitPath(g_Git.m_CurrentDir));
	}

	// Subversion sometimes writes temp files to the current directory!
	// Since TSVN doesn't need a specific CWD anyway, we just set it
	// to the users temp folder: that way, Subversion is guaranteed to
	// have write access to the CWD
	{
		DWORD len = GetCurrentDirectory(0, NULL);
		if (len)
		{
			std::unique_ptr<TCHAR[]> originalCurrentDirectory(new TCHAR[len]);
			if (GetCurrentDirectory(len, originalCurrentDirectory.get()))
			{
				sOrigCWD = originalCurrentDirectory.get();
				sOrigCWD = CPathUtils::GetLongPathname(sOrigCWD);
			}
		}
		TCHAR pathbuf[MAX_PATH];
		GetTortoiseGitTempPath(MAX_PATH, pathbuf);
		SetCurrentDirectory(pathbuf);
	}

	CheckForNewerVersion();

	CAutoGeneralHandle TGitMutex = ::CreateMutex(NULL, FALSE, _T("TortoiseGitProc.exe"));
	if (!g_Git.SetCurrentDir(cmdLinePath.GetWinPathString(), parser.HasKey(_T("submodule")) == TRUE))
	{
		for (int i = 0; i < pathList.GetCount(); ++i)
			if(g_Git.SetCurrentDir(pathList[i].GetWinPath()))
				break;
	}

	if(!g_Git.m_CurrentDir.IsEmpty())
	{
		sOrigCWD = g_Git.m_CurrentDir;
		SetCurrentDirectory(g_Git.m_CurrentDir);
	}

	if (g_sGroupingUUID.IsEmpty())
	{
		CRegStdDWORD groupSetting = CRegStdDWORD(_T("Software\\TortoiseGit\\GroupTaskbarIconsPerRepo"), 3);
		switch (DWORD(groupSetting))
		{
		case 1:
		case 2:
			// implemented differently to TortoiseSVN atm
			break;
		case 3:
		case 4:
			{
				CString wcroot;
				if (g_GitAdminDir.HasAdminDir(g_Git.m_CurrentDir, true, &wcroot))
				{
					git_oid oid;
					CStringA wcRootA(wcroot + CPathUtils::GetAppDirectory());
					if (!git_odb_hash(&oid, wcRootA.GetBuffer(), wcRootA.GetLength(), GIT_OBJ_BLOB))
					{
						CStringA hash;
						git_oid_tostr(hash.GetBufferSetLength(GIT_OID_HEXSZ + 1), GIT_OID_HEXSZ + 1, &oid);
						hash.ReleaseBuffer();
						g_sGroupingUUID = hash;
					}
					ProjectProperties pp;
					pp.ReadProps();
					CString icon = pp.sIcon;
					icon.Replace('/', '\\');
					if (icon.IsEmpty())
						g_bGroupingRemoveIcon = true;
					g_sGroupingIcon = icon;
				}
			}
		}
	}

	CString sAppID = GetTaskIDPerUUID(g_sGroupingUUID).c_str();
	InitializeJumpList(sAppID);
	EnsureGitLibrary(false);

	{
		CString err;
		try
		{
			// requires CWD to be set
			CGit::m_LogEncode = CAppUtils::GetLogOutputEncode();

			// make sure all config files are read in order to check that none contains an error
			g_Git.GetConfigValue(_T("doesnot.exist"));
		}
		catch (char* msg)
		{
			err = CString(msg);
		}

		if (!err.IsEmpty())
		{
			UINT choice = CMessageBox::Show(hWndExplorer, err, _T("TortoiseGit"), 1, IDI_ERROR, CString(MAKEINTRESOURCE(IDS_PROC_EDITLOCALGITCONFIG)), CString(MAKEINTRESOURCE(IDS_PROC_EDITGLOBALGITCONFIG)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON)));
			if (choice == 1)
			{
				// open the config file with alternative editor
				CAppUtils::LaunchAlternativeEditor(g_Git.GetGitLocalConfig());
			}
			else if (choice == 2)
			{
				// open the global config file with alternative editor
				CAppUtils::LaunchAlternativeEditor(g_Git.GetGitGlobalConfig());
			}
			return FALSE;
		}
	}

	// execute the requested command
	CommandServer server;
	Command * cmd = server.GetCommand(parser.GetVal(_T("command")));
	if (cmd)
	{
		cmd->SetExplorerHwnd(hWndExplorer);

		cmd->SetParser(parser);
		cmd->SetPaths(pathList, cmdLinePath);

		retSuccess = cmd->Execute();
		delete cmd;
	}

	// Look for temporary files left around by TortoiseSVN and
	// remove them. But only delete 'old' files because some
	// apps might still be needing the recent ones.
	{
		DWORD len = GetTortoiseGitTempPath(0, NULL);
		std::unique_ptr<TCHAR[]> path(new TCHAR[len + 100]);
		len = GetTortoiseGitTempPath (len + 100, path.get());
		if (len != 0)
		{
			CDirFileEnum finder(path.get());
			FILETIME systime_;
			::GetSystemTimeAsFileTime(&systime_);
			__int64 systime = (((_int64)systime_.dwHighDateTime)<<32) | ((__int64)systime_.dwLowDateTime);
			bool isDir;
			CString filepath;
			while (finder.NextFile(filepath, &isDir))
			{
				HANDLE hFile = ::CreateFile(filepath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, isDir ? FILE_FLAG_BACKUP_SEMANTICS : NULL, NULL);
				if (hFile != INVALID_HANDLE_VALUE)
				{
					FILETIME createtime_;
					if (::GetFileTime(hFile, &createtime_, NULL, NULL))
					{
						::CloseHandle(hFile);
						__int64 createtime = (((_int64)createtime_.dwHighDateTime)<<32) | ((__int64)createtime_.dwLowDateTime);
						if ((createtime + 864000000000) < systime)		//only delete files older than a day
						{
							::SetFileAttributes(filepath, FILE_ATTRIBUTE_NORMAL);
							if (isDir)
								::RemoveDirectory(filepath);
							else
								::DeleteFile(filepath);
						}
					}
					else
						::CloseHandle(hFile);
				}
			}
		}
	}

	// Since the dialog has been closed, return FALSE so that we exit the
	// application, rather than start the application's message pump.
	return FALSE;
}
Exemplo n.º 3
0
void *xemuexec_run ( char *const args[] )
{
	char cmdline[1024];
	int cmdlinesize = sizeof cmdline;
	struct ugly_windows_ps_t *st = malloc(sizeof(struct ugly_windows_ps_t));
	if (!st)
		FATAL("exec: cannot allocate memory");
	ZeroMemory(st, sizeof(struct ugly_windows_ps_t));
	st->si.cb = sizeof(STARTUPINFO);
	st->cmdline = NULL;
	if (snprintf(cmdline, cmdlinesize,"\"%s\"", args[0]) != strlen(args[0]) + 2)
		FATAL("exec: too long commandline");
	cmdlinesize -= strlen(args[0]) + 2;
	while (*(++args)) {
		int arg_padding_len = strchr(*args, ' ') ? 3 : 1;
		if (cmdlinesize <= 0)
			FATAL("exec: too long commandline");
		if (snprintf(cmdline + strlen(cmdline), cmdlinesize, arg_padding_len == 1 ? " %s" : " \"%s\"", *args) != strlen(*args) + arg_padding_len)
			FATAL("exec: too long commandline");
		cmdlinesize -= strlen(*args) + arg_padding_len;
	}
	st->cmdline = _tcsdup(TEXT(cmdline));	// really no idea about this windows madness, just copying examples ...
	if (!st->cmdline) {
		free(st);
		FATAL("exec: cannot allocate memory");
	}
	// TODO: figure out what I should have for std handles to do and inheritance for the "child" process
#if 0
	//st->si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
	st->si.hStdError = (HANDLE)_open_osfhandle(_fileno(stderr), _O_TEXT);
	st->si.hStdOutput = (HANDLE)_open_osfhandle(_fileno(stdout), _O_TEXT);
		//_open_osfhandle((INT_PTR)_fileno(stdout), _O_TEXT);	
		//GetStdHandle(STD_OUTPUT_HANDLE);
	//st->si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
	st->si.hStdInput = (HANDLE)_get_osfhandle(fileno(stdin));
	//st->si.dwFlags |= STARTF_USESTDHANDLES;
	SetHandleInformation(st->si.hStdError, HANDLE_FLAG_INHERIT, 0);
	SetHandleInformation(st->si.hStdOutput, HANDLE_FLAG_INHERIT, 0);
	SetHandleInformation(st->si.hStdInput, HANDLE_FLAG_INHERIT, 0);
#endif
	if (CreateProcess(NULL,
		st->cmdline,
		NULL,		// process handle not inheritable
		NULL,		// thread handle not inheritable
		FALSE,		// set handle inheritance
		0,		// no creation flags
		NULL,		// use parent's env. block
		NULL,		// use parent's starting directory
		&st->si,	// startup-info structure pointer
		&st->pi		// process-info structure pointer
	)) {	// Windows does this differently as well compared to others: non-zero value means OKEY ....
		st->creationstatus = 0;
		DEBUGPRINT("EXEC: (%s) seems to be OK :-)" NL, cmdline);
	} else {
		st->creationstatus = GetLastError();
		DEBUGPRINT("EXEC: (%s) failed with %d" NL, cmdline, (int)st->creationstatus);
		if (!st->creationstatus) {	// I am not sure what Windows fumbles for, even MSDN is quite lame without _exact_ specification (MS should learn from POSIX dox ...)
			st->creationstatus = 1;
		}
	}
	//CloseHandle(st->si.hStdError);
	//CloseHandle(st->si.hStdOutput);
	//CloseHandle(st->si.hStdInput);
	return st;
}
Exemplo n.º 4
0
    /*
     * The ServiceMain function to start service.
     */
VOID WINAPI
ServiceMain (DWORD argc, LPTSTR argv[])
{
  SECURITY_ATTRIBUTES SecurityAttributes;
  unsigned threadId;

  /*
   * Input Arguments to function startup 
   */
  DWORD ArgCount = 0;
  LPTSTR *ArgArray = NULL;
  TCHAR szRegKey[512];
  TCHAR szValue[128];
  DWORD nSize;
  HKEY hParamKey = NULL;	/* To read startup parameters */
  DWORD TotalParams = 0;
  DWORD i;
  InputParams ThreadInputParams;

  /*
   * Build the Input parameters to pass to worker thread 
   */

  /*
   * SCM sends Service Name as first arg, increment to point
   * arguments user specified while starting contorl agent
   */

  /*
   * Read registry parameter 
   */
  ArgCount = 1;

  /*
   * Create Registry Key path 
   */
  _sntprintf (szRegKey, CountOf(szRegKey), _T("%s%s\\%s"),
	     _T ("SYSTEM\\CurrentControlSet\\Services\\"), app_name_long,
	     _T("Parameters"));
  if (RegOpenKeyEx
      (HKEY_LOCAL_MACHINE, szRegKey, 0, KEY_ALL_ACCESS, &hParamKey) == ERROR_SUCCESS)
    {

      /*
       * Read startup Configuration information 
       */
      /*
       * Find number of subkeys inside parameters 
       */
      if (RegQueryInfoKey (hParamKey, NULL, NULL, 0,
	   NULL, NULL, NULL, &TotalParams,
	   NULL, NULL, NULL, NULL) == ERROR_SUCCESS)
	{
	  if (TotalParams != 0)
	    {
	      ArgCount += TotalParams;

	      /*
	       * Allocate memory to hold strings 
	       */
	      ArgArray = (LPTSTR *) malloc (sizeof (LPTSTR) * ArgCount);
              if (ArgArray == 0)
                {
                  WriteToEventLog (EVENTLOG_ERROR_TYPE,
		       _T ("Resource failure"));
                  return;
                }

	      /*
	       * Copy first argument 
	       */
	      ArgArray[0] = _tcsdup (argv[0]);
	      for (i = 1; i <= TotalParams; i++)
		{

		  /*
		   * Create Subkey value name 
		   */
		  _sntprintf (szRegKey, CountOf(szRegKey), _T("%s%d"), _T("Param"), i);

		  /*
		   * Set size 
		   */
		  nSize = 128;
		  RegQueryValueEx (hParamKey, szRegKey, 0, NULL,
				   (LPBYTE) & szValue, &nSize);
		  ArgArray[i] = _tcsdup (szValue);
		}
	    }
	}
      RegCloseKey (hParamKey);
    }
  if (ArgCount == 1)
    {

      /*
       * No statup agrs are given 
       */
      ThreadInputParams.Argc = argc;
      ThreadInputParams.Argv = argv;
    }

  else
    {
      ThreadInputParams.Argc = ArgCount;
      ThreadInputParams.Argv = ArgArray;
    }

  /*
   * Register Service Control Handler 
   */
  hServiceStatus = RegisterServiceCtrlHandler (app_name_long, ControlHandler);
  if (hServiceStatus == 0)
    {
      WriteToEventLog (EVENTLOG_ERROR_TYPE,
		       _T ("RegisterServiceCtrlHandler failed"));
      return;
    }

  /*
   * Update the service status to START_PENDING 
   */
  UpdateServiceStatus (SERVICE_START_PENDING, NO_ERROR, SCM_WAIT_INTERVAL);

  /*
   * Spin of worker thread, which does majority of the work 
   */
  TRY
  {
    if (SetSimpleSecurityAttributes (&SecurityAttributes) == FALSE)
      {
	WriteToEventLog (EVENTLOG_ERROR_TYPE,
			 _T ("Couldn't init security attributes"));
	LEAVE;
      }
    hServiceThread =
      (void *) _beginthreadex (&SecurityAttributes, 0,
			       ThreadFunction,
			       (void *) &ThreadInputParams, 0, &threadId);
    if (hServiceThread == NULL)
      {
	WriteToEventLog (EVENTLOG_ERROR_TYPE, _T ("Couldn't start worker thread"));
	LEAVE;
      }

    /*
     * Set Service Status to Running 
     */
    UpdateServiceStatus (SERVICE_RUNNING, NO_ERROR, SCM_WAIT_INTERVAL);

    /*
     * Wait for termination event and worker thread to
     * * spin down.
     */
    WaitForSingleObject (hServiceThread, INFINITE);
  }
  FINALLY
  {
    /*
     * Release resources 
     */
    UpdateServiceStatus (SERVICE_STOPPED, NO_ERROR, SCM_WAIT_INTERVAL);
    if (hServiceThread)
      CloseHandle (hServiceThread);
    FreeSecurityAttributes (&SecurityAttributes);

    /*
     * Delete allocated argument list 
     */
    if (ArgCount > 1 && ArgArray != NULL)
      {
	/*
	 * Delete all strings 
	 */
	for (i = 0; i < ArgCount; i++)
	  {
	    free (ArgArray[i]);
	  }
	free (ArgArray);
      }
  }
}
Exemplo n.º 5
0
static int AddDatabaseToList(HWND hwndList, TCHAR* filename, TCHAR* dir)
{
	LV_ITEM lvi;
	int iNewItem;
	TCHAR szSize[20], *pName, *pDot, szName[MAX_PATH];
	HANDLE hDbFile;
	DBHeader dbhdr;
	DWORD bytesRead;
	DWORD totalSize,wasted=0;
	int broken=0;

	lvi.mask=LVIF_PARAM;
	lvi.iSubItem=0;
	for(lvi.iItem=ListView_GetItemCount(hwndList)-1;lvi.iItem>=0;lvi.iItem--) {
		ListView_GetItem(hwndList,&lvi);
		if( !_tcsicmp(( TCHAR* )lvi.lParam,filename)) return lvi.iItem;
	}
	hDbFile=CreateFile(filename,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL);
	if ( hDbFile == INVALID_HANDLE_VALUE )
		return -1;

	ReadFile(hDbFile,&dbhdr,sizeof(dbhdr),&bytesRead,NULL);
	totalSize=GetFileSize(hDbFile,NULL);

	broken = (bytesRead<sizeof(dbhdr) || memcmp(dbhdr.signature,&dbSignature,sizeof(dbhdr.signature)));

	if(!broken) {
		wasted = dbhdr.slackSpace;
		if (totalSize>dbhdr.ofsFileEnd)
			wasted+=totalSize-dbhdr.ofsFileEnd;
	}
	CloseHandle(hDbFile);

	pName = _tcsrchr(filename,'\\');
	if ( pName == NULL )
		pName = ( LPTSTR )filename;
	else
		pName++;
	_tcscpy(szName,dir);
	_tcscat(szName,pName);
	pDot = _tcsrchr( szName, '.' );
	if ( pDot != NULL && !_tcsicmp( pDot, _T(".dat")) )
		*pDot=0;

	lvi.iItem = 0;
	lvi.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE;
	lvi.iSubItem = 0;
	lvi.lParam = ( LPARAM )_tcsdup(filename);
	lvi.pszText = szName;
	if (broken)
		lvi.iImage = 3;
	else if ( wasted < 1024*128 )
		lvi.iImage = 0;
	else if ( wasted < 1024*256 + (DWORD)(totalSize > 2*1024*1024 ) ? 256 * 1024 : 0 )
		lvi.iImage=1;
	else
		lvi.iImage=2;

	iNewItem = ListView_InsertItem(hwndList, &lvi );
	_stprintf(szSize,_T("%.2lf MB"),totalSize/1048576.0);
	ListView_SetItemText(hwndList,iNewItem,1,szSize);
	if ( !broken ) {
		_stprintf(szSize,_T("%.2lf MB"),wasted/1048576.0);
		ListView_SetItemText(hwndList,iNewItem,2,szSize);
	}
	return iNewItem;
}
Exemplo n.º 6
0
ProxyPage::ProxyPage(SettingsManager *s) : PropPage(s) {
	title = _tcsdup((TSTRING(SETTINGS_NETWORK) + _T('\\') + TSTRING(PROXIES)).c_str());
	SetTitle(title);

	m_psp.dwFlags |= PSP_RTLREADING;
}
Exemplo n.º 7
0
int CInternet::URLPost(const TCHAR *lpszServer, const char *lpszDest)
{
	int bReturn = 0;
//	HINTERNET  hConnect = NULL, hRequest = NULL;
	
	TCHAR szErrMsg[512];
  	char *lpBufferA=NULL;

	LPTSTR AcceptTypes[10] = {TEXT("*/*"), NULL}; 

    DWORD dwRequestFlag = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;

	if(strstr(lpszServer,"https://")!=NULL) //check if it is a HTTPS server
		dwRequestFlag = INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID | INTERNET_FLAG_IGNORE_CERT_CN_INVALID;

	TCHAR szHeaders[] = _T("Content-Type: application/x-www-form-urlencoded"); //content type for post...
	
	TCHAR *HostName = _tcsdup(uc.lpszHostName);
	HostName[uc.dwHostNameLength] = '\0';
	TCHAR *FileName = _tcsdup(uc.lpszUrlPath);
	FileName[uc.dwUrlPathLength] = '\0';
	HINTERNET hCO = InternetConnect(m_hOpen, HostName, uc.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, INTERNET_FLAG_NO_CACHE_WRITE, 0);
	HINTERNET hIS = HttpOpenRequest(hCO, _T("POST"), FileName, NULL, NULL, (LPCTSTR*)AcceptTypes, dwRequestFlag, 0);

again:
	HINTERNET hOU = InternetOpenUrl (m_hOpen, lpszServer, NULL, 0,dwRequestFlag, 0);
	//DWORD dwLength = GetFileLength(hOU);
	if (!HttpSendRequest(hIS, szHeaders, _tcslen(szHeaders), (TCHAR*)&uc.lpszUrlPath[1], _tcslen(&uc.lpszUrlPath[1])))
	{
		DWORD LastError = GetLastError();
		if(LastError == ERROR_INTERNET_INVALID_CA)
		{
			DWORD dwFlags;
			DWORD dwBuffLen = sizeof(dwFlags);

			InternetQueryOption (hIS, INTERNET_OPTION_SECURITY_FLAGS,
			(LPVOID)&dwFlags, &dwBuffLen);

			dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA;
			InternetSetOption (hIS, INTERNET_OPTION_SECURITY_FLAGS,
			&dwFlags, sizeof (dwFlags) );
			goto again;

		}
	}
	
	FILE *stream = NULL;
	errno_t err = _set_fmode(_O_BINARY);
	if (err == EINVAL)
	{ 
	  OutputDebugString("Invalid mode.\n");
	  return 5;
	}
	
	DWORD dynamicByte = 32000;
	DWORD downloadBytes = 0;
	DWORD dwSize = 0; 
	DWORD availableSize=0;
	do
	{
		lpBufferA = new CHAR [dynamicByte];
		InternetQueryDataAvailable(hIS,&availableSize,0,0);
		sprintf_s(szErrMsg,sizeof(szErrMsg),"Downloaded %d of %d KBytes\n",downloadBytes/1000,availableSize/1000);
		OutputDebugString(szErrMsg);	
	
		if (!InternetReadFile (hIS, (LPVOID)lpBufferA, dynamicByte, &dwSize))
		{
			_stprintf_s(szErrMsg, TEXT("%s: %x\n"), TEXT("InternetReadFile Error"),GetLastError());
			OutputDebugString(szErrMsg);
			delete[] lpBufferA;
			goto exit;
		}

		if (dwSize != 0)    
		{	
			downloadBytes+=dwSize;
			if((stream==NULL) && (bReturn==0))
		   		fopen_s(&stream, lpszDest, "w+" );

			if(stream!=NULL)
				 fwrite( lpBufferA, sizeof( CHAR ), dwSize, stream );		
		}    
		if(lpBufferA)
			delete[] lpBufferA; 
		dynamicByte+=1024;
		if(dynamicByte>128000)
			dynamicByte = 128000;

	} while (dwSize);

	if(stream!=NULL)
		fclose(stream);

  goto exitWithNoErr;
exit:
	bReturn = 1;
exitWithNoErr:
	free(HostName);
	free(FileName);

	if (hIS)
	{
		if (!InternetCloseHandle (hIS))
		{
			_stprintf_s(szErrMsg, TEXT("%s: %x"), TEXT("CloseHandle Error"), GetLastError());
			OutputDebugString(szErrMsg);
		}
	}
	if (hCO)
	{
		if (!InternetCloseHandle (hCO))
		{
			_stprintf_s(szErrMsg, TEXT("%s: %x"), TEXT("ConnectOpen close Error"), GetLastError());
			OutputDebugString(szErrMsg);
		}
	}
    _stprintf_s(szErrMsg, TEXT("Return %d"), bReturn);
	OutputDebugString(szErrMsg);
	return bReturn;
}
int APIENTRY	_tWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
	size_t i;
	MSG msg;

	// Initialize global strings
	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDS_NINTENDULATOR, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance);

	GetModuleFileName(NULL, ProgPath, MAX_PATH);
	for (i = _tcslen(ProgPath); (i > 0) && (ProgPath[i] != _T('\\')); i--)
		ProgPath[i] = 0;

	// find our folder in Application Data, if it exists
	if (!SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, DataPath)))
	{
		// if we can't even find AppData, then there's a much bigger problem...
		MessageBox(NULL, _T("FATAL: unable to locate Application Data folder for current user"), _T("Nintendulator"), MB_OK | MB_ICONERROR);
		return FALSE;
	}
	PathAppend(DataPath, _T("Nintendulator"));
	if (GetFileAttributes(DataPath) == INVALID_FILE_ATTRIBUTES)
		CreateDirectory(DataPath, NULL);

	// Perform application initialization:
	if (!InitInstance (hInstance, nCmdShow)) 
		return FALSE;

	hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_NINTENDULATOR);

	timeBeginPeriod(1);

	if (lpCmdLine[0])
	{
		// grab a copy of the command line parms - we're gonna need to extract a single filename from it
		TCHAR *cmdline = _tcsdup(lpCmdLine);
		// and remember the pointer so we can safely free it at the end
		TCHAR *bkptr = cmdline;

		// if the filename is in quotes, strip them off (and ignore everything past it)
		if (cmdline[0] == _T('"'))
		{
			cmdline++;
			// yes, it IS possible for the second quote to not exist!
			if (_tcschr(cmdline, '"'))
				*_tcschr(cmdline, '"') = 0;
		}
		// otherwise just kill everything past the first space
		else if (_tcschr(cmdline, ' '))
			*_tcschr(cmdline, ' ') = 0;

		NES::OpenFile(cmdline);
		free(bkptr);	// free up the memory from its original pointer
	}

	// Main message loop:
	while (GetMessage(&msg, NULL, 0, 0))
	{
		HWND focus = GetForegroundWindow();
		if ((focus != hMainWnd) && IsDialogMessage(focus, &msg))
			continue;
		if (MaskKeyboard || !TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) 
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}
	timeEndPeriod(1);

	return (int)msg.wParam;
}
Exemplo n.º 9
0
Arquivo: nla.c Projeto: CeBkCn/FreeRDP
LPTSTR nla_make_spn(const char* ServiceClass, const char* hostname)
{
	DWORD status;
	DWORD SpnLength;
	LPTSTR hostnameX = NULL;
	LPTSTR ServiceClassX = NULL;
	LPTSTR ServicePrincipalName = NULL;
#ifdef UNICODE
	ConvertToUnicode(CP_UTF8, 0, hostname, -1, &hostnameX, 0);
	ConvertToUnicode(CP_UTF8, 0, ServiceClass, -1, &ServiceClassX, 0);
#else
	hostnameX = _strdup(hostname);
	ServiceClassX = _strdup(ServiceClass);
#endif
	if (!hostnameX || !ServiceClassX)
	{
		free(hostnameX);
		free(ServiceClassX);
		return NULL;
	}

	if (!ServiceClass)
	{
		ServicePrincipalName = (LPTSTR) _tcsdup(hostnameX);
		free(ServiceClassX);
		free(hostnameX);
		return ServicePrincipalName;
	}

	SpnLength = 0;
	status = DsMakeSpn(ServiceClassX, hostnameX, NULL, 0, NULL, &SpnLength, NULL);

	if (status != ERROR_BUFFER_OVERFLOW)
	{
		free(ServiceClassX);
		free(hostnameX);
		return NULL;
	}

	ServicePrincipalName = (LPTSTR) malloc(SpnLength * sizeof(TCHAR));

	if (!ServicePrincipalName)
	{
		free(ServiceClassX);
		free(hostnameX);
		return NULL;
	}

	status = DsMakeSpn(ServiceClassX, hostnameX, NULL, 0, NULL, &SpnLength, ServicePrincipalName);

	if (status != ERROR_SUCCESS)
	{
		free(ServicePrincipalName);
		free(ServiceClassX);
		free(hostnameX);
		return NULL;
	}

	free(ServiceClassX);
	free(hostnameX);
	return ServicePrincipalName;
}
Exemplo n.º 10
0
static TCHAR* GetWindowTitle(HANDLE *hContact, const char *szProto)
{
	DBVARIANT dbv;
	int isTemplate;
	int len, contactNameLen = 0, statusLen = 0, statusMsgLen = 0, protocolLen = 0;
	TCHAR *p, *tmplt, *szContactName = NULL, *szStatus = NULL, *szStatusMsg = NULL, *szProtocol = NULL, *title;
	TCHAR *pszNewTitleEnd = _tcsdup(TranslateT("Message Session"));
	isTemplate = 0;
	if (hContact && szProto) {
		szContactName = GetNickname(hContact, szProto);
		contactNameLen = lstrlen(szContactName);
		szStatus = strToWcs((char *) CallService(MS_CLIST_GETSTATUSMODEDESCRIPTION, szProto == NULL ? ID_STATUS_OFFLINE : DBGetContactSettingWord(hContact, szProto, "Status", ID_STATUS_OFFLINE), 0), -1, CP_ACP);
		statusLen = lstrlen(szStatus);
		if (!DBGetContactSetting(hContact, "CList", "StatusMsg",&dbv)) {
			if (strlen(dbv.pszVal) > 0) {
				int i, j;
       			szStatusMsg = strToWcs(dbv.pszVal, -1, CP_ACP);
				statusMsgLen = lstrlen(szStatusMsg);
				for (i = j = 0; i < statusMsgLen; i++) {
					if (szStatusMsg[i] == '\r') {
						continue;
					} else if (szStatusMsg[i] == '\n') {
						szStatusMsg[j++] = ' ';
					} else {
						szStatusMsg[j++] = szStatusMsg[i];
					}
				}
				szStatusMsg[j] = '\0';
				statusMsgLen = j;
			}
       		DBFreeVariant(&dbv);
		}

		if (!DBGetContactSetting(NULL, SRMMMOD, SRMSGSET_WINDOWTITLE, &dbv)) {
			isTemplate = 1;
			tmplt = strToWcs(dbv.pszVal, -1, CP_ACP);
			DBFreeVariant(&dbv);
		} else {
			int statusIcon = DBGetContactSettingByte(NULL, SRMMMOD, SRMSGSET_STATUSICON, SRMSGDEFSET_STATUSICON);
			if (statusIcon) {
				tmplt = _T("%name% - ");
			} else {
				tmplt = _T("%name% (%status%) : ");
			}
		}
	} else {
		tmplt = _T("");
	}
	for (len = 0, p = tmplt; *p; p++) {
		if (*p == '%') {
			if (!_tcsncmp(p, _T("%name%"), 6)) {
				len += contactNameLen;
				p += 5;
				continue;
			} else if (!_tcsncmp(p, _T("%status%"), 8)) {
				len += statusLen;
				p += 7;
				continue;
			} else if (!_tcsncmp(p, _T("%statusmsg%"), 11)) {
				len += statusMsgLen;
				p += 10;
				continue;
			}
		}
		len++;
	}
	if (!isTemplate) {
		len += lstrlen(pszNewTitleEnd);
	}
	title = (TCHAR *)malloc(sizeof(TCHAR) * (len + 1));
	for (len = 0, p = tmplt; *p; p++) {
		if (*p == '%') {
			if (!_tcsncmp(p, _T("%name%"), 6)) {
				memcpy(title+len, szContactName, sizeof(TCHAR) * contactNameLen);
				len += contactNameLen;
				p += 5;
				continue;
			} else if (!_tcsncmp(p, _T("%status%"), 8)) {
				memcpy(title+len, szStatus, sizeof(TCHAR) * statusLen);
				len += statusLen;
				p += 7;
				continue;
			} else if (!_tcsncmp(p, _T("%statusmsg%"), 11)) {
				memcpy(title+len, szStatusMsg, sizeof(TCHAR) * statusMsgLen);
				len += statusMsgLen;
				p += 10;
				continue;
			}
		}
		title[len++] = *p;
	}
	if (!isTemplate) {
		memcpy(title+len, pszNewTitleEnd, sizeof(TCHAR) * lstrlen(pszNewTitleEnd));
		len += lstrlen(pszNewTitleEnd);
	}
	title[len] = '\0';
	if (isTemplate) {
		free(tmplt);
	}
	free(szContactName);
	free(szStatus);
	free(pszNewTitleEnd);
	return title;
}
Exemplo n.º 11
0
BOOL CNav_Scaner_InterfaceApp::InitInstance()
{
	// InitCommonControlsEx() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.
	INITCOMMONCONTROLSEX InitCtrls;
	InitCtrls.dwSize = sizeof(InitCtrls);
	// Set this to include all the common control classes you want to use
	// in your application.
	InitCtrls.dwICC = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);

	CWinApp::InitInstance();

	AfxEnableControlContainer();

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	// of your final executable, you should remove from the following
	// the specific initialization routines you do not need
	// Change the registry key under which our settings are stored
	// TODO: You should modify this string to be something appropriate
	// such as the name of your company or organization
	CString sPath;
	wchar_t cBuffer[MAX_PATH];
    ::GetModuleFileName(NULL, cBuffer, MAX_PATH);
    sPath = cBuffer;
    sPath = sPath.Left(sPath.ReverseFind('\\'));
	if (sPath.Right(1)!="\\") sPath += "\\";

	CString sFileName = sPath+AfxGetApp()->m_pszProfileName;
	sFileName.MakeLower();
	if(sFileName.Right(4)!=_T(".ini"))
	{
		sFileName = sFileName.Left(sFileName.GetLength()-4);
		sFileName = sFileName + _T(".ini");
	}
	free((void*)AfxGetApp()->m_pszProfileName);
	AfxGetApp()->m_pszProfileName = _tcsdup(sFileName);
	
	IniReader.SetIniFileName();

	OpenDBNav();
	CString sError;
	if(!OpenDBProg(&sError))
	{
		AfxMessageBox(sError);
	}
	else
	{
		CNav_Scaner_InterfaceDlg dlg;
		m_pMainWnd = &dlg;
		INT_PTR nResponse = dlg.DoModal();
		if (nResponse == IDOK)
		{
		
		}
		else if (nResponse == IDCANCEL)
		{
	
		}
	}
	CloseDBProg();
	CloseDBNav();
	// Since the dialog has been closed, return FALSE so that we exit the
	//  application, rather than start the application's message pump.
	return FALSE;
}
Exemplo n.º 12
0
/// Creates a new named pipe instance.
///
/// @param[in] pipe underlying O/S file handle
/// @param[in] pszName name of the pipe, not NULL
/// @param[in] bServer true if this is a server that can accept connections
/// @param[in] bReader true if this is the read end (or a server that returns read ends, i.e. accepts connections from clients that will write)
CNamedPipe::CNamedPipe (FILE_REFERENCE pipe, const TCHAR *pszName, bool bServer, bool bReader)
: CTimeoutIO (pipe) {
	m_pszName = _tcsdup (pszName);
	m_bServer = bServer;
	m_bReader = bReader;
}
Exemplo n.º 13
0
	/// Creates a new thread instance
	///
	/// @param[in] pszName name of the pipe, not NULL
	/// @param[in] nMode file mode to open the pipe in
	CNamedPipeOpenThread (const TCHAR *pszName, int nMode) : CThread () {
		m_pszName = _tcsdup (pszName);
		m_nMode = nMode;
	}
Exemplo n.º 14
0
BOOL CALLBACK CPeManifestAssembly::EnumResNameProc(HMODULE hModule,LPCTSTR lpszType,LPTSTR lpszName,LONG_PTR lParam)
{
    CPeManifestAssembly* pManifestAssembly = (CPeManifestAssembly*)lParam;
    if( lpszType==RT_MANIFEST)
    {
        HRSRC hResource = ::FindResource(hModule, lpszName, lpszType);
        if( hResource )
        {
            // DWORD dwResource = ::SizeofResource(hModule, hResource);

            HGLOBAL hResData = ::LoadResource(hModule, hResource); 
            if(hResData)
            {
                const BYTE *pResource = (const BYTE *)::LockResource(hResData); 
                if(pResource)
                {
                    // example of manifest content
                    //<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
                    //<dependency>
                    //  <dependentAssembly>
                    //    <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" version="9.0.21022.8" processorArchitecture="x86" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity>
                    //  </dependentAssembly>
                    //</dependency>
                    //<dependency>
                    //  <dependentAssembly>
                    //    <assemblyIdentity type="win32" name="Microsoft.VC90.MFC" version="9.0.21022.8" processorArchitecture="x86" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity>
                    //  </dependentAssembly>
                    //</dependency>
                    //<dependency>
                    //  <dependentAssembly>
                    //    <assemblyIdentity type="win32" name="Microsoft.VC90.ATL" version="9.0.21022.8" processorArchitecture="x86" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity>
                    //  </dependentAssembly>
                    //</dependency>
                    //</assembly>

                    TCHAR* ResourceContent;
                    // manifest seems to be only in ansi encoding --> convert to TCHAR
                    CAnsiUnicodeConvert::AnsiToTchar((char*)pResource,&ResourceContent);
                    if (ResourceContent)
                    {
                        TCHAR* LocalResourceContent;
                        // assume to get local copy to put \0 for a quicker parsing
                        LocalResourceContent = _tcsdup(ResourceContent);
                        free(ResourceContent);
                        if (LocalResourceContent)
                        {
                            // Do a very light parsing
                            TCHAR* dependentAssemblyBeginTag;
                            TCHAR* dependentAssemblyEndTag;
                            TCHAR* assemblyIdentityBeginTag;
                            TCHAR* assemblyIdentityEndTag;
                            TCHAR* StrIdentityContent;
                            CPeManifestAssemblyIdentity* pIdentity;
                            TCHAR* CurrentPos;
                            SIZE_T assemblyIdentityBeginTagSize;
                            SIZE_T assemblyIdentityEndTagSize;
                            SIZE_T dependentAssemblyBeginTagSize;
                            SIZE_T dependentAssemblyEndTagSize;

                            CurrentPos = LocalResourceContent;
                            dependentAssemblyBeginTagSize = _tcslen(ASSEMBLY_DEPENDENT_ASSEMBLY_BEGIN_TAG);
                            dependentAssemblyEndTagSize = _tcslen(ASSEMBLY_DEPENDENT_ASSEMBLY_END_TAG);
                            assemblyIdentityBeginTagSize = _tcslen(ASSEMBLY_IDENTITY_BEGIN_TAG);
                            assemblyIdentityEndTagSize = _tcslen(ASSEMBLY_IDENTITY_END_TAG);

                            // find <dependentAssembly> and </dependentAssembly>
                            dependentAssemblyBeginTag = _tcsstr(CurrentPos, ASSEMBLY_DEPENDENT_ASSEMBLY_BEGIN_TAG );
                            dependentAssemblyEndTag = _tcsstr(CurrentPos, ASSEMBLY_DEPENDENT_ASSEMBLY_END_TAG );
                            while (dependentAssemblyBeginTag && dependentAssemblyEndTag)
                            {
                                CurrentPos = dependentAssemblyBeginTag+dependentAssemblyBeginTagSize;
                                *dependentAssemblyEndTag=0; // we can do this as we use a local buffer

                                // find <assemblyIdentity
                                assemblyIdentityBeginTag = _tcsstr(CurrentPos,ASSEMBLY_IDENTITY_BEGIN_TAG);
                                assemblyIdentityEndTag = _tcsstr(CurrentPos,ASSEMBLY_IDENTITY_END_TAG);
                                while (assemblyIdentityBeginTag && assemblyIdentityEndTag)
                                {
                                    // point after <assemblyIdentity
                                    StrIdentityContent = assemblyIdentityBeginTag + assemblyIdentityBeginTagSize;

                                    pIdentity = new CPeManifestAssemblyIdentity();
                                    // parse identity content
                                    if (pIdentity->Parse(StrIdentityContent))
                                    {
                                        //	on success, add the dependency to the collection
                                        pManifestAssembly->AddDependency(pIdentity);
                                    }
                                    else
                                        delete pIdentity;

                                    // point after </assemblyIdentity>
                                    CurrentPos = assemblyIdentityEndTag + assemblyIdentityEndTagSize;

                                    // find next <assemblyIdentity
                                    assemblyIdentityBeginTag = _tcsstr(CurrentPos,ASSEMBLY_IDENTITY_BEGIN_TAG);
                                }

                                // point after </dependentAssembly>
                                CurrentPos = dependentAssemblyEndTag + dependentAssemblyEndTagSize;

                                // find next <dependentAssembly> and </dependentAssembly>
                                dependentAssemblyBeginTag = _tcsstr(CurrentPos, ASSEMBLY_DEPENDENT_ASSEMBLY_BEGIN_TAG );
                                dependentAssemblyEndTag = _tcsstr(CurrentPos, ASSEMBLY_DEPENDENT_ASSEMBLY_END_TAG );
                            }
                            free(LocalResourceContent);
                        }
                    }

                }

                UnlockResource(hResData); 
                ::FreeResource(hResData); 
            }
        }
    }

    //	Keep going.
    return TRUE;
}
Exemplo n.º 15
0
BOOL CTortoiseProcApp::InitInstance()
{
	EnableCrashHandler();
	InitializeJumpList();
	CheckUpgrade();
	CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
	CMFCButton::EnableWindowsTheming();

	Gdiplus::GdiplusStartupInput gdiplusStartupInput;
	Gdiplus::GdiplusStartup(&m_gdiplusToken,&gdiplusStartupInput,NULL);

	if(!CheckMsysGitDir())
	{
		UINT ret = CMessageBox::Show(NULL,_T("MSysGit (http://code.google.com/p/msysgit/) not found."),
									_T("TortoiseGit"), 3, IDI_HAND, _T("&Set MSysGit path"), _T("&Goto WebSite"), _T("&Abort"));
		if(ret == 2)
		{
			ShellExecute(NULL, NULL, _T("http://code.google.com/p/msysgit/"), NULL, NULL, SW_SHOW);
		}
		else if(ret == 1)
		{
			// open settings dialog
			CSettings dlg(IDS_PROC_SETTINGS_TITLE);
			dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
			dlg.SetTreeWidth(220);

			dlg.DoModal();
			dlg.HandleRestart();
		}
		return FALSE;
	}

	//set the resource dll for the required language
	CRegDWORD loc = CRegDWORD(_T("Software\\TortoiseGit\\LanguageID"), 1033);
	long langId = loc;
	CString langDll;
	CStringA langpath = CStringA(CPathUtils::GetAppParentDirectory());
	langpath += "Languages";
//	bindtextdomain("subversion", (LPCSTR)langpath);
//	bind_textdomain_codeset("subversion", "UTF-8");
	HINSTANCE hInst = NULL;
	do
	{
		langDll.Format(_T("..\\Languages\\TortoiseProc%d.dll"), langId);

		hInst = LoadLibrary(langDll);

		CString sVer = _T(STRPRODUCTVER);
		CString sFileVer = CPathUtils::GetVersionFromFile(langDll);
		if (sFileVer.Compare(sVer)!=0)
		{
			FreeLibrary(hInst);
			hInst = NULL;
		}
		if (hInst != NULL)
		{
			AfxSetResourceHandle(hInst);
		}
		else
		{
			DWORD lid = SUBLANGID(langId);
			lid--;
			if (lid > 0)
			{
				langId = MAKELANGID(PRIMARYLANGID(langId), lid);
			}
			else
				langId = 0;
		}
	} while ((hInst == NULL) && (langId != 0));
	TCHAR buf[6];
	_tcscpy_s(buf, _T("en"));
	langId = loc;
	CString sHelppath;
	sHelppath = this->m_pszHelpFilePath;
	sHelppath = sHelppath.MakeLower();
	// MFC uses a help file with the same name as the application by default,
	// which means we have to change that default to our language specific help files
	sHelppath.Replace(_T("tortoiseproc.chm"), _T("TortoiseGit_en.chm"));
	free((void*)m_pszHelpFilePath);
	m_pszHelpFilePath=_tcsdup(sHelppath);
	sHelppath = CPathUtils::GetAppParentDirectory() + _T("Languages\\TortoiseGit_en.chm");
	do
	{
		CString sLang = _T("_");
		if (GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf)))
		{
			sLang += buf;
			sHelppath.Replace(_T("_en"), sLang);
			if (PathFileExists(sHelppath))
			{
				free((void*)m_pszHelpFilePath);
				m_pszHelpFilePath=_tcsdup(sHelppath);
				break;
			}
		}
		sHelppath.Replace(sLang, _T("_en"));
		if (GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf)))
		{
			sLang += _T("_");
			sLang += buf;
			sHelppath.Replace(_T("_en"), sLang);
			if (PathFileExists(sHelppath))
			{
				free((void*)m_pszHelpFilePath);
				m_pszHelpFilePath=_tcsdup(sHelppath);
				break;
			}
		}
		sHelppath.Replace(sLang, _T("_en"));

		DWORD lid = SUBLANGID(langId);
		lid--;
		if (lid > 0)
		{
			langId = MAKELANGID(PRIMARYLANGID(langId), lid);
		}
		else
			langId = 0;
	} while (langId);
	setlocale(LC_ALL, "");

	// InitCommonControls() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.

	INITCOMMONCONTROLSEX used = {
		sizeof(INITCOMMONCONTROLSEX),
			ICC_ANIMATE_CLASS | ICC_BAR_CLASSES | ICC_COOL_CLASSES | ICC_DATE_CLASSES |
			ICC_HOTKEY_CLASS | ICC_INTERNET_CLASSES | ICC_LISTVIEW_CLASSES |
			ICC_NATIVEFNTCTL_CLASS | ICC_PAGESCROLLER_CLASS | ICC_PROGRESS_CLASS |
			ICC_TAB_CLASSES | ICC_TREEVIEW_CLASSES | ICC_UPDOWN_CLASS |
			ICC_USEREX_CLASSES | ICC_WIN95_CLASSES
	};
	InitCommonControlsEx(&used);
	AfxOleInit();
	AfxEnableControlContainer();
	AfxInitRichEdit2();
	CWinAppEx::InitInstance();
	SetRegistryKey(_T("TortoiseGit"));

	CCmdLineParser parser(AfxGetApp()->m_lpCmdLine);

	// if HKCU\Software\TortoiseGit\Debug is not 0, show our command line
	// in a message box
	if (CRegDWORD(_T("Software\\TortoiseGit\\Debug"), FALSE)==TRUE)
		AfxMessageBox(AfxGetApp()->m_lpCmdLine, MB_OK | MB_ICONINFORMATION);

	if ( parser.HasKey(_T("path")) && parser.HasKey(_T("pathfile")))
	{
		CMessageBox::Show(NULL, IDS_ERR_INVALIDPATH, IDS_APPNAME, MB_ICONERROR);
		return FALSE;
	}

	CTGitPath cmdLinePath;
	CTGitPathList pathList;
	if ( parser.HasKey(_T("pathfile")) )
	{

		CString sPathfileArgument = CPathUtils::GetLongPathname(parser.GetVal(_T("pathfile")));

		cmdLinePath.SetFromUnknown(sPathfileArgument);
		if (pathList.LoadFromFile(cmdLinePath)==false)
			return FALSE;		// no path specified!
		if ( parser.HasKey(_T("deletepathfile")) )
		{
			// We can delete the temporary path file, now that we've loaded it
			::DeleteFile(cmdLinePath.GetWinPath());
		}
		// This was a path to a temporary file - it's got no meaning now, and
		// anybody who uses it again is in for a problem...
		cmdLinePath.Reset();

	}
	else
	{

		CString sPathArgument = CPathUtils::GetLongPathname(parser.GetVal(_T("path")));
		int asterisk = sPathArgument.Find('*');
		cmdLinePath.SetFromUnknown(asterisk >= 0 ? sPathArgument.Left(asterisk) : sPathArgument);
		pathList.LoadFromAsteriskSeparatedString(sPathArgument);
	}

	if (pathList.GetCount() == 0) {
		pathList.AddPath(CTGitPath::CTGitPath(g_Git.m_CurrentDir));
	}

	hWndExplorer = NULL;
	CString sVal = parser.GetVal(_T("hwnd"));
	if (!sVal.IsEmpty())
		hWndExplorer = (HWND)_ttoi64(sVal);

	while (GetParent(hWndExplorer)!=NULL)
		hWndExplorer = GetParent(hWndExplorer);
	if (!IsWindow(hWndExplorer))
	{
		hWndExplorer = NULL;
	}

	// Subversion sometimes writes temp files to the current directory!
	// Since TSVN doesn't need a specific CWD anyway, we just set it
	// to the users temp folder: that way, Subversion is guaranteed to
	// have write access to the CWD
	{
		DWORD len = GetCurrentDirectory(0, NULL);
		if (len)
		{
			TCHAR * originalCurrentDirectory = new TCHAR[len];
			if (GetCurrentDirectory(len, originalCurrentDirectory))
			{
				//sOrigCWD = originalCurrentDirectory;
				//sOrigCWD = CPathUtils::GetLongPathname(sOrigCWD);
			}
			delete [] originalCurrentDirectory;
		}
		TCHAR pathbuf[MAX_PATH];
		GetTempPath(MAX_PATH, pathbuf);
		SetCurrentDirectory(pathbuf);
	}

	// check for newer versions
	if (CRegDWORD(_T("Software\\TortoiseGit\\CheckNewer"), TRUE) != FALSE)
	{
		time_t now;
		struct tm ptm;

		time(&now);
		if ((now != 0) && (localtime_s(&ptm, &now)==0))
		{
			int week = 0;
			// we don't calculate the real 'week of the year' here
			// because just to decide if we should check for an update
			// that's not needed.
			week = ptm.tm_yday / 7;

			CRegDWORD oldweek = CRegDWORD(_T("Software\\TortoiseGit\\CheckNewerWeek"), (DWORD)-1);
			if (((DWORD)oldweek) == -1)
				oldweek = week;		// first start of TortoiseProc, no update check needed
			else
			{
				if ((DWORD)week != oldweek)
				{
					oldweek = week;

					TCHAR com[MAX_PATH+100];
					GetModuleFileName(NULL, com, MAX_PATH);
					_tcscat_s(com, MAX_PATH+100, _T(" /command:updatecheck"));

					CAppUtils::LaunchApplication(com, 0, false);
				}
			}
		}
	}

	if (parser.HasVal(_T("configdir")))
	{
		// the user can override the location of the Subversion config directory here
		CString sConfigDir = parser.GetVal(_T("configdir"));
//		g_GitGlobal.SetConfigDir(sConfigDir);
	}
	// to avoid that SASL will look for and load its plugin dlls all around the
	// system, we set the path here.
	// Note that SASL doesn't have to be initialized yet for this to work
//	sasl_set_path(SASL_PATH_TYPE_PLUGIN, (LPSTR)(LPCSTR)CUnicodeUtils::GetUTF8(CPathUtils::GetAppDirectory().TrimRight('\\')));

	HANDLE TSVNMutex = ::CreateMutex(NULL, FALSE, _T("TortoiseGitProc.exe"));
	if(!g_Git.SetCurrentDir(cmdLinePath.GetWinPathString()))
	{
		int i=0;
		for(i=0;i<pathList.GetCount();i++)
			if(g_Git.SetCurrentDir(pathList[i].GetWinPath()))
				break;
	}

	if(!g_Git.m_CurrentDir.IsEmpty())
		SetCurrentDirectory(g_Git.m_CurrentDir);

	{
		CString err;
		try
		{
			// requires CWD to be set
			CGit::m_LogEncode = CAppUtils::GetLogOutputEncode();
		}
		catch (char* msg)
		{
			err = CString(msg);
		}

		if (!err.IsEmpty())
		{
			UINT choice = CMessageBox::Show(hWndExplorer, err, _T("TortoiseGit Error"), 1, IDI_ERROR, _T("&Edit .git/config"), _T("Edit &global .gitconfig"), _T("&Abort"));
			if (choice == 1)
			{
				// open the config file with alternative editor
				CString path = g_Git.m_CurrentDir;
				path += _T("\\.git\\config");
				CAppUtils::LaunchAlternativeEditor(path);
			}
			else if (choice == 2)
			{
				// open the global config file with alternative editor
				TCHAR buf[MAX_PATH];
				ExpandEnvironmentStrings(_T("%HOMEDRIVE%\\%HOMEPATH%\\.gitconfig"), buf, MAX_PATH);
				CAppUtils::LaunchAlternativeEditor(buf);
			}
			return FALSE;
		}
	}

	// execute the requested command
	CommandServer server;
	Command * cmd = server.GetCommand(parser.GetVal(_T("command")));
	if (cmd)
	{
		cmd->SetExplorerHwnd(hWndExplorer);

		cmd->SetParser(parser);
		cmd->SetPaths(pathList, cmdLinePath);

		retSuccess = cmd->Execute();
		delete cmd;
	}

	if (TSVNMutex)
		::CloseHandle(TSVNMutex);

	// Look for temporary files left around by TortoiseSVN and
	// remove them. But only delete 'old' files because some
	// apps might still be needing the recent ones.
	{
		DWORD len = ::GetTempPath(0, NULL);
		TCHAR * path = new TCHAR[len + 100];
		len = ::GetTempPath (len+100, path);
		if (len != 0)
		{
			CSimpleFileFind finder = CSimpleFileFind(path, _T("*svn*.*"));
			FILETIME systime_;
			::GetSystemTimeAsFileTime(&systime_);
			__int64 systime = (((_int64)systime_.dwHighDateTime)<<32) | ((__int64)systime_.dwLowDateTime);
			while (finder.FindNextFileNoDirectories())
			{
				CString filepath = finder.GetFilePath();
				HANDLE hFile = ::CreateFile(filepath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
				if (hFile != INVALID_HANDLE_VALUE)
				{
					FILETIME createtime_;
					if (::GetFileTime(hFile, &createtime_, NULL, NULL))
					{
						::CloseHandle(hFile);
						__int64 createtime = (((_int64)createtime_.dwHighDateTime)<<32) | ((__int64)createtime_.dwLowDateTime);
						if ((createtime + 864000000000) < systime)		//only delete files older than a day
						{
							::SetFileAttributes(filepath, FILE_ATTRIBUTE_NORMAL);
							::DeleteFile(filepath);
						}
					}
					else
						::CloseHandle(hFile);
				}
			}
		}
		delete[] path;
	}

	// Since the dialog has been closed, return FALSE so that we exit the
	// application, rather than start the application's message pump.
	return FALSE;
}
Exemplo n.º 16
0
BOOL AFXAPI AfxWinInit( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine,
                        int nCmdShow )
/*************************************************************************************/
{
    UNUSED_ALWAYS( hPrevInstance );

    AFX_MODULE_STATE *pState = AfxGetModuleState();
    ASSERT( pState != NULL );
    pState->m_hCurrentInstanceHandle = hInstance;
    pState->m_hCurrentResourceHandle = hInstance;

    WNDCLASS wc;
    wc.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = ::DefWindowProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInstance;
    wc.hIcon = NULL;
    wc.hCursor = ::LoadCursor( NULL, IDC_ARROW );
    wc.hbrBackground = NULL;
    wc.lpszMenuName = NULL;
    wc.lpszClassName = _T("AfxWnd" );
    AfxRegisterClass( &wc );
    wc.hIcon = ::LoadIcon( NULL, IDI_WINLOGO );
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wc.lpszClassName = _T("AfxFrameOrView");
    AfxRegisterClass( &wc );
    wc.style = CS_DBLCLKS;
    wc.hbrBackground = NULL;
    wc.lpszClassName = _T("AfxMDIFrame");
    AfxRegisterClass( &wc );
    wc.style = 0;
    wc.hIcon = NULL;
    wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
    wc.lpszClassName = _T("AfxControlBar");
    AfxRegisterClass( &wc );
    
    CWinApp *pApp = AfxGetApp();
    if( pApp != NULL ) {
        pApp->m_hInstance = hInstance;
        pApp->m_lpCmdLine = lpCmdLine;
        pApp->m_nCmdShow = nCmdShow;

        TCHAR szBuff[MAX_PATH + 1];
        ::GetModuleFileName( hInstance, szBuff, MAX_PATH );
        TCHAR *pszFile = _tcsrchr( szBuff, _T('\\') );
        if( pszFile != NULL ) {
            pszFile++;
        } else {
            pszFile = szBuff;
        }
        TCHAR *pszExt = _tcsrchr( pszFile, _T('.') );
        if( pszExt != NULL ) {
            *pszExt = _T('\0');
        }
        pApp->m_pszExeName = _tcsdup( pszFile );
        if( pApp->m_eHelpType == afxHTMLHelp ) {
            _tcscat( pszFile, _T(".CHM") );
        } else {
            _tcscat( pszFile, _T(".HLP") );
        }
        pApp->m_pszHelpFilePath = _tcsdup( pszFile );
        if( pApp->m_pszAppName == NULL ) {
            TCHAR szAppName[256];
            if( ::LoadString( hInstance, AFX_IDS_APP_TITLE, szAppName, 256 ) > 0 ) {
                pApp->m_pszAppName = _tcsdup( szAppName );
            } else {
                pApp->m_pszAppName = _tcsdup( pApp->m_pszExeName );
            }
        }
        pState->m_lpszCurrentAppName = pApp->m_pszAppName;
    }
    
    return( TRUE );
}
Exemplo n.º 17
0
int UsbSerial::ScanEnumTree( LPCTSTR lpEnumPath, TCHAR** openPorts )
{
  static const TCHAR lpstrPortsClass[] = TEXT("PORTS");
  static const TCHAR lpstrPortsClassGUID[] = TEXT("{4D36E978-E325-11CE-BFC1-08002BE10318}");

  DWORD  dwError=0;
  HKEY   hkEnum=NULL;
  DWORD  dwIndex1;
  HKEY   hkLevel1=NULL;
  DWORD  dwIndex2;
  HKEY   hkLevel2=NULL;
  HKEY   hkDeviceParameters=NULL;
  TCHAR  lpClass[sizeof(lpstrPortsClass)/sizeof(lpstrPortsClass[0])];
  DWORD  cbClass;
  TCHAR  lpClassGUID[sizeof(lpstrPortsClassGUID)/sizeof(lpstrPortsClassGUID[0])];
  DWORD  cbClassGUID;
  LPTSTR lpPortName=NULL;
  LPTSTR lpFriendlyName=NULL;
  
  int openCount = 0;

  typedef struct
  {
    LPCTSTR lpPortName;     /* "COM1", etc. */
    LPCTSTR lpFriendlyName; /* Suitable to describe the port, as for  */
                          /* instance "Infrared serial port (COM4)" */
  }LISTPORTS_PORTINFO;

  //printf( "ScanEnumTree(): top\n" );

  if(dwError=RegOpenKeyEx(HKEY_LOCAL_MACHINE,lpEnumPath,0,KEY_ENUMERATE_SUB_KEYS,&hkEnum)){
    goto end;
  }

  for(dwIndex1=0;;++dwIndex1)
  {
	//printf("finding loop; dwIndex1 = %d\n", dwIndex1);

    if(hkLevel1!=NULL){
      RegCloseKey(hkLevel1);
      hkLevel1=NULL;
    }
    if(dwError=OpenSubKeyByIndex(hkEnum,dwIndex1,KEY_ENUMERATE_SUB_KEYS,&hkLevel1)){
      if(dwError==ERROR_NO_MORE_ITEMS){
        dwError=0;
        break;
      }
      else goto end;
    }

      for(dwIndex2=0;;++dwIndex2){
        BOOL               bFriendlyNameNotFound=FALSE;
        LISTPORTS_PORTINFO portinfo;

        if(hkLevel2!=NULL){
          RegCloseKey(hkLevel2);
          hkLevel2=NULL;
        }
        if(dwError=OpenSubKeyByIndex(hkLevel1,dwIndex2,KEY_READ,&hkLevel2)){
          if(dwError==ERROR_NO_MORE_ITEMS){
            dwError=0;
            break;
          }
          else goto end;
        }

        /* Look if the driver class is the one we're looking for.
         * We accept either "CLASS" or "CLASSGUID" as identifiers.
         * No need to dynamically arrange for space to retrieve the values,
         * they must have the same length as the strings they're compared to
         * if the comparison is to be succesful.
         */

        cbClass=sizeof(lpClass);
        if(RegQueryValueEx(hkLevel2,TEXT("CLASS"),NULL,NULL,
                           (LPBYTE)lpClass,&cbClass)==ERROR_SUCCESS&&
           _tcsicmp(lpClass,lpstrPortsClass)==0){
          /* ok */
        }
        else{
          cbClassGUID=sizeof(lpClassGUID);
          if(RegQueryValueEx(hkLevel2,TEXT("CLASSGUID"),NULL,NULL,
                             (LPBYTE)lpClassGUID,&cbClassGUID)==ERROR_SUCCESS&&
             _tcsicmp(lpClassGUID,lpstrPortsClassGUID)==0){
            /* ok */
          }
          else continue;
        }

        /* get "PORTNAME" */

        dwError=QueryStringValue(hkLevel2,TEXT("PORTNAME"),&lpPortName);
        if(dwError==ERROR_FILE_NOT_FOUND){
          /* In Win200, "PORTNAME" is located under the subkey "DEVICE PARAMETERS".
           * Try and look there.
           */

          if(hkDeviceParameters!=NULL){
            RegCloseKey(hkDeviceParameters);
            hkDeviceParameters=NULL;
          }
          if(RegOpenKeyEx(hkLevel2,TEXT("DEVICE PARAMETERS"),0,KEY_READ,
                          &hkDeviceParameters)==ERROR_SUCCESS){
             dwError=QueryStringValue(hkDeviceParameters,TEXT("PORTNAME"),&lpPortName);
          }
        }
        if(dwError){
          if(dwError==ERROR_FILE_NOT_FOUND){ 
            /* boy that was strange, we better skip this device */
            dwError=0;
            continue;
          }
          else goto end;
        }
         //printf("found port, name %ls\n", lpPortName);

        /* check if it is a serial port (instead of, say, a parallel port) */

        if(_tcsncmp(lpPortName,TEXT("COM"),3)!=0)continue;

        /* now go for "FRIENDLYNAME" */

        if(dwError=QueryStringValue(hkLevel2,TEXT("FRIENDLYNAME"),&lpFriendlyName)){
          if(dwError==ERROR_FILE_NOT_FOUND){
            bFriendlyNameNotFound=TRUE;
            dwError=0;
          }
          else goto end;
        }
        
        /* Assemble the information and pass it on to the callback.
         * In the unlikely case there's no friendly name available,
         * use port name instead.
         */
        portinfo.lpPortName=lpPortName;
        portinfo.lpFriendlyName=bFriendlyNameNotFound?lpPortName:lpFriendlyName;
		{
			//printf( "Friendly name: %ls\n", portinfo.lpFriendlyName );
			if (!_tcsncmp(TEXT("Make Controller Kit"), portinfo.lpFriendlyName, 19))
			{
				TCHAR* pname;
				pname = _tcsdup(portinfo.lpPortName);
				//messageInterface->message( 1, "Found matching registry entry...\n" );
				// We've found a matching entry in the registry...
				// Now see if it's actually there by trying to open it
				int result = testOpen( pname );
				// if it is, store it
				if( result == 0 )
					openPorts[ openCount++ ] = pname; 
			}
        }
      }
  }
  goto end;

end:
  free(lpFriendlyName);
  free(lpPortName);
  if(hkDeviceParameters!=NULL)RegCloseKey(hkDeviceParameters);
  if(hkLevel2!=NULL)          RegCloseKey(hkLevel2);
  if(hkLevel1!=NULL)          RegCloseKey(hkLevel1);
  if(hkEnum!=NULL)            RegCloseKey(hkEnum);
  if(dwError!=0)
  {
    SetLastError(dwError);
    return 0; //TELEO_E_UNKNOWN;
  }
  else return openCount; //TELEO_OK;
}
/* --- PRIVATE FUNCTIONS ---------------------------------------------------- */
static void CallbackBuildDnCache(
	_In_ CSV_HANDLE hOutfile,
	_In_ CSV_HANDLE hDenyOutfile,
	_In_ LPTSTR *tokens
) {
	BOOL bResult = FALSE;
	CACHE_OBJECT_BY_DN cacheEntry = { 0 };
	CACHE_OBJECT_BY_DN mailCacheEntry = { 0 };
	PCACHE_OBJECT_BY_DN inserted = NULL;
	BOOL newElement = FALSE;
	LPTSTR objectClass = NULL;

	UNREFERENCED_PARAMETER(hDenyOutfile);

	if (STR_EMPTY(tokens[LdpListDn]) || STR_EMPTY(tokens[LdpListObjectClass]))
		return;

	cacheEntry.dn = _tcsdup(tokens[LdpListDn]);
	if (!cacheEntry.dn)
		FATAL(_T("Could not dup dn <%s>"), tokens[LdpListDn]);

	cacheEntry.objectClass = _tcsdup(tokens[LdpListObjectClass]);
	if (!cacheEntry.objectClass)
		FATAL(_T("Could not dup objectClass <%s>"), tokens[LdpListObjectClass]);

	CacheEntryInsert(
		ppCache,
		(PVOID)&cacheEntry,
		sizeof(CACHE_OBJECT_BY_DN),
		&inserted,
		&newElement
	);
	if (!inserted) {
		LOG(Err, _T("cannot insert new object-by-dn cache entry <%s>"), tokens[LdpListDn]);
	}
	else if (!newElement) {
		LOG(Dbg, _T("object-by-dn cache entry is not new <%s>"), tokens[LdpListDn]);
		free(cacheEntry.dn);
		free(cacheEntry.objectClass);
	}
	else {
		objectClass = _tcsrchr(tokens[LdpListObjectClass], _T(';')) + 1;
		bResult = ControlWriteOutline(hOutfile, tokens[LdpListDn], objectClass, CONTROL_ALLNODES_KEYWORD);
		if (!bResult)
			LOG(Err, _T("Cannot write outline for <%s>"), tokens[LdpListDn]);
	}

	// Writing Mail attributes as object of type email
	if (STR_EMPTY(tokens[LdpListMail]))
		return;

	mailCacheEntry.dn = _tcsdup(tokens[LdpListMail]);
	if (!mailCacheEntry.dn)
		FATAL(_T("Could not dup dn <%s>"), tokens[LdpListMail]);

	mailCacheEntry.objectClass = _tcsdup(_T("email"));
	if (!mailCacheEntry.objectClass)
		FATAL(_T("Could not dup objectClass <%s>"), _T("email"));

	CacheEntryInsert(
		ppCache,
		(PVOID)&mailCacheEntry,
		sizeof(CACHE_OBJECT_BY_DN),
		&inserted,
		&newElement
	);
	if (!inserted) {
		LOG(Err, _T("cannot insert new object-by-dn cache entry <%s>"), tokens[LdpListMail]);
	}
	else if (!newElement) {
		LOG(Dbg, _T("object-by-dn cache entry is not new <%s>"), tokens[LdpListMail]);
		free(mailCacheEntry.dn);
		free(mailCacheEntry.objectClass);
	}
	else {
		bResult = ControlWriteOutline(hOutfile, tokens[LdpListMail], _T("email"), CONTROL_ALLNODES_KEYWORD);
		if (!bResult)
			LOG(Err, _T("Cannot write outline for <%s>"), tokens[LdpListMail]);
	}

}
Exemplo n.º 19
0
/*
 * Copy settings into a print dialog & any devmode
 */
BOOL AwtPrintControl::InitPrintDialog(JNIEnv *env,
                                      jobject printCtrl, PRINTDLG &pd) {
    HWND hwndOwner = NULL;
    jobject dialogOwner =
        env->GetObjectField(printCtrl, AwtPrintControl::dialogOwnerPeerID);
    if (dialogOwner != NULL) {
        AwtComponent *dialogOwnerComp =
          (AwtComponent *)JNI_GET_PDATA(dialogOwner);

        hwndOwner = dialogOwnerComp->GetHWnd();
        env->DeleteLocalRef(dialogOwner);
        dialogOwner = NULL;
    }
    jobject mdh = NULL;
    jobject dest = NULL;
    jobject select = NULL;
    jobject dialog = NULL;
    LPTSTR printName = NULL;
    LPTSTR portName = NULL;

    // If the user didn't specify a printer, then this call returns the
    // name of the default printer.
    jstring printerName = (jstring)
      env->CallObjectMethod(printCtrl, AwtPrintControl::getPrinterID);

    if (printerName != NULL) {

        pd.hDevMode = AwtPrintControl::getPrintHDMode(env, printCtrl);
        pd.hDevNames = AwtPrintControl::getPrintHDName(env, printCtrl);

        LPTSTR getName = (LPTSTR)JNU_GetStringPlatformChars(env,
                                                      printerName, NULL);

        BOOL samePrinter = FALSE;

        // check if given printername is same as the currently saved printer
        if (pd.hDevNames != NULL ) {

            DEVNAMES *devnames = (DEVNAMES *)::GlobalLock(pd.hDevNames);
            if (devnames != NULL) {
                LPTSTR lpdevnames = (LPTSTR)devnames;
                printName = lpdevnames+devnames->wDeviceOffset;

                if (!_tcscmp(printName, getName)) {

                    samePrinter = TRUE;
                    printName = _tcsdup(lpdevnames+devnames->wDeviceOffset);
                    portName = _tcsdup(lpdevnames+devnames->wOutputOffset);

                }
            }
            ::GlobalUnlock(pd.hDevNames);
        }

        if (!samePrinter) {
            LPTSTR foundPrinter = NULL;
            LPTSTR foundPort = NULL;
            DWORD cbBuf = 0;
            VERIFY(AwtPrintControl::FindPrinter(NULL, NULL, &cbBuf,
                                                NULL, NULL));
            LPBYTE buffer = new BYTE[cbBuf];

            if (AwtPrintControl::FindPrinter(printerName, buffer, &cbBuf,
                                             &foundPrinter, &foundPort) &&
                (foundPrinter != NULL) && (foundPort != NULL)) {

                printName = _tcsdup(foundPrinter);
                portName = _tcsdup(foundPort);

                if (!AwtPrintControl::CreateDevModeAndDevNames(&pd,
                                                   foundPrinter, foundPort)) {
                    delete [] buffer;
                    if (printName != NULL) {
                      free(printName);
                    }
                    if (portName != NULL) {
                      free(portName);
                    }
                    return FALSE;
                }

                DASSERT(pd.hDevNames != NULL);
            } else {
                delete [] buffer;
                if (printName != NULL) {
                  free(printName);
                }
                if (portName != NULL) {
                  free(portName);
                }
                return FALSE;
            }

            delete [] buffer;
        }
        // PrintDlg may change the values of hDevMode and hDevNames so we
        // re-initialize our saved handles.
        AwtPrintControl::setPrintHDMode(env, printCtrl, NULL);
        AwtPrintControl::setPrintHDName(env, printCtrl, NULL);
    } else {

        // There is no default printer. This means that there are no
        // printers installed at all.

        if (printName != NULL) {
          free(printName);
        }
        if (portName != NULL) {
          free(portName);
        }
        // Returning TRUE means try to display the native print dialog
        // which will either display an error message or prompt the
        // user to install a printer.
        return TRUE;
    }

    // Now, set-up the struct for the real calls to ::PrintDlg and ::CreateDC

    pd.hwndOwner = hwndOwner;
    pd.Flags = PD_ENABLEPRINTHOOK | PD_RETURNDC;
    pd.lpfnPrintHook = (LPPRINTHOOKPROC)PrintDlgHook;

    if (env->CallBooleanMethod(printCtrl, AwtPrintControl::getCollateID)) {
        pd.Flags |= PD_COLLATE;
    }

    pd.nCopies = (WORD)env->CallIntMethod(printCtrl,
                                          AwtPrintControl::getCopiesID);
    pd.nFromPage = (WORD)env->CallIntMethod(printCtrl,
                                            AwtPrintControl::getFromPageID);
    pd.nToPage = (WORD)env->CallIntMethod(printCtrl,
                                          AwtPrintControl::getToPageID);
    pd.nMinPage = (WORD)env->CallIntMethod(printCtrl,
                                           AwtPrintControl::getMinPageID);
    jint maxPage = env->CallIntMethod(printCtrl,
                                      AwtPrintControl::getMaxPageID);
    pd.nMaxPage = (maxPage <= (jint)((WORD)-1)) ? (WORD)maxPage : (WORD)-1;

    if (env->CallBooleanMethod(printCtrl,
                               AwtPrintControl::getDestID)) {
      pd.Flags |= PD_PRINTTOFILE;
    }

    jint selectType = env->CallIntMethod(printCtrl,
                                         AwtPrintControl::getSelectID);

    // selectType identifies whether No selection (2D) or
    // SunPageSelection (AWT)
    if (selectType != 0) {
      pd.Flags |= selectType;
    }

    if (!env->CallBooleanMethod(printCtrl,
                                AwtPrintControl::getPrintToFileEnabledID)) {
      pd.Flags |= PD_DISABLEPRINTTOFILE;
    }

    if (pd.hDevMode != NULL) {
      DEVMODE *devmode = (DEVMODE *)::GlobalLock(pd.hDevMode);
      DASSERT(!IsBadWritePtr(devmode, sizeof(DEVMODE)));

      devmode->dmFields |= DM_COPIES | DM_COLLATE | DM_ORIENTATION |
          DM_PAPERSIZE | DM_PRINTQUALITY | DM_COLOR | DM_DUPLEX;

      devmode->dmCopies = pd.nCopies;

      jint orient = env->CallIntMethod(printCtrl,
                                       AwtPrintControl::getOrientID);
      if (orient == 0) {
        devmode->dmOrientation = DMORIENT_LANDSCAPE;
      } else if (orient == 1) {
        devmode->dmOrientation = DMORIENT_PORTRAIT;
      }

      devmode->dmCollate = (pd.Flags & PD_COLLATE) ? DMCOLLATE_TRUE
        : DMCOLLATE_FALSE;

      int quality = env->CallIntMethod(printCtrl,
                                       AwtPrintControl::getQualityID);
      if (quality) {
        devmode->dmPrintQuality = quality;
      }

      int color = env->CallIntMethod(printCtrl,
                                     AwtPrintControl::getColorID);
      if (color) {
        devmode->dmColor = color;
      }

      int sides = env->CallIntMethod(printCtrl,
                                     AwtPrintControl::getSidesID);
      if (sides) {
        devmode->dmDuplex = (int)sides;
      }

      jintArray obj = (jintArray)env->CallObjectMethod(printCtrl,
                                       AwtPrintControl::getWin32MediaID);
      jboolean isCopy;
      jint *wid_ht = env->GetIntArrayElements(obj,
                                              &isCopy);

      double newWid = 0.0, newHt = 0.0;
      if (wid_ht != NULL && wid_ht[0] != 0 && wid_ht[1] != 0) {
        devmode->dmPaperSize = AwtPrintControl::getNearestMatchingPaper(
                                             printName,
                                             portName,
                                             (double)wid_ht[0],
                                             (double)wid_ht[1],
                                             &newWid, &newHt);

      }
      env->ReleaseIntArrayElements(obj, wid_ht, 0);
      ::GlobalUnlock(pd.hDevMode);
      devmode = NULL;
    }

    if (printName != NULL) {
      free(printName);
    }
    if (portName != NULL) {
      free(portName);
    }

    return TRUE;
}
Exemplo n.º 20
0
// deprecated - remove once a registry-free version of Safari has shipped (first major version after 3.1.1)
static void registerWebKitNightly()
{
    // look up server's file name
    TCHAR szFileName[MAX_PATH];
    GetModuleFileName(gInstance, szFileName, MAX_PATH);

    typedef HRESULT (WINAPI *RegisterTypeLibForUserPtr)(ITypeLib*, OLECHAR*, OLECHAR*);
    COMPtr<ITypeLib> typeLib;
    LoadTypeLibEx(szFileName, REGKIND_NONE, &typeLib);
    if (RegisterTypeLibForUserPtr registerTypeLibForUser = reinterpret_cast<RegisterTypeLibForUserPtr>(GetProcAddress(GetModuleHandle(TEXT("oleaut32.dll")), "RegisterTypeLibForUser")))
        registerTypeLibForUser(typeLib.get(), szFileName, 0);
    else
        RegisterTypeLib(typeLib.get(), szFileName, 0);

    HKEY userClasses;
    if (RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("SOFTWARE\\CLASSES"), 0, KEY_WRITE, &userClasses) != ERROR_SUCCESS)
        userClasses = 0;

    // register entries from table
    int nEntries = ARRAYSIZE(gRegTable);
    HRESULT hr = S_OK;
    for (int i = 0; SUCCEEDED(hr) && i < nEntries; i++) {
        LPTSTR pszKeyName   = _tcsdup(gRegTable[i][0]);
        LPTSTR pszValueName = gRegTable[i][1] ? _tcsdup(gRegTable[i][1]) : 0;
        LPTSTR allocatedValue   = (gRegTable[i][2] != (LPTSTR)-1) ? _tcsdup(gRegTable[i][2]) : (LPTSTR)-1;
        LPTSTR pszValue     = allocatedValue;

        if (pszKeyName && pszValue) {

            int clsidIndex = i/gSlotsPerEntry;
            substituteGUID(pszKeyName, &gRegCLSIDs[clsidIndex]);
            substituteGUID(pszValueName, &gRegCLSIDs[clsidIndex]);

            // map rogue value to module file name
            if (pszValue == (LPTSTR)-1)
                pszValue = szFileName;
            else
                substituteGUID(pszValue, &gRegCLSIDs[clsidIndex]);

            // create the key
            HKEY hkey;
            LONG err = RegCreateKey(HKEY_CLASSES_ROOT, pszKeyName, &hkey);
            if (err != ERROR_SUCCESS && userClasses)
                err = RegCreateKey(userClasses, pszKeyName, &hkey);
            if (err == ERROR_SUCCESS) {
                // set the value
                err = RegSetValueEx(hkey, pszValueName, 0, REG_SZ, (const BYTE*)pszValue, (DWORD) sizeof(pszValue[0])*(_tcslen(pszValue) + 1));
                RegCloseKey(hkey);
            }
        }
        if (pszKeyName)
            free(pszKeyName);
        if (pszValueName)
            free(pszValueName);
        if (allocatedValue && allocatedValue != (LPTSTR)-1)
            free(allocatedValue);
    }

    if (userClasses)
        RegCloseKey(userClasses);
}
Exemplo n.º 21
0
// Split a string usinf a particular delimiter, split result are copied into lpBuffer
// in the "double null terminated string" format as the following figure shows:
// xxx\0xxxx\0xx\0xxx\0\0
//
// For example, if the delimiter is ",", then string "ab,cd,e" will be
// splitted into "ab\0cd\0e\0\0", this string format can be parsed into an array
// of sub strings easily using user defined functions or SFIni::ParseStringArray.
DWORD SFIni::__StringSplit(LPCTSTR lpString, LPTSTR lpBuffer, DWORD dwBufSize, LPCTSTR lpDelimiter, BOOL bTrimString)
{
	if (lpString == NULL || lpBuffer == NULL || dwBufSize == 0)
		return 0;	

	DWORD dwCopied = 0;
	*lpBuffer = _T('\0');
	if (*lpString == _T('\0'))
		return 0;

	// If lpDelimiter is NULL, use the default delimiter ",", if delimiter length
	// is 0, then return whole string
	if (lpDelimiter != NULL && *lpDelimiter == _T('\0'))
	{
		_tcsncpy(lpBuffer, lpString, dwBufSize - 1);
		return _tcslen(lpBuffer);
	}

	LPTSTR pszDel = (lpDelimiter == NULL) ? _tcsdup(DEF_PROFILE_DELIMITER) : _tcsdup(lpDelimiter);
	const DWORD DEL_LEN = _tcslen(pszDel);
	LPTSTR lpTarget = lpBuffer;

	// Search through lpString for delimiter matches, and extract sub strings out
	LPCTSTR lpPos = lpString;
	LPCTSTR lpEnd = _tcsstr(lpPos, pszDel);

	while (lpEnd != NULL)
	{
		LPTSTR pszSeg = __StrDupEx(lpPos, lpEnd);
		if (bTrimString)
			__TrimString(pszSeg);

		const DWORD SEG_LEN = _tcslen(pszSeg);
		const DWORD COPY_LEN = min(SEG_LEN, dwBufSize - dwCopied);

		// Need to avoid buffer overflow
		if (COPY_LEN > 0)
		{
			dwCopied += COPY_LEN + 1;
			_tcsncpy(lpTarget, pszSeg, COPY_LEN);
			lpTarget[COPY_LEN] = _T('\0');
			lpTarget = &lpTarget[SEG_LEN + 1];
		}
		delete [] pszSeg;
		lpPos = &lpEnd[DEL_LEN]; // Advance the pointer for next search		
		lpEnd = _tcsstr(lpPos, pszDel);
	}

	// The last part of string, there may not be the trailing delimiter, so we
	// need to take care of this part, too
	LPTSTR pszSeg = _tcsdup(lpPos);
	if (bTrimString)
		__TrimString(pszSeg);

	const DWORD SEG_LEN = _tcslen(pszSeg);
	const DWORD COPY_LEN = min(SEG_LEN, dwBufSize - dwCopied);

	if (COPY_LEN > 0)
	{
		dwCopied += COPY_LEN + 1;
		_tcsncpy(lpTarget, pszSeg, COPY_LEN);
		lpTarget[COPY_LEN] = _T('\0');
	}

	delete [] pszSeg;
	lpBuffer[dwCopied] = _T('\0');
	delete [] pszDel;
	return dwCopied;
}
Exemplo n.º 22
0
void QueryDlg::OnBnClickedButtonSale()
{
	// TODO:  在此添加控件通知处理程序代码
	TCHAR* old_locale = _tcsdup(_tsetlocale(LC_CTYPE, NULL));
	_tsetlocale(LC_CTYPE, _T("chs"));

	UpdateData(TRUE);

	CString str;
	int lineSelect = -1;
	for (int i = 0; i<m_listCtrl_Query.GetItemCount(); i++)
	{
		if (m_listCtrl_Query.GetItemState(i, LVIS_SELECTED) == LVIS_SELECTED)
		{
			lineSelect = i;
		}
	}
	CString idSelect = m_listCtrl_Query.GetItemText(lineSelect, 0);
	
	//读取文件
	CStdioFile csf_read(_T("res/ticketInfo.txt"), CStdioFile::modeCreate | CStdioFile::modeNoTruncate | CStdioFile::modeRead);
	CString trainInfos[10000];
	int num = 0;
	while (csf_read.ReadString(trainInfos[num]))
	{
		num++;
	}
	csf_read.Close();
	
	//判断是否可以买票
	for (int i = 0; i < num; i++)
	{
		CString *com = splitS(trainInfos[i]);

		if (com[0] == idSelect)
		{
			int numOfPassenger = _ttoi(com[5]);
			int ticketOrdered = _ttoi(com[6]);
			//如果余票足够并且没有超过时间,更新购票人数
			if (myOverTime(com[1]))
			{
				MessageBox(_T("所购买的班次已经发车!\n请重新选购~"));
				return;
			}
			if (ticketOrdered + m_edit_ticket_num <= numOfPassenger&&!myOverTime(com[1]))
			{
				ticketOrdered += m_edit_ticket_num;
				com[6].Format(_T("%d"), ticketOrdered);
				trainInfos[i]= cat(com);
				//写回文件


				CStdioFile  csf_write( _T("res/ticketInfo.txt"), CStdioFile::modeCreate | CStdioFile::modeNoTruncate | CStdioFile::modeReadWrite);
				for (int j = 0; j < num; j++)
				{
					csf_write.WriteString(trainInfos[j]+"\n");
				}
				csf_write.Flush();
				csf_write.Close();
				CString csBuy;
				csBuy.Format(_T("%d"), m_edit_ticket_num);
				MessageBox(csBuy + _T("张票购买成功!"));
				return;
			}
			else if (numOfPassenger<ticketOrdered)
			{
				MessageBox(_T("购票数量太多,请重新输入"));
				return;
			}
			else
			{
				MessageBox(_T("已经没有余票!=_="));
				return;
			}
		}
	}

	_tsetlocale(LC_CTYPE, old_locale);
	free(old_locale);
}
Exemplo n.º 23
0
void CCKAHUMTESTUI2Dlg::AddStringToLog (LPCTSTR string)
{
	PostMessage (WM_USER_DELAYEDLOG, (WPARAM)_tcsdup (string), 0);
}
Exemplo n.º 24
0
void QueryDlg::OnBnClickedButtonQuery()
{
	// TODO:  在此添加控件通知处理程序代码
	UpdateData(TRUE);
	//处理中文
	TCHAR* old_locale = _tcsdup(_tsetlocale(LC_CTYPE, NULL));
	_tsetlocale(LC_CTYPE, _T("chs"));

	if (!hasViewList)
	{
		CRect rect;
		m_listCtrl_Query.GetClientRect(rect);
		CString title[8] = { _T("班次"), _T("发车时间"), _T("起点站"), _T("终点站"), _T("行车时间"), _T("额定载量"), _T("已订票人数"), _T("状态") };

		for (int i = 0; i < 8; i++)
		{
			m_listCtrl_Query.InsertColumn(i, title[i], 0, rect.Width() / 8, i);
		}
	}
	if (hasViewList)
		m_listCtrl_Query.DeleteAllItems();


	CStdioFile csf_read(_T("res/ticketInfo.txt"), CStdioFile::modeCreate | CStdioFile::modeNoTruncate | CStdioFile::modeReadWrite);
	int numOfline = 0;
	csf_read.SeekToBegin();
	CString trainInfo[10000];
	while ((csf_read.ReadString(trainInfo[numOfline])))
	{
		numOfline++;
	}
	csf_read.Close();//文件读取结束,关闭
	//查找与查询内容相符合的输出到listCtr
	int kl = 0;
	for (int i = 0; i < numOfline; i++)
	{
		CString *com = splitS(trainInfo[i]);
		if (com[0] == m_edit_txt_query || com[3] == m_edit_txt_query)
		{
			m_listCtrl_Query.InsertItem(kl, com[0]);
			
			for (int j = 1; j < 7; j++)
			{
				m_listCtrl_Query.SetItemText(kl, j, com[j]);
			}
			if (myOverTime(com[1]))
				m_listCtrl_Query.SetItemText(kl, 7, _T("已发车!"));
			else
			{
				m_listCtrl_Query.SetItemText(kl, 7, _T("未发出"));
			}
			kl++;
		}
	}
	if (kl == 0)
		MessageBox(_T("未查询到结果!"));
	//始终高亮度被选中的表项
	m_listCtrl_Query.ModifyStyle(0L, LVS_SHOWSELALWAYS);
	m_listCtrl_Query.SetExtendedStyle(LVS_EX_FULLROWSELECT);

	hasViewList = true;
	
	_tsetlocale(LC_CTYPE, old_locale);
	free(old_locale);
}
Exemplo n.º 25
0
CFGDATA::
CFGDATA()
{
    m_DebugMode = enumLOCAL_USERMODE;
    
    m_bUsingCfgFile = FALSE;
    
    m_bRunningOnHost = TRUE;
    m_bDisplaySummaryInfo = FALSE;
    m_bLaunchNewProcess = TRUE;
    m_pszExecutableName = NULL;
    m_bAdvancedInterface = TRUE;
    
    m_dwServicePack = 0;
    
    m_pszDumpFileName = _tcsdup(_T("%systemroot%\\memory.dmp"));
    m_pszShortCutName = NULL;
    
    //
    // Sym stuff
    m_pszDestinationPath = NULL;    
    
    m_bCopyOS_SymPath = FALSE;
    m_pszOS_SymPath = NULL;
    m_pszOS_VolumeLabel_SymPath = NULL;
    m_uOS_DriveType_SymPath = DRIVE_UNKNOWN;

    m_bCopySP_SymPath = FALSE;
    m_pszSP_SymPath = NULL;
    m_pszSP_VolumeLabel_SymPath = NULL;
    m_uSP_DriveType_SymPath = DRIVE_UNKNOWN;

    m_bCopyHotFix_SymPath = FALSE;
    m_pszHotFix_SymPath = NULL;
    m_pszHotFix_VolumeLabel_SymPath = NULL;
    m_uHotFix_DriveType_SymPath = DRIVE_UNKNOWN;

    m_bCopyAdditional_SymPath = FALSE;


   
    m_pszDeskTopShortcut_FullPath = NULL;

    m_pszHotFixes = NULL;
    
    ZeroMemory(m_szInstallSrcPath, sizeof(m_szInstallSrcPath));
    
    //
    // Where does DbgWiz.exe live?
    {
        ZeroMemory(m_szWizInitialDir, sizeof(m_szWizInitialDir));
        
        char szPath[_MAX_PATH] = {0};
        PSTR pszFilePart = NULL;
        
        Assert(SearchPath(NULL, "dbgwiz", ".exe", 
            sizeof(szPath), szPath, &pszFilePart));
        
        Assert(pszFilePart);
        *pszFilePart = NULL;
        
        strcpy(m_szWizInitialDir, szPath); 
    }
    
    m_bSerial = TRUE;
    m_dwBaudRate = 0;
    m_pszCommPortName = NULL;
    m_pszCompName = NULL;
    m_pszPipeName = NULL;
    
    ZeroMemory(&m_si, sizeof(m_si));
    GetSystemInfo(&m_si);
    
    {
        HKEY hkey = NULL;
        PSTR pszKeyPath = NULL;
        PSTR pszRegValue = NULL;
        
        ZeroMemory(&m_osi, sizeof(m_osi));
        m_osi.dwOSVersionInfoSize = sizeof(m_osi);
        Assert(GetVersionEx(&m_osi));
        
        // Detect from where the OS was installed
        if (VER_PLATFORM_WIN32_NT == m_osi.dwPlatformId) {
            // NT
            pszKeyPath = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion";
            pszRegValue = "SourcePath";
        } else if (VER_PLATFORM_WIN32_WINDOWS == m_osi.dwPlatformId) {
            // Figure out what version of win9x we're using
            if (0 == m_osi.dwMinorVersion) {
                pszKeyPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion";
                pszRegValue = "AppinstallPath";
            } else if (10 == m_osi.dwMinorVersion) {
                pszKeyPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup";
                pszRegValue = "SourcePath";
            } else {
                WKSP_MsgBox(NULL, IDS_ERROR_UNSUPPORTED_OS);
            }
        } else {
            // Something else
            WKSP_MsgBox(NULL, IDS_ERROR_UNSUPPORTED_OS);
        }
        
        
        Assert(ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE,
            pszKeyPath, 0, KEY_READ, &hkey));
        if (hkey) {
            DWORD dwSize = sizeof(m_szInstallSrcPath);
            DWORD dwType = REG_EXPAND_SZ;
            Assert(ERROR_SUCCESS == RegQueryValueEx(hkey, pszRegValue, NULL, &dwType,
                (PUCHAR) m_szInstallSrcPath, &dwSize));
            
            Assert(ERROR_SUCCESS == RegCloseKey(hkey));
        }
        
        //
        // Get the hot fixes. Concat hotfixes into a list that looks like:
        //  "Qxxxx, Qxxxx, Qxxxx, Qxxxx"
        //        
        if (VER_PLATFORM_WIN32_NT == m_osi.dwPlatformId) {
            if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE,
                "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix", 0, KEY_READ, &hkey)) {

                DWORD dwMaxKeyNameLen = 0;
                DWORD dwNumSubKeys = 0;
                PSTR pszBigBuffer = NULL;
                PSTR pszNameBuffer = NULL;
            
                WKSP_RegKeyValueInfo(hkey, &dwNumSubKeys, NULL, &dwMaxKeyNameLen, NULL);

                // Make it bigger. Bigger is safer.
                dwMaxKeyNameLen += 2;
            
                pszNameBuffer = (PSTR) calloc(dwMaxKeyNameLen, 1);
                pszBigBuffer = (PSTR) calloc(dwMaxKeyNameLen * dwNumSubKeys 
                    // Factor in the space required for each ", " between the hotfixes
                    + (dwNumSubKeys -1) * 2, 1);
            
                if (pszNameBuffer && pszBigBuffer) {
                    // So far so good, get each entry
                    for (DWORD dw=0; dw<dwNumSubKeys; dw++) {
                        DWORD dwSize = dwMaxKeyNameLen;
                        WKSP_RegGetKeyName(hkey, dw, pszNameBuffer, &dwSize);
                    
                        // concat the list
                        strcat(pszBigBuffer, pszNameBuffer);
                        if (dw < dwNumSubKeys-1) {
                            strcat(pszBigBuffer, ", ");
                        }
                    }
                
                    m_pszHotFixes = NT4SafeStrDup(pszBigBuffer);
                }
            
                if (pszNameBuffer) {
                   free(pszNameBuffer);
                }
                if (pszBigBuffer) {
                   free(pszBigBuffer);
                }

                Assert(ERROR_SUCCESS == RegCloseKey(hkey));
            }
        }
    }
    
    //
    // debug: free/checked: 
    if (VER_PLATFORM_WIN32_NT == m_osi.dwPlatformId) {
        HKEY hkey = NULL;
        char sz[_MAX_PATH] = {0};
        DWORD dwType;
        DWORD dwSize = sizeof(sz);
        
        Assert(ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE,
            "Software\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_READ, &hkey));
        
        Assert(ERROR_SUCCESS == RegQueryValueEx(hkey, "CurrentType", NULL, &dwType,
            (PUCHAR) sz, &dwSize));
        
        Assert(ERROR_SUCCESS == RegCloseKey(hkey));
        
        PSTR psz = strtok(sz, " ");
        Assert(psz);
        psz = strtok(NULL, " ");
        
        if (!_stricmp(psz, "Free")) {
            m_pszFreeCheckedBuild = WKSP_DynaLoadString(g_hInst, IDS_OS_DESC_FREE);
        } else if (!_stricmp(psz, "Checked")) {
            m_pszFreeCheckedBuild = WKSP_DynaLoadString(g_hInst, IDS_OS_DESC_CHECKED);
        } else {
            m_pszFreeCheckedBuild = WKSP_DynaLoadString(g_hInst, IDS_UNKNOWN);
        }
    }
    
    
    DoNotUseCfgFile();    
    GuessAtSymSrc();
}
DWORD COpenALSoundUtility::OnLoadSoundDatabase(DWORD size, void* param)
{
	VERIFY_MESSAGE_SIZE(size, sizeof(IHashString));
	IHashString *dbFileName = (IHashString*) param;

	if ((dbFileName != NULL) && (_tcscmp(dbFileName->GetString(), _T("")) != 0))
	{
		TCHAR *fileName = _tcsdup(dbFileName->GetString());
		LOADFILEEXTPARAMS lfep;
		lfep.fileName = fileName;
		lfep.bInternalLoad = true;

		static DWORD msgLoadFileByExtension = CHashString(_T("LoadFileByExtension")).GetUniqueID();
		DWORD retval = m_ToolBox->SendMessage(msgLoadFileByExtension, sizeof(LOADFILEEXTPARAMS), &lfep);
		free( fileName );
		if (retval == MSG_HANDLED)
		{
			// clear prior sound list - not additive, exclusive!
			m_SoundMap.clear();
			
			CHashString hsSoundDBObject;
			DATABASEINFO dbi;
			dbi.m_FileName = dbFileName;
			static DWORD msgGetDatabase = CHashString(_T("GetDatabase")).GetUniqueID();
			retval = m_ToolBox->SendMessage(msgGetDatabase, sizeof(DATABASEINFO), &dbi);
			if (retval == MSG_HANDLED)
			{
				hsSoundDBObject.Init(dbi.m_DatabaseName->GetString());
				DATABASEATTRIBUTEPARAMS dap;
				CREATEARCHIVE ca;
				static CHashString memType(_T("Memory"));

				ca.mode = STREAM_MODE_WRITE | STREAM_MODE_READ;
				ca.streamData = NULL;
				ca.streamSize = 0;
				ca.streamType = &memType;
				static DWORD msgHash_CreateArchive = CHashString(_T("CreateArchive")).GetUniqueID();
				m_ToolBox->SendMessage(msgHash_CreateArchive, sizeof(CREATEARCHIVE), &ca);

				IArchive *attribArchive = ca.archive;
				if (attribArchive == NULL)
				{
					m_ToolBox->Log(LOGERROR, _T("Sound manager: archive is null; could not get sound attributes!\n\tNo sounds loaded!\n"));
					return MSG_ERROR;
				}

				dap.m_AttributeArchive = attribArchive;

				static DWORD msgGetAttribute = CHashString(_T("GetAttribute")).GetUniqueID();
				static CHashString hsKeyString(_T("KeyString"));
				static CHashString hsFileName(_T("FileName"));
				static CHashString hsGlobalVolume(_T("GlobalVolume"));
				static CHashString hsCachedUncompressed(_T("CacheUncompressed"));

				static CHashString hsDBType(_T("CDefinedDatabase"));
				for (UINT i=0; i<(UINT)dbi.m_nItems; i++)
				{
					// get key string
					attribArchive->SeekTo(0, SEEK_SET);
					dap.m_Index = i;
					dap.m_AttributeName = &hsKeyString;
					retval = m_ToolBox->SendMessage(msgGetAttribute, sizeof(DATABASEATTRIBUTEPARAMS), &dap, &hsSoundDBObject, &hsDBType);
					if (retval != MSG_HANDLED)
					{
						m_ToolBox->Log(LOGERROR, _T("Sound manager: could not get key attribute for row %d; sounds not fully loaded!\n"), i);
						attribArchive->Close();
						return MSG_ERROR;
					}

					CHashString hsKey;
					StdString szKey;
					attribArchive->SetIsWriting(false);
					attribArchive->Read(szKey);
					hsKey = szKey;

					// get filename
					attribArchive->SeekTo(0, SEEK_SET);
					dap.m_AttributeName = &hsFileName;
					retval = m_ToolBox->SendMessage(msgGetAttribute, sizeof(DATABASEATTRIBUTEPARAMS), &dap, &hsSoundDBObject, &hsDBType);
					if (retval != MSG_HANDLED)
					{
						m_ToolBox->Log(LOGERROR, _T("Sound manager: could not get file attribute for row %d; sounds not fully loaded!\n"), i);
						attribArchive->Close();
						return MSG_ERROR;
					}

					CHashString hsFile;
					StdString szFile;
					attribArchive->SetIsWriting(false);
					attribArchive->Read(szFile);
					szFile.tolower();
					hsFile = szFile;

					// get volume
					attribArchive->SeekTo(0, SEEK_SET);
					dap.m_AttributeName = &hsGlobalVolume;
					retval = m_ToolBox->SendMessage(msgGetAttribute, sizeof(DATABASEATTRIBUTEPARAMS), &dap, &hsSoundDBObject, &hsDBType);
					if (retval != MSG_HANDLED)
					{
						m_ToolBox->Log(LOGERROR, _T("Sound manager: could not get volume attribute for row %d; sounds not fully loaded!\n"), i);
						attribArchive->Close();
						return MSG_ERROR;
					}

					float fVolume;
					attribArchive->SetIsWriting(false);
					attribArchive->Read(fVolume);

					// get cached attribute
					attribArchive->SeekTo(0, SEEK_SET);
					dap.m_AttributeName = &hsCachedUncompressed;
					retval = m_ToolBox->SendMessage(msgGetAttribute, sizeof(DATABASEATTRIBUTEPARAMS), &dap, &hsSoundDBObject, &hsDBType);
					if (retval != MSG_HANDLED)
					{
						m_ToolBox->Log(LOGERROR, _T("Sound manager: could not get volume attribute for row %d; sounds not fully loaded!\n"), i);
						attribArchive->Close();
						return MSG_ERROR;
					}

					bool bCachedUncompressed;
					attribArchive->SetIsWriting(false);
					attribArchive->Read(bCachedUncompressed);

					if (_tcscmp(szKey, _T("GlobalSoundVolume")) == 0)
					{
						static DWORD msgSetGlobalSoundVolume = CHashString(_T("SetGlobalSoundVolume")).GetUniqueID();
						m_ToolBox->SendMessage(msgSetGlobalSoundVolume, sizeof(float), &fVolume);						
					}
					else if(_tcscmp(szKey, _T("GlobalMusicVolume")) == 0)
					{
						static DWORD msgSetGlobalMusicVolume = CHashString(_T("SetGlobalMusicVolume")).GetUniqueID();
						m_ToolBox->SendMessage(msgSetGlobalMusicVolume, sizeof(float), &fVolume);
					}
					else
					{					
						// insert into map
						GLOBALSOUNDDATA gsd;
						gsd.dwFileName = hsFile.GetUniqueID();
						gsd.fVolume = fVolume;
						gsd.bCachedUncompressed = bCachedUncompressed;

						m_SoundMap[hsKey.GetUniqueID()] = gsd;
						m_FileToKeyMap[hsFile.GetUniqueID()] = hsKey.GetUniqueID();
					}
				}

				attribArchive->Close();
			}
			else
			{
				m_ToolBox->Log(LOGERROR, _T("Sound manager: could not get database info!\n\tNo sounds loaded!\n"));
				return MSG_ERROR;
			}
		}
		else
		{
			m_ToolBox->Log(LOGERROR, _T("Sound manager: sound database failed to load!\n\tNo sounds loaded!\n"));
			return MSG_ERROR;
		}
	}
	return MSG_HANDLED_STOP;
}
Exemplo n.º 27
0
TCHAR *GetContactID(MCONTACT hContact, char *szProto)
{
	CONTACTINFO ctInfo;
	INT_PTR ret;

	ZeroMemory((void *) &ctInfo, sizeof(ctInfo));
	ctInfo.cbSize = sizeof(ctInfo);
	ctInfo.szProto = szProto;
	ctInfo.dwFlag = CNF_UNIQUEID;
#ifdef _UNICODE
	ctInfo.dwFlag |= CNF_UNICODE;
#endif
	ctInfo.hContact = hContact;
	ret = CallService(MS_CONTACT_GETCONTACTINFO, 0, (LPARAM) &ctInfo);
	TCHAR *buffer;
	if (!ret)
		{
			TCHAR tmp[16];
			switch (ctInfo.type)
				{
					case CNFT_BYTE:
						{
							mir_sntprintf(tmp, SIZEOF(tmp), _T("%d"), ctInfo.bVal);
							buffer = _tcsdup(tmp);

							break;
						}

					case CNFT_WORD:
						{
							mir_sntprintf(tmp, SIZEOF(tmp), _T("%d"), ctInfo.wVal);
							buffer = _tcsdup(tmp);

							break;
						}

					case CNFT_DWORD:
						{
							mir_sntprintf(tmp, SIZEOF(tmp), _T("%ld"), ctInfo.dVal);
							buffer = _tcsdup(tmp);

							break;
						}

					case CNFT_ASCIIZ:
					default:
						{
							buffer = _tcsdup(ctInfo.pszVal);

							break;
						}
				}


		}
	mir_free(ctInfo.pszVal);
	if (!ret)
		{
			return buffer;
		}
		else{
			return NULL;
		}
}
Exemplo n.º 28
0
// get redirection arguments, ie. filenames that relate to redirection.
// NULL returned for redirections that aren't specified.
// Same filename may be returned for multiple redirections, such as for: >foo 2>&1
// The filename buffers must be free()'d.
bool getRedirArgs(LPTSTR lpCmdLine, RedirArg** redirArgs, int* numRedirArgs)
{
	bool		success = false;
	const int	maxArgChars = 1024;
	TCHAR		arg[maxArgChars];
	ArgType		argType;
	RedirArg	redirArg;
	bool		stderrAlso;

	if (lpCmdLine == NULL || redirArgs == NULL || numRedirArgs == NULL)
		return false;

	// for now, we only handle the first 3 descriptors (stdin, stdout, stderr), so pre-create the array
	*redirArgs = (RedirArg*)malloc(3*sizeof(RedirArg));
	if (*redirArgs == NULL)
		return false;
	*numRedirArgs = 3;
	// setup default stdin
	(*redirArgs)[0].redirType = RT_PIPE_STDIN;
	(*redirArgs)[0].fd = 0;
	(*redirArgs)[0].fd2 = -1;
	(*redirArgs)[0].filename = NULL;
	(*redirArgs)[0].append = false;
	(*redirArgs)[0].openForRead = true;
	(*redirArgs)[0].openForWrite = false;
	// setup default stdout
	(*redirArgs)[1].redirType = RT_PIPE_STDOUT;
	(*redirArgs)[1].fd = 1;
	(*redirArgs)[1].fd2 = -1;
	(*redirArgs)[1].filename = NULL;
	(*redirArgs)[1].append = false;
	(*redirArgs)[1].openForRead = false;
	(*redirArgs)[1].openForWrite = true;
	// setup default stderr
	(*redirArgs)[2].redirType = RT_PIPE_STDERR;
	(*redirArgs)[2].fd = 2;
	(*redirArgs)[2].fd2 = -1;
	(*redirArgs)[2].filename = NULL;
	(*redirArgs)[2].append = false;
	(*redirArgs)[2].openForRead = false;
	(*redirArgs)[2].openForWrite = true;

	while ((argType = getCmdLineArg(&lpCmdLine, arg, maxArgChars, &redirArg, &stderrAlso)) > 0)
	{
		if (argType == TOK_REDIR)
		{
			int	fd = redirArg.fd;
			if (fd > 2)
				goto cleanup;	// don't handle other file descriptors

			// if any other descriptors redirect via this descriptor, copy current redirArg to them
			int fdCopiedTo = -1;	// first descriptor copied to
			for (int i=0; i<*numRedirArgs; i++)
			{
				if (i == fd)
					continue;	// don't compare against self
				if ((*redirArgs)[i].redirType == RT_HANDLE && (*redirArgs)[i].fd2 == fd)
				{
					if (fdCopiedTo == -1)
					{	// copy redirArg to first referencing descriptor
						fdCopiedTo = i;
						(*redirArgs)[i] = (*redirArgs)[fd];
					}
					else
					{	// make other referencing descriptors reference the first referencing descriptor
						(*redirArgs)[i].fd2 = fdCopiedTo;
					}
				}
			}

			(*redirArgs)[fd] = redirArg;
			if (redirArg.redirType == RT_FILE)
			{
				TCHAR	filename[1024];
				if (getCmdLineArg(&lpCmdLine, filename, sizeof(filename), NULL, NULL) != TOK_STRING)
					goto cleanup;
				(*redirArgs)[fd].filename = _tcsdup(filename);
			}

			if (stderrAlso)
			{
				int	fd = 2;	// stderr

				// if any other descriptors redirect via this descriptor, copy current redirArg to them
				int fdCopiedTo = -1;	// first descriptor copied to
				for (int i=0; i<*numRedirArgs; i++)
				{
					if (i == fd)
						continue;	// don't compare against self
					if ((*redirArgs)[i].redirType == RT_HANDLE && (*redirArgs)[i].fd2 == fd)
					{
						if (fdCopiedTo == -1)
						{	// copy redirArg to first referencing descriptor
							fdCopiedTo = i;
							(*redirArgs)[i] = (*redirArgs)[fd];
						}
						else
						{	// make other referencing descriptors reference the first referencing descriptor
							(*redirArgs)[i].fd2 = fdCopiedTo;
						}
					}
				}

				(*redirArgs)[fd] = redirArg;
				(*redirArgs)[fd].redirType = RT_HANDLE;
				(*redirArgs)[fd].fd = fd;
				(*redirArgs)[fd].fd2 = redirArg.fd;
			}
		}
	}

	// success
	success = true;

cleanup:

	if (!success)
	{
		free(*redirArgs);
		*redirArgs = NULL;
		*numRedirArgs = 0;
	}

	return success;
}
Exemplo n.º 29
0
BOOL CChordEaseApp::InitInstance()
{
	AfxEnableControlContainer();

#ifdef _DEBUG
	Win32Console::Create();
#endif

	CSplashDlg	splash;	
	splash.Create(IDD_SPLASH);	// create splash screen

	// initialize COM for apartment threading
	if (FAILED(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED))) {
		AfxMessageBox(IDS_APP_CANT_INIT_COM);
		return FALSE;
	}

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	//  of your final executable, you should remove from the following
	//  the specific initialization routines you do not need.

#if _MFC_VER < 0x0700
#ifdef _AFXDLL
	Enable3dControls();			// Call this when using MFC in a shared DLL
#else
	Enable3dControlsStatic();	// Call this when linking to MFC statically
#endif
#endif

#ifdef PORTABLE_APP	// if building portable application
	// Set profile name to INI file in application folder
	free((void*)m_pszProfileName);
	CPathStr	IniPath(GetAppFolder());
	IniPath.Append(CString(m_pszAppName) + _T(".ini"));
	m_pszProfileName = _tcsdup(IniPath);
#else
	// Change the registry key under which our settings are stored.
	SetRegistryKey(_T("Anal Software"));
#endif

	LoadStdProfileSettings(8);  // Load standard INI file options (including MRU)

	// Register the application's document templates.  Document templates
	//  serve as the connection between documents, frame windows and views.

	CSingleDocTemplate* pDocTemplate;
	pDocTemplate = new CSingleDocTemplate(
		IDR_MAINFRAME,
		RUNTIME_CLASS(CChordEaseDoc),
		RUNTIME_CLASS(CMainFrame),       // main SDI frame window
		RUNTIME_CLASS(CChordEaseView));
	ASSERT(m_pDocManager == NULL);
	m_pDocManager = new CDocManagerEx;
	AddDocTemplate(pDocTemplate);

	// Parse command line for standard shell commands, DDE, file open
	CCommandLineInfo cmdInfo;
	ParseCommandLine(cmdInfo);

	if (IsPatchPath(cmdInfo.m_strFileName)) {
		m_PatchPath = cmdInfo.m_strFileName;
		cmdInfo.m_nShellCommand = CCommandLineInfo::FileNew;
	}

	// Dispatch commands specified on the command line
	if (!ProcessShellCommand(cmdInfo))
		return FALSE;

	splash.DestroyWindow();	// destroy splash screen

	// The one and only window has been initialized, so show and update it.
	m_pMainWnd->ShowWindow(SW_SHOW);
	m_pMainWnd->UpdateWindow();

	return TRUE;
}
Exemplo n.º 30
0
int file_edit(char* name)
{
	char original_name_path[30];
	int original_inode = inode_num;//记录当前的inode
	strcpy(original_name_path, name);
	if (eat_path(name) == -1) {
		printf("错误:文件路径出错!‘%s’\n", original_name_path);
		return -1;
	}
	if (type_check(name) == Directory) {
		printf("错误:'%s'文件不存在!\n", name);
		close_dir(inode_num);
		inode_num = original_inode;
		open_dir(inode_num);
		return -1;
	}
	if (type_check(name) == -1) {
		printf("错误:'%s'文件不存在!\n", name);
		close_dir(inode_num);
		inode_num = original_inode;
		open_dir(inode_num);
		return -1;
	}

	if (file_read(name) == -1) {//文件读取失败
		printf("错误:无读写‘%s’文件权限!\n", name);
		close_dir(inode_num);
		inode_num = original_inode;
		open_dir(inode_num);
		return -1;
	}

	BuffModifyTimeBeforeEdit = getBuffModifyTime();//文件信息载入到buff.txt后,获取buff.txt的修改时间,用来判断载入的内容在记事本中是否被修改
	/*
	SYSTEMTIME *STime = new SYSTEMTIME;
	FileTimeToSystemTime(&BuffModifyTimeBeforeEdit, STime);
	printf("%d-%d-%d-%d-%d-%d\n", STime->wYear, STime->wMonth, STime->wDay, STime->wHour, STime->wMinute, STime->wSecond);
	*/
	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	LPTSTR szCmdline = _tcsdup(TEXT("notepad.exe buff.txt"));

	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);
	ZeroMemory(&pi, sizeof(pi));

	// 打开子进程
	if (!CreateProcess(NULL,   // No module name (use command line)
		szCmdline,      // Command line
		NULL,           // Process handle not inheritable
		NULL,           // Thread handle not inheritable
		FALSE,          // Set handle inheritance to FALSE
		0,              // No creation flags
		NULL,           // Use parent's environment block
		NULL,           // Use parent's starting directory
		&si,            // Pointer to STARTUPINFO structure
		&pi)           // Pointer to PROCESS_INFORMATION structure
		)
	{
		printf("CreateProcess failed (%d).\n", GetLastError());
		return 0;
	}

	// Wait until child process exits.
	WaitForSingleObject(pi.hProcess, INFINITE);

	// Close process and thread handles.
	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);
	Sleep(10);
	BuffModifyTimeAfterEdit = getBuffModifyTime();//buff.txt关闭后,获取buff.txt的修改时间,用来判断载入的内容在记事本中是否被修改
	/*
	SYSTEMTIME *STime = new SYSTEMTIME;
	FileTimeToSystemTime(&BuffModifyTimeAfterEdit, STime);
	printf("%d-%d-%d-%d-%d-%d\n", STime->wYear, STime->wMonth, STime->wDay, STime->wHour, STime->wMinute, STime->wSecond);
	*/
	if (BuffModifyTimeBeforeEdit.dwLowDateTime == BuffModifyTimeAfterEdit.dwLowDateTime
		&& BuffModifyTimeBeforeEdit.dwHighDateTime == BuffModifyTimeAfterEdit.dwHighDateTime) {
								//若buff.txt的修改时间没有发生变化。则载入记事本的内容没有发生改变,则不必重新写入		
		close_dir(inode_num);
		inode_num = original_inode;
		open_dir(inode_num);
		return -1;
	}
	
	if (file_write(name) == -1) { //将数据从BUFF写入文件
		printf("错误:文件类型为只读,无法修改!\n");
		close_dir(inode_num);
		inode_num = original_inode;
		open_dir(inode_num);
		return -1;
	}

	close_dir(inode_num);
	inode_num = original_inode;
	open_dir(inode_num);
	return 0;
}