Example #1
0
HRESULT CDebugLog::SetProperties(IApplicationContext *pAppCtx)
{
    HRESULT                                  hr = S_OK;
    LPWSTR                                   wzAppName = NULL;

    // Get the executable name
    if (pAppCtx) {
        hr = ::AppCtxGetWrapper(pAppCtx, ACTAG_APP_NAME, &wzAppName);
        if (FAILED(hr)) {
            goto Exit;
        }
    }

    if (wzAppName && lstrlenW(wzAppName)) {
        _wzEXEName = WSTRDupDynamic(wzAppName);
        if (!_wzEXEName) {
            hr = E_OUTOFMEMORY;
            goto Exit;
        }
    }
    else {
        LPWSTR               wzFileName;

        // Didn't find EXE name in appctx. Use the .EXE name.
        wzFileName = PathFindFileName(g_wzEXEPath);
        _ASSERTE(wzFileName);

        _wzEXEName = WSTRDupDynamic(wzFileName);
        if (!_wzEXEName) {
            hr = E_OUTOFMEMORY;
            goto Exit;
        }
    }

Exit:
    SAFEDELETEARRAY(wzAppName);

    return hr;
}
Example #2
0
BOOL CMediaSettingsPage::OnInitDialog()
{
	CSettingsPage::OnInitDialog();

	m_bEnablePlay		= Settings.MediaPlayer.EnablePlay;
	m_bEnableEnqueue	= Settings.MediaPlayer.EnableEnqueue;

	for ( string_set::const_iterator i = Settings.MediaPlayer.FileTypes.begin();
		i != Settings.MediaPlayer.FileTypes.end(); ++i )
	{
		m_wndList.AddString( *i );
	}

	m_wndServices.AddString( L"(" + LoadString( IDS_GENERAL_CUSTOM ) + L"\x2026)" );
	m_wndServices.AddString( LoadString( IDS_MEDIA_PLAYER ) );
	int nSelected = INTERNAL_INDEX;

	for ( string_set::const_iterator i = Settings.MediaPlayer.ServicePath.begin();
		i != Settings.MediaPlayer.ServicePath.end(); ++i )
	{
		CString strPlayer = *i;
		BOOL bSelected = strPlayer.Right( 1 ) == L'*';	// SELECTED_PLAYER_TOKEN
		if ( bSelected ) strPlayer.TrimRight( L'*' );	// SELECTED_PLAYER_TOKEN

		int nIndex = m_wndServices.AddString( PathFindFileName( strPlayer ) );
		if ( bSelected )
			nSelected = nIndex;

		m_wndServices.SetItemDataPtr( nIndex, new CString( strPlayer ) );
	}

	m_wndServices.SetCurSel( nSelected );

	UpdateData( FALSE );

	Update();

	return TRUE;
}
HRESULT CRegisterExtension::RegisterAppShortcutInSendTo() const
{
    WCHAR szPath[MAX_PATH];
    HRESULT hr = GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath)) ? S_OK : ResultFromKnownLastError();
    if (SUCCEEDED(hr))
    {
        //  Set the shortcut target
        IShellLink *psl;
        hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&psl));
        if (SUCCEEDED(hr))
        {
            hr = psl->SetPath(szPath);
            if (SUCCEEDED(hr))
            {
                WCHAR szName[MAX_PATH];
                StringCchCopy(szName, ARRAYSIZE(szName), PathFindFileName(szPath));
                PathRenameExtension(szName, L".lnk");

                hr = SHGetFolderPath(NULL, CSIDL_SENDTO, NULL, 0, szPath);
                if (SUCCEEDED(hr))
                {
                    hr = PathAppend(szPath, szName) ? S_OK : E_FAIL;
                    if (SUCCEEDED(hr))
                    {
                        IPersistFile *ppf;
                        hr = psl->QueryInterface(IID_PPV_ARGS(&ppf));
                        if (SUCCEEDED(hr))
                        {
                            hr = ppf->Save(szPath, TRUE);
                            ppf->Release();
                        }
                    }
                }
            }
            psl->Release();
        }
    }
    return hr;
}
Example #4
0
void CCrossDlg::PopulateCombo(int Sel)
{
	CComboBox& Combo = (Sel == SEL_A ? m_NameA : m_NameB);
	CString	s;
	Combo.GetWindowText(s);
	Combo.ResetContent();
	int	i;
	for (i = 0; i < SELS; i++) {
		if (i != Sel) {	// exclude self-assignment
			int	pos = Combo.AddString(m_Frm->GetSelName(i));
			Combo.SetItemData(pos, i);	// store selection index in item
		}
	}
	int	Patches = m_Frm->GetPlaylist().GetCount();
	for (i = 0; i < Patches; i++) {
		CPathStr	Name;
		Name = PathFindFileName(m_Frm->GetPlaylist().GetPath(i));
		Name.RemoveExtension();
		Combo.AddString(Name);
	}
	Combo.SetWindowText(s);
}
Example #5
0
BOOL fileSaveForce(PSTR szName,PSTR szTempName,PBYTE pData,DWORD cbData)
{
  char  szTemp[_MAX_PATH];
  char  szData[8192];
  DWORD dwType,dwData;
  HKEY  hKey;
  PSTR  pFrom,pTo;
  char  szFrom[_MAX_PATH];
  char  szTo[_MAX_PATH];
 
  //try normal save
  if (fileSave(szName,pData,cbData)) return TRUE;
  //use MOVEFILE_DELAY_UNTIL_REBOOT
  strcpy(szTemp,szName);
  strcpy(PathFindFileName(szTemp),szTempName);
  if (!fileSave(szTemp,pData,cbData)) return FALSE;
  //check if MoveFileEx need ?
  if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Session Manager",0,KEY_READ,&hKey)){
    dwData = sizeof(szData);
    RegQueryValueEx(hKey,"PendingFileRenameOperations",NULL,&dwType,(PBYTE)szData,&dwData);
    RegCloseKey(hKey);

	strcpy(szFrom,szTemp);
	strcpy(szTo,szName);

	strlwr(szFrom);
	strlwr(szTo);
    
	for(pFrom=szData;pFrom<szData+dwData;){
	  pTo   = pFrom + 1 + strlen(pFrom);
	  strlwr(pFrom);
	  strlwr(pTo);
	  if (NULL != strstr(pFrom,szFrom) && NULL != strstr(pTo,szTo)) return TRUE;
	  pFrom = pTo + 1 + strlen(pTo);
    }
  }
  return MoveFileEx(szTemp,szName,MOVEFILE_DELAY_UNTIL_REBOOT);
}
string AppSettings::FindImage(const string& fname){
   TCHAR buffer[MAX_PATH];

   // Simply check for fully qualified path
   if (PathIsRoot(fname.c_str())) {
      if (-1 != _taccess(fname.c_str(), 0))
         return fname;
   }

   // Test if its relative and in one of the specified root paths
   for (stringlist::iterator itr = textureRootPaths.begin(), end = textureRootPaths.end(); itr != end; ++itr ){
      PathCombine(buffer, itr->c_str(), fname.c_str());
      if (-1 != _taccess(buffer, 0)){
         return string(buffer);
      }
   }

   // Hit the directories to find out whats out there
   if (!parsedImages){
      FindImages(imgTable, rootPath, searchPaths, extensions);
      parsedImages = true;
   }
   
   // Search my filename for our texture
   _tcscpy(buffer, PathFindFileName(fname.c_str()));
   PathRemoveExtension(buffer);
   NameValueCollection::iterator itr = imgTable.find(buffer);
   if (itr != imgTable.end()){
      if (!rootPath.empty()) {
         _tcscpy(buffer, rootPath.c_str());
         PathCombine(buffer, rootPath.c_str(), ((*itr).second).c_str());
         return string(buffer);
      } else {
         return (*itr).second;
      }
   }
   return fname;
}
Example #7
0
bool CCrossDlg::Open(int Sel, LPCTSTR Path)
{
	ASSERT(Sel >= 0 && Sel < SELS);
	if (!SaveCheck(Sel))
		return(FALSE);
	CStdioFile	fp;
	CFileException	e;
	if (!fp.Open(Path, CFile::modeRead | CFile::shareDenyWrite, &e)) {
		e.ReportError();
		return(FALSE);
	}
	CPatch	Patch;
	if (!Patch.Read(fp))
		return(FALSE);
	m_Info[Sel] = Patch;
	UpdateMix(m_PosEdit.GetVal());
	CPathStr	FileName(PathFindFileName(Path));
	FileName.RemoveExtension();
	SetName(Sel, FileName);
	if (Sel == m_Frm->GetEditSel())	// if input is selected for editing
		m_Frm->SetEditSel(Sel);	// refresh parameters dialog
	return(TRUE);
}
Example #8
0
//UtilExpandTemplateString()のパラメータ展開に必要な情報を構築する
void MakeExpandInformationEx(std::map<stdString,CString> &envInfo,LPCTSTR lpOpenDir,LPCTSTR lpOutputFile)
{
	//環境変数で構築
	UtilMakeExpandInformation(envInfo);

	//変数登録
	if(lpOpenDir){
		envInfo[_T("dir")]=lpOpenDir;
		envInfo[_T("OutputDir")]=lpOpenDir;

		//出力ドライブ名
		TCHAR szBuffer[MAX_PATH+1];
		_tcsncpy_s(szBuffer,lpOpenDir,COUNTOF(szBuffer)-1);
		PathStripToRoot(szBuffer);
		if(szBuffer[_tcslen(szBuffer)-1]==L'\\')szBuffer[_tcslen(szBuffer)-1]=L'\0';
		envInfo[_T("OutputDrive")]=(LPCTSTR)szBuffer;
	}

	if(lpOutputFile){
		envInfo[_T("OutputFile")]=lpOutputFile;
		envInfo[_T("OutputFileName")]=PathFindFileName(lpOutputFile);
	}
}
Example #9
0
void
GetDirectoryAndFileName(const std::string &currentDirectory, 
                        const std::string &relativeName,
                        std::string *directory, std::string *filename) {
#ifdef ISPC_IS_WINDOWS
    char path[MAX_PATH];
    const char *combPath = PathCombine(path, currentDirectory.c_str(),
                                       relativeName.c_str());
    assert(combPath != NULL);
    const char *filenamePtr = PathFindFileName(combPath);
    *filename = filenamePtr;
    *directory = std::string(combPath, filenamePtr - combPath);
#else
    // We need a fully qualified path.  First, see if the current file name
    // is fully qualified itself--in that case, the current working
    // directory isn't needed.  
    // @todo This probably needs to be smarter for Windows...
    std::string fullPath;
    if (relativeName[0] == '/')
        fullPath = relativeName;
    else {
        fullPath = g->currentDirectory;
        if (fullPath[fullPath.size()-1] != '/')
            fullPath.push_back('/');
        fullPath += relativeName;
    }

    // now, we need to separate it into the base name and the directory
    const char *fp = fullPath.c_str();
    const char *basenameStart = strrchr(fp, '/');
    assert(basenameStart != NULL);
    ++basenameStart;
    assert(basenameStart != '\0');
    *filename = basenameStart;
    *directory = std::string(fp, basenameStart - fp);
#endif // ISPC_IS_WINDOWS
}
Example #10
0
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void CWinPCap::Initialize(void) {
  if (!LoadWinPCap()) {
    TCHAR path[MAX_PATH];
    if (GetModuleFileName(NULL, path, _countof(path))) {
      lstrcpy(PathFindFileName(path), _T("winpcap-nmap-4.12.exe"));
      CString exe(path);
      CString cmd = CString(_T("\"")) + exe + _T("\" /S");

      PROCESS_INFORMATION pi;
      STARTUPINFO si;
      memset( &si, 0, sizeof(si) );
      si.cb = sizeof(si);
      si.dwFlags = STARTF_USESHOWWINDOW;
      si.wShowWindow = SW_HIDE;
      if (CreateProcess((LPCTSTR)exe, (LPTSTR)(LPCTSTR)cmd, 0, 0, FALSE, 
          IDLE_PRIORITY_CLASS , 0, NULL, &si, &pi)) {
        WaitForSingleObject(pi.hProcess, 60 * 60 * 1000);
        CloseHandle(pi.hThread);
        CloseHandle(pi.hProcess);
      }
    }
    LoadWinPCap();
  }
}
Example #11
0
void Logger::StartLog()
{
	time_t rawtime;
	tm timeinfo;
	time(&rawtime);
	localtime_s(&timeinfo, &rawtime);
	timeinfo.tm_mon++;
	timeinfo.tm_year += 1900;


	TCHAR modulePath[MAX_PATH];
	TCHAR * moduleName;
	GetModuleFileName(NULL, modulePath, MAX_PATH);
	moduleName = PathFindFileName(modulePath);
	*(PathFindExtension(moduleName)) = 0;

	// Log to TextFiles
	char logFile[MAX_PATH];
	std::string logs_dir(".\\Logs");
	MAKEDIR(logs_dir.c_str());
	sprintf_s(logFile, "%s\\%s_%02d-%02d-%04d.txt", logs_dir.c_str(), moduleName, timeinfo.tm_mday, timeinfo.tm_mon, timeinfo.tm_year);

	std::ofstream fsLog(logFile, std::ios::app);
	if (fsLog.is_open())
	{
		char timeData[MAX_PATH];
		sprintf_s(timeData, "%02d:%02d:%02d %02d-%02d-%04d", timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec, timeinfo.tm_mday, timeinfo.tm_mon, timeinfo.tm_year);
		fsLog << "=============================================================================================" << std::endl;
		fsLog << "===\t\t\t\tLOG START " << timeData << "\t\t\t\t  ===" << std::endl;
		fsLog << "=============================================================================================" << std::endl;
		fsLog.close();
	}

	Log("%s - Dragon Ball Online Server\n", moduleName);
	SetConsoleTitle(moduleName);
}
void CReadChangesRequest::ProcessNotification()
{
	BYTE* pBase = m_BackupBuffer.data();

	for (;;)
	{
		FILE_NOTIFY_INFORMATION& fni = (FILE_NOTIFY_INFORMATION&)*pBase;

		std::wstring wstrFilename = fni.FileName; // , fni.FileNameLength / sizeof(wchar_t));
		//wstrFilename[fni.FileNameLength] = 0;
		// Handle a trailing backslash, such as for a root directory.
		if (m_wstrDirectory[m_wstrDirectory.length()-1] != L'\\')
			wstrFilename = m_wstrDirectory + L'\\' + wstrFilename;
		else
			wstrFilename = m_wstrDirectory + wstrFilename;

		// If it could be a short filename, expand it.
		LPCWSTR wszFilename = PathFindFileName(wstrFilename.c_str());
		int len = lstrlen(wszFilename);
		// The maximum length of an 8.3 filename is twelve, including the dot.
		if (len <= 12 && wcschr(wszFilename, L'~'))
		{
			// Convert to the long filename form. Unfortunately, this
			// does not work for deletions, so it's an imperfect fix.
			wchar_t wbuf[MAX_PATH];
			if (::GetLongPathName(wstrFilename.c_str(), wbuf, _countof(wbuf)) > 0)
				wstrFilename = wbuf;
		}

		m_pServer->m_pBase->Push(fni.Action, wstrFilename);

		if (!fni.NextEntryOffset)
			break;
		pBase += fni.NextEntryOffset;
	};
}
Example #13
0
MBASEAPI LPCTSTR MIRACLEEXPORT mirGetFileTitle(LPCTSTR lpszPath)
{	
	return PathFindFileName(lpszPath);	
}
Example #14
0
BOOL showContextMenu (HWND hDlg, TCHAR* FName, WNDPROC menuProc)
{
	TCHAR* FileName = PathFindFileName (FName);
	TCHAR FilePath [MAX_PATH];
	lstrcpy (FilePath, FName);
	*PathFindFileName (FilePath) = L'\0';
	
	LPSHELLFOLDER DesktopFolder;
	if (NOERROR != SHGetDesktopFolder (&DesktopFolder))
	{
		return FALSE;
	}
	
	LPITEMIDLIST ParentPidl;
	ULONG Eaten;
	if (S_OK != DesktopFolder->ParseDisplayName (hDlg, 0, FilePath, &Eaten, &ParentPidl, 0))
	{
		return FALSE;
	}
	
	LPSHELLFOLDER ParentFolder;
	if (S_OK != DesktopFolder->BindToObject (ParentPidl, 0, IID_IShellFolder, (void**)&ParentFolder))
	{
		return FALSE;
	}
	
	LPITEMIDLIST Pidl;
	if (S_OK != ParentFolder->ParseDisplayName (hDlg, 0, FileName, &Eaten, &Pidl, 0))
	{
		return FALSE;
	}	

	LPCONTEXTMENU CM;
	if (S_OK != ParentFolder->GetUIObjectOf (hDlg, 1, (LPCITEMIDLIST*)&Pidl, IID_IContextMenu, 0, (void**)&CM))
	{
		return FALSE;
	}
	
	HMENU hMenu = CreatePopupMenu ();
	if (hMenu == NULL) 
	{
		return FALSE;
	}
	
	CM->QueryContextMenu (hMenu, 0, 1, 0x7FFF, CMF_EXTENDEDVERBS | CMF_EXPLORE);
	
	WNDPROC defWndProc = (WNDPROC) SetWindowLong (hDlg, GWL_WNDPROC, (LONG)menuProc);
	SetProp (hDlg, L"defWndProc", (HANDLE) defWndProc);
	
	POINT pt;
	GetCursorPos (&pt);
	int Cmd = TrackPopupMenu (hMenu,
		TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_RIGHTBUTTON | TPM_RETURNCMD,
		pt.x, pt.y, 0, hDlg, 0);


	SetWindowLong (hDlg, GWL_WNDPROC, (LONG) RemoveProp (hDlg, L"defWndProc"));
		
	if (Cmd)
	{
		// Set up a CMINVOKECOMMANDINFO structure.
		CMINVOKECOMMANDINFO CI;
		ZeroMemory (&CI, sizeof(CMINVOKECOMMANDINFO));
		CI.cbSize = sizeof (CMINVOKECOMMANDINFO);
		CI.hwnd = hDlg;
		CI.lpVerb = (LPCSTR) MAKEINTRESOURCE(Cmd - 1);
		CI.lpParameters = "";
		CI.lpDirectory = "";
		CI.nShow = SW_SHOWNORMAL;
		CM->InvokeCommand (&CI);
	}
	
	return DestroyMenu (hMenu);
}
Example #15
0
int _tmain(int argc, _TCHAR* argv[])
{
	if ( argc < 4 )
	{
		_tprintf( _T("SkinUpdate ") _VERSION_
			_T("\nUsage: SkinUpdate.exe input.h input.rc output.xml\n") );
		return 1;
	}

	LPCTSTR szOutput = NULL;

	for ( int i = 1 ; i < argc ; i++ )
	{
		LPCTSTR szFilename = PathFindFileName( argv[ i ] );
		LPCTSTR szExt = PathFindExtension( szFilename );
		if ( _tcscmp( szExt, _T(".h") ) == 0 )
		{
			if ( ! LoadIDs( argv[ i ] ) )
			{
				_tprintf( _T("Error: Filed to load IDs from: %s\n"), szFilename );
				return 1;
			}
			_tprintf(
				_T("Loaded from %s:\n")
				_T("  %d IDs\n"),
				szFilename, g_oIDs.GetCount() );
		}
		else if ( _tcscmp( szExt, _T(".rc") ) == 0 )
		{
			if ( ! LoadResources( argv[ i ] ) )
			{
				_tprintf( _T("Error: Filed to load strings from: %s\n"), szFilename );
				return 1;
			}
			_tprintf(
				_T("Loaded from %s:\n")
				_T("  %d strings\n")
				_T("  %d guidelines\n")
				_T("  %d dialogs\n")
				_T("  %d icons\n")
				_T("  %d bitmaps\n")
				_T("  %d htmls\n"),
				szFilename,
				g_oStrings.GetCount(),
				g_oGuidelines.GetCount(),
				g_oDialogs.GetCount(),
				g_oIcons.GetCount(),
				g_oBitmaps.GetCount(),
				g_oHtmls.GetCount() );
		}
		else if ( _tcscmp( szExt, _T(".xml") ) == 0 )
		{
			szOutput = argv[ i ];
		}
		else
		{
			_tprintf( _T("Error: Unknown file extension: %s\n"), szExt );
			return 1;
		}
	}

	for ( POSITION pos = g_oDialogs.GetStartPosition() ; pos ; )
	{
		CStringA sID;
		UINT nID;
		g_oDialogs.GetNextAssoc( pos, sID, nID );

		if ( ! g_oGuidelines.Lookup( sID, nID ) )
			_tprintf( _T("Warning: Found dialog \"%hs\" without guideline\n"), sID );
	}

	for ( POSITION pos = g_oIDs.GetStartPosition() ; pos ; )
	{
		CStringA sID;
		UINT nID;
		g_oIDs.GetNextAssoc( pos, sID, nID );

		if ( _strnicmp( sID, "IDI_", 4 ) == 0 )
		{
			UINT nFoo;
			if ( ! g_oIcons.Lookup( sID, nFoo ) )
				_tprintf( _T("Warning: Found orphan icon ID \"%hs\"\n"), sID );
		}
		else if ( _strnicmp( sID, "IDR_", 4 ) == 0 )
		{
			UINT nFoo;
			if ( ! g_oBitmaps.Lookup( sID, nFoo ) &&
				 ! g_oIcons.Lookup( sID, nFoo ) &&
				 ! g_oHtmls.Lookup( sID, nFoo ) )
			{
				_tprintf( _T("Warning: Found orphan bitmap/icon/html ID \"%hs\"\n"), sID );
			}
		}
		else if ( _strnicmp( sID, "IDB_", 4 ) == 0 )
		{
			UINT nFoo;
			if ( ! g_oBitmaps.Lookup( sID, nFoo ) )
				_tprintf( _T("Warning: Found orphan bitmap ID \"%hs\"\n"), sID );
		}
		else if ( _strnicmp( sID, "IDD_", 4 ) == 0 )
		{
			UINT nFoo;
			if ( ! g_oDialogs.Lookup( sID, nFoo ) )
				_tprintf( _T("Warning: Found orphan dialog ID \"%hs\"\n"), sID );
		}
		else if ( _strnicmp( sID, "IDS_", 4 ) == 0 )
		{
			CSSPair oFoo;
			if ( ! g_oStrings.Lookup( nID, oFoo ) )
				_tprintf( _T("Warning: Found orphan string ID \"%hs\"\n"), sID );
		}
		//else if ( _strnicmp( sID, "ID_", 3 ) == 0 )
		//{
		//	CSSPair oFoo;
		//	if ( ! g_oStrings.Lookup( nID, oFoo ) )
		//		_tprintf( _T("Warning: Found orphan string ID \"%hs\"\n"), sID );
		//}
	}

	// Sort by ID
	std::list< CStringA > indexTips;
	std::list< UINT > indexStrings;
	for ( POSITION pos = g_oStrings.GetStartPosition() ; pos ; )
	{
		UINT nID;
		CSSPair oPair;
		g_oStrings.GetNextAssoc( pos, nID, oPair );
		if ( nID < 30000 )	// Strings
			indexStrings.push_back( nID );
		else	// Tips
			indexTips.push_back( oPair.sSecond );
	}
	indexStrings.sort();
	indexTips.sort();

	if ( ! szOutput )
		szOutput = _T("default-en.xml");

	FILE* pFile = NULL;
	if ( _tfopen_s( &pFile, szOutput, _T("wt") ) != 0 )
	{
		_tprintf( _T("Error: Can't create output XML-file: %s\n"), szOutput );
		return 1;
	}

	// File header
	_ftprintf( pFile,
		_T("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n")
		_T("<skin xmlns=\"http://schemas.peerproject.org/Skin.xsd\" version=\"1.0\">\n\n") );

	// Manifest
	_ftprintf( pFile,
		_T("<!-- Manifest -->\n")
		_T("<manifest\tname=\"(translation language: English)\"\n")
		_T("\t\tauthor=\"(translation author)\"\n")
		_T("\t\tupdatedBy=\"(translation updaters)\"\n")
		_T("\t\tdescription=\"(translation description: PeerProject English Skin File)\"\n")
		_T("\t\tlink=\"(translation URL: http://peerproject.org)\"\n")
		_T("\t\temail=\"(author e-mail)\"\n")
		_T("\t\tversion=\"(PeerProject version)\"\n")
		_T("\t\ttype=\"Language\"\n")
		_T("\t\tlanguage=\"(translation language code: en)\"\n")
		_T("\t\tprompt=\"(translation prompt: Click here to select English as your natural language.)\"\n")
		_T("\t\tdir=\"(translation language direction: ltr or rtl)\"\n")
		_T("/>\n\n") );

	// Toolbars
	_ftprintf( pFile,
		_T("\t<!-- Toolbar Definitions -->\n\t<toolbars>\n")
		_T("\t</toolbars>\n\n") );

	// Menus
	_ftprintf( pFile,
		_T("\t<!-- Menu Definitions -->\n\t<menus>\n")
		_T("\t</menus>\n\n") );

	// Documents
	_ftprintf( pFile,
		_T("\t<!-- Documents -->\n\t<documents>\n")
		_T("\t</documents>\n\n") );

	// Command Tips
	_ftprintf( pFile,
		_T("\t<!-- Localised Command Tip Text. The \"message\" is displayed in the status bar, while the \"tip\" is shown in a tooltip -->\n\t<commandTips>\n") );
	for ( std::list< CStringA >::iterator i = indexTips.begin() ; i != indexTips.end() ; ++i )
	{
		UINT nID;
		ATLVERIFY( g_oIDs.Lookup( (*i), nID ) );
		CSSPair oPair;
		ATLVERIFY( g_oStrings.Lookup( nID, oPair ) );
		ATLASSERT( oPair.sSecond == (*i) );
		oPair.sFirst.Replace( "&", "&amp;" );
		oPair.sFirst.Replace( "�", "&#160;" );	// Not a space
		oPair.sFirst.Replace( "\"\"", "&quot;" );
		oPair.sFirst.Replace( "\\r\\n", "\\n" );
		int nPos = oPair.sFirst.Find( "\\n" );
		if ( nPos == -1 )
			_ftprintf( pFile, _T("\t\t<tip id=\"%hs\" message=\"%hs\"/>\n"), oPair.sSecond, oPair.sFirst );
		else
			_ftprintf( pFile, _T("\t\t<tip id=\"%hs\" message=\"%hs\" tip=\"%hs\"/>\n"), oPair.sSecond, oPair.sFirst.Left( nPos ), oPair.sFirst.Mid( nPos + 2 ) );
	}
	_ftprintf( pFile,
		_T("\t</commandTips>\n\n") );

	// Control Tips
	_ftprintf( pFile,
		_T("\t<!-- Tips displayed when mouse is moved over controls in the dialogs -->\n\t<controlTips>\n")
		_T("\t</controlTips>\n\n") );

	// Strings
	_ftprintf( pFile,
		_T("\t<!-- Localised Strings -->\n\t<strings>\n") );
	for ( std::list< UINT >::iterator i = indexStrings.begin() ; i != indexStrings.end() ; ++i )
	{
		CSSPair oPair;
		ATLVERIFY( g_oStrings.Lookup( (*i), oPair ) );
		oPair.sFirst.Replace( "&", "&amp;" );
		oPair.sFirst.Replace( "�", "&#160;" );	// Not a space
		oPair.sFirst.Replace( "\"\"", "&quot;" );
		oPair.sFirst.Replace( "\\r\\n", "\\n" );
		if ( (*i) < 7000 )	// Frames
			_ftprintf( pFile, _T("\t\t<string id=\"WINDOW_%hs\" value=\"%hs\"/>\n"), oPair.sSecond.Left( oPair.sSecond.GetLength() - 5 ).Mid( 4 ), oPair.sFirst );
		else
			_ftprintf( pFile, _T("\t\t<string id=\"%u\" value=\"%hs\"/>\n"), (*i), oPair.sFirst );
	}
	_ftprintf( pFile,
		_T("\t</strings>\n\n") );

	// Dialogs
	_ftprintf( pFile,
		_T("\t<!-- Localised Dialog Text, the \"cookie\" verifies that the dialog matches the skin -->\n")
		_T("\t<!-- Use DialogScan feature, do not edit dialogs manually -->\n\t<dialogs>\n")
		_T("\t</dialogs>\n\n") );

	// Columns
	_ftprintf( pFile,
		_T("\t<!-- Columns Definitions -->\n\t<listColumns>\n")
		_T("\t</listColumns>\n\n") );

	// EOF
	_ftprintf( pFile,
		_T("</skin>\n") );

	fclose( pFile );

	_tprintf( _T("Saved output XML-file: %s\n"), szOutput );

	return 0;
}
Example #16
0
INT_PTR CALLBACK CDialogPackage::SelectFolderDlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_INITDIALOG:
    {
        EnableThemeDialogTexture(hWnd, ETDT_ENABLETAB);
        c_Dialog->SetDialogFont(hWnd);

        std::wstring* existingPath = (std::wstring*)lParam;
        SetWindowLongPtr(hWnd, GWLP_USERDATA, lParam);

        *existingPath += L'*';
        WIN32_FIND_DATA fd;
        HANDLE hFind = FindFirstFileEx(existingPath->c_str(), FindExInfoStandard, &fd, FindExSearchNameMatch, NULL, 0);
        existingPath->pop_back();

        if (hFind != INVALID_HANDLE_VALUE)
        {
            const WCHAR* folder = PathFindFileName(existingPath->c_str());

            HWND item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_EXISTING_RADIO);
            std::wstring text = L"Add folder from ";
            text.append(folder, wcslen(folder) - 1);
            text += L':';
            SetWindowText(item, text.c_str());
            Button_SetCheck(item, BST_CHECKED);

            item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_EXISTING_COMBO);

            do
            {
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY &&
                        !(fd.cFileName[0] == L'.' && (!fd.cFileName[1] || fd.cFileName[1] == L'.' && !fd.cFileName[2])) &&
                        wcscmp(fd.cFileName, L"Backup") != 0 &&
                        wcscmp(fd.cFileName, L"@Backup") != 0)
                {
                    ComboBox_InsertString(item, -1, fd.cFileName);
                }
            }
            while (FindNextFile(hFind, &fd));

            ComboBox_SetCurSel(item, 0);

            FindClose(hFind);
        }
    }
    break;

    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case IDC_PACKAGESELECTFOLDER_EXISTING_RADIO:
        {
            HWND item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_EXISTING_COMBO);
            EnableWindow(item, TRUE);
            int sel = ComboBox_GetCurSel(item);
            item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_CUSTOM_EDIT);
            EnableWindow(item, FALSE);
            item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_CUSTOMBROWSE_BUTTON);
            EnableWindow(item, FALSE);

            item = GetDlgItem(hWnd, IDOK);
            EnableWindow(item, sel != -1);
        }
        break;

        case IDC_PACKAGESELECTFOLDER_CUSTOM_RADIO:
        {
            HWND item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_EXISTING_COMBO);
            EnableWindow(item, FALSE);
            item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_CUSTOM_EDIT);
            EnableWindow(item, TRUE);
            item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_CUSTOMBROWSE_BUTTON);
            EnableWindow(item, TRUE);

            SendMessage(hWnd, WM_COMMAND, MAKEWPARAM(IDC_PACKAGESELECTFOLDER_CUSTOM_EDIT, EN_CHANGE), 0);
        }
        break;

        case IDC_PACKAGESELECTFOLDER_CUSTOM_EDIT:
            if (HIWORD(wParam) == EN_CHANGE)
            {
                WCHAR buffer[MAX_PATH];
                int len = Edit_GetText((HWND)lParam, buffer, MAX_PATH);

                // Disable Add button if invalid directory
                DWORD attributes = GetFileAttributes(buffer);
                BOOL state = (attributes != INVALID_FILE_ATTRIBUTES &&
                              attributes & FILE_ATTRIBUTE_DIRECTORY);
                EnableWindow(GetDlgItem(hWnd, IDOK), state);
            }
            break;

        case IDC_PACKAGESELECTFOLDER_CUSTOMBROWSE_BUTTON:
        {
            WCHAR buffer[MAX_PATH];
            BROWSEINFO bi = {0};
            bi.hwndOwner = hWnd;
            bi.ulFlags = BIF_USENEWUI | BIF_NONEWFOLDERBUTTON | BIF_RETURNONLYFSDIRS;

            PIDLIST_ABSOLUTE pidl = SHBrowseForFolder(&bi);
            if (pidl && SHGetPathFromIDList(pidl, buffer))
            {
                HWND item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_CUSTOM_EDIT);
                SetWindowText(item, buffer);
                CoTaskMemFree(pidl);
            }
        }
        break;

        case IDOK:
        {
            WCHAR buffer[MAX_PATH];
            HWND item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_EXISTING_RADIO);
            bool existing = Button_GetCheck(item) == BST_CHECKED;

            item = GetDlgItem(hWnd, existing ? IDC_PACKAGESELECTFOLDER_EXISTING_COMBO : IDC_PACKAGESELECTFOLDER_CUSTOM_EDIT);
            GetWindowText(item, buffer, _countof(buffer));

            std::wstring* result = (std::wstring*)GetWindowLongPtr(hWnd, GWLP_USERDATA);

            if (existing)
            {
                *result += buffer;
            }
            else
            {
                *result = buffer;
            }
            *result += L'\\';

            EndDialog(hWnd, 1);
        }
        }
        break;

    case WM_CLOSE:
        EndDialog(hWnd, 0);
        break;

    default:
        return FALSE;
    }

    return TRUE;
}
Example #17
0
extern "C" __declspec(dllexport) bool PinToStartMenu4XP(bool bPin, char* szPath)
{
	TSAUTO();

	TCHAR file_dir[MAX_PATH + 1] = {0};
	TCHAR *file_name;
	wchar_t* pwstr_Path = AnsiToUnicode(szPath);
	if(pwstr_Path == NULL){
		return false;
	}

	wcscpy_s(file_dir,MAX_PATH,pwstr_Path);
	PathRemoveFileSpecW(file_dir);
	file_name = PathFindFileName(pwstr_Path);
	::CoInitialize(NULL);
	CComPtr<IShellDispatch> pShellDisp;
	CComPtr<Folder> folder_ptr;
	CComPtr<FolderItem> folder_item_ptr;
	CComPtr<FolderItemVerbs> folder_item_verbs_ptr;


	HRESULT rv = CoCreateInstance( CLSID_Shell, NULL, CLSCTX_SERVER,IID_IDispatch, (LPVOID *) &pShellDisp );
	do 
	{
		IF_FAILED_OR_NULL_BREAK(rv,pShellDisp);
		rv = pShellDisp->NameSpace(_variant_t(file_dir),&folder_ptr);
		IF_FAILED_OR_NULL_BREAK(rv,folder_ptr);
		rv = folder_ptr->ParseName(CComBSTR(file_name),&folder_item_ptr);
		IF_FAILED_OR_NULL_BREAK(rv,folder_item_ptr);
		rv = folder_item_ptr->Verbs(&folder_item_verbs_ptr);
		IF_FAILED_OR_NULL_BREAK(rv,folder_item_verbs_ptr);
		long count = 0;
		folder_item_verbs_ptr->get_Count(&count);
		for (long i = 0; i < count ; ++i)
		{
			FolderItemVerb* item_verb = NULL;
			rv = folder_item_verbs_ptr->Item(_variant_t(i),&item_verb);
			if (SUCCEEDED(rv) && item_verb)
			{
				CComBSTR bstrName;
				item_verb->get_Name(&bstrName);

				if ( VerbNameMatch(bstrName,bPin) )
				{
					TSDEBUG4CXX("Find Verb to Pin:"<< bstrName);
					int i = 0;
					do
					{
						rv = item_verb->DoIt();
						TSDEBUG4CXX("Try Do Verb. NO." << i+1 << ", return="<<rv);
						if (SUCCEEDED(rv))
						{
							::SHChangeNotify(SHCNE_UPDATEDIR|SHCNE_INTERRUPT|SHCNE_ASSOCCHANGED, SHCNF_IDLIST |SHCNF_FLUSH | SHCNF_PATH|SHCNE_ASSOCCHANGED,
								pwstr_Path,0);
							Sleep(500);
							delete [] pwstr_Path;
							::CoUninitialize();
							return true;
						}else
						{
							Sleep(500);
							rv = item_verb->DoIt();
						}
					}while ( i++ < 3);
						
					break;
				}
			}
		}
	} while (0);
	delete [] pwstr_Path;
	::CoUninitialize();
	return false;
}
Example #18
0
INT_PTR CDialogPackage::CTabInfo::OnCommand(WPARAM wParam, LPARAM lParam)
{
    switch (LOWORD(wParam))
    {
    case IDC_PACKAGEINFO_ADDSKIN_BUTTON:
    {
        c_Dialog->m_SkinFolder.second = SelectFolder(m_Window, g_Data.skinsPath);
        if (!c_Dialog->m_SkinFolder.second.empty())
        {
            c_Dialog->m_SkinFolder.first = PathFindFileName(c_Dialog->m_SkinFolder.second.c_str());
            c_Dialog->m_SkinFolder.first.pop_back();	// Remove slash

            HWND item = GetDlgItem(m_Window, IDC_PACKAGEINFO_COMPONENTS_LIST);
            LVITEM lvi;
            lvi.mask = LVIF_TEXT | LVIF_GROUPID;
            lvi.iItem = 1;
            lvi.iSubItem = 0;
            lvi.iGroupId = 0;
            lvi.pszText = (WCHAR*)c_Dialog->m_SkinFolder.first.c_str();
            ListView_InsertItem(item, &lvi);

            EnableWindow((HWND)lParam, FALSE);
            c_Dialog->SetNextButtonState();
        }
    }
    break;

    case IDC_PACKAGEINFO_ADDTHEME_BUTTON:
    {
        std::wstring folder = SelectFolder(m_Window, g_Data.settingsPath + L"Layouts\\");
        if (!folder.empty())
        {
            std::wstring name = PathFindFileName(folder.c_str());
            name.pop_back();	// Remove slash

            if (c_Dialog->m_LayoutFolders.insert(std::make_pair(name, folder)).second)
            {
                HWND item = GetDlgItem(m_Window, IDC_PACKAGEINFO_COMPONENTS_LIST);
                LVITEM lvi;
                lvi.mask = LVIF_TEXT | LVIF_GROUPID;
                lvi.iItem = c_Dialog->m_LayoutFolders.size() + 1;
                lvi.iSubItem = 0;
                lvi.iGroupId = 1;
                lvi.pszText = (WCHAR*)name.c_str();
                ListView_InsertItem(item, &lvi);
            }
        }
    }
    break;

    case IDC_PACKAGEINFO_ADDPLUGIN_BUTTON:
    {
        std::pair<std::wstring, std::wstring> plugins = SelectPlugin(m_Window);
        std::wstring name = PathFindFileName(plugins.first.c_str());
        if (!name.empty() && c_Dialog->m_PluginFolders.insert(std::make_pair(name, plugins)).second)
        {
            HWND item = GetDlgItem(m_Window, IDC_PACKAGEINFO_COMPONENTS_LIST);
            LVITEM lvi;
            lvi.mask = LVIF_TEXT | LVIF_GROUPID;
            lvi.iItem = c_Dialog->m_PluginFolders.size() + 1;
            lvi.iSubItem = 0;
            lvi.iGroupId = 2;
            lvi.pszText = (WCHAR*)name.c_str();
            ListView_InsertItem(item, &lvi);
        }
    }
    break;

    case IDC_PACKAGEINFO_REMOVE_BUTTON:
    {
        HWND item = GetDlgItem(m_Window, IDC_PACKAGEINFO_COMPONENTS_LIST);
        int sel = ListView_GetNextItem(item, -1, LVNI_FOCUSED | LVNI_SELECTED);
        if (sel != -1)
        {
            WCHAR buffer[MAX_PATH];

            // Remove unchecked items from the component sets
            LVITEM lvi;
            lvi.mask = LVIF_GROUPID | LVIF_TEXT;
            lvi.iSubItem = 0;
            lvi.iItem = sel;
            lvi.pszText = buffer;
            lvi.cchTextMax = _countof(buffer);
            ListView_GetItem(item, &lvi);

            ListView_DeleteItem(item, sel);

            const std::wstring name = buffer;
            switch (lvi.iGroupId)
            {
            case 0:
            {
                item = GetDlgItem(m_Window, IDC_PACKAGEINFO_ADDSKIN_BUTTON);
                EnableWindow(item, TRUE);
                c_Dialog->m_SkinFolder.first.clear();
                c_Dialog->m_SkinFolder.second.clear();
                c_Dialog->SetNextButtonState();
            }
            break;

            case 1:
                c_Dialog->m_LayoutFolders.erase(c_Dialog->m_LayoutFolders.find(name));
                break;

            case 2:
                c_Dialog->m_PluginFolders.erase(c_Dialog->m_PluginFolders.find(name));
                break;
            }
        }
    }
    break;

    case IDC_PACKAGEINFO_NAME_EDIT:
    case IDC_PACKAGEINFO_AUTHOR_EDIT:
    case IDC_PACKAGEINFO_VERSION_EDIT:
        if (HIWORD(wParam) == EN_CHANGE)
        {
            WCHAR buffer[64];
            int len = GetWindowText((HWND)lParam, buffer, _countof(buffer));
            if (LOWORD(wParam) == IDC_PACKAGEINFO_NAME_EDIT)
            {
                c_Dialog->m_Name.assign(buffer, len);
            }
            else if (LOWORD(wParam) == IDC_PACKAGEINFO_AUTHOR_EDIT)
            {
                c_Dialog->m_Author.assign(buffer, len);
            }
            else // if (LOWORD(wParam) == IDC_PACKAGEINFO_VERSION_EDIT)
            {
                c_Dialog->m_Version.assign(buffer, len);
            }
            c_Dialog->SetNextButtonState();
        }
        break;


    default:
        return FALSE;
    }

    return TRUE;
}
Example #19
0
DWORD WINAPI Import(LPVOID lpParameter)
{
    BOOL   bIsDirectory;
    CHAR   szFileName[MAX_PATH];
    PBYTE  pbFile;
    LPSTR  lpPath, lpFileName;
    HANDLE hFile, hMap, hFind;
    DWORD  dwFileAttributes, dwSize, dwNewSize, dwCount, dwTotal;
    FILETYPE FileType;
    WIN32_FIND_DATA wfd;

    lpPath = (LPSTR)lpParameter;
    dwNewSize = dwCount = dwTotal = 0;
    dwFileAttributes = GetFileAttributes(lpPath);
    if (dwFileAttributes == INVALID_FILE_ATTRIBUTES)
    {
        return 0;
    }

    bIsDirectory = dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
    if (bIsDirectory)
    {
        sprintf(szFileName, "%s\\*.*", lpPath);
        hFind = FindFirstFile(szFileName, &wfd);
        if (hFind == INVALID_HANDLE_VALUE)
        {
            return 0;
        }
        lpFileName = szFileName;
    }
    else
    {
        lpFileName = lpPath;
    }

    while (ReleaseSemaphore(g_hSemaphore, 1, NULL) == FALSE)
    {
        Sleep(1);
    }

    do
    {
        if (bIsDirectory)
        {
            if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                continue;
            }
            sprintf(szFileName, "%s\\%s", lpPath, wfd.cFileName);
        }

        ++dwTotal;
        hFile = CreateFile(FILE_NAME,
                           GENERIC_READ|GENERIC_WRITE,
                           FILE_SHARE_READ|FILE_SHARE_WRITE,
                           NULL,
                           OPEN_EXISTING,
                           FILE_ATTRIBUTE_NORMAL,
                           NULL);
        if (hFile == INVALID_HANDLE_VALUE)
        {
            printf("CreateFile() failed: %s\n", FILE_NAME);
            continue;
        }

        dwSize = GetFileSize(hFile, NULL);

        if (dwSize != 0)
        {
            hMap = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, dwSize, NULL);
            if (hMap == NULL)
            {
                printf("CreateFileMapping() failed: %s\n", FILE_NAME);
                CloseHandle(hFile);
                continue;
            }

            pbFile = (PBYTE)MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
            CloseHandle(hMap);
            if (pbFile == NULL)
            {
                printf("MapViewOfFile() failed: %s\n", FILE_NAME);
                CloseHandle(hFile);
                continue;
            }

            FileType = CheckFileType(pbFile, dwSize, PathFindFileName(FILE_NAME));
            if (FileType != UNKNOWN)
            {
                ReplaceString(pbDict, pbFile, dwSize);
                dwNewSize = StringToAnsi(pbFile, FileType, dwSize);
                ++dwCount;
            }

            UnmapViewOfFile(pbFile);
            if (dwNewSize != 0)
            {
                SetFilePointer(hFile, dwNewSize, 0, FILE_BEGIN);
                SetEndOfFile(hFile);
            }
        }
        CloseHandle(hFile);
    } while (bIsDirectory && FindNextFile(hFind, &wfd));

    if (bIsDirectory)
    {
        FindClose(hFind);
    }

    WaitForSingleObject(g_hSemaphore, INFINITE);
    return dwCount;
}
Example #20
0
dboolean D_TryGetWad(const char* name)
{
#ifndef __CELLOS_LV2__
  dboolean result = false;

  char wadname[PATH_MAX];
  char* cmdline = NULL;
  char* wadname_p = NULL;
  char* msg = NULL;
  const char* format =
    "The necessary wad has not been found\n"
    "Do you want to search for \'%s\'?\n\n"
    "Command line:\n%s\n\n"
    "Be careful! Execution of an unknown program is unsafe.";

  if (!getwad_cmdline || !name || !(*getwad_cmdline) || !(*name))
    return false;

  strncpy(wadname, PathFindFileName(name), sizeof(wadname) - 4);
  AddDefaultExtension(wadname, ".wad");

  cmdline = malloc(strlen(getwad_cmdline) + strlen(wadname) + 2);
  wadname_p = strstr(getwad_cmdline, "%wadname%");
  if (wadname_p)
  {
    strncpy(cmdline, getwad_cmdline, wadname_p - getwad_cmdline);
    strcat(cmdline, wadname);
    strcat(cmdline, wadname_p + strlen("%wadname%"));
  }
  else
  {
    sprintf(cmdline, "%s %s", getwad_cmdline, wadname);
  }

  msg = malloc(strlen(format) + strlen(wadname) + strlen(cmdline));
  sprintf(msg, format, wadname, cmdline);

  if (PRB_IDYES == I_MessageBox(msg, PRB_MB_DEFBUTTON2 | PRB_MB_YESNO))
  {
    int ret;

    lprintf(LO_INFO, "D_TryGetWad: Trying to get %s from somewhere\n", name);

    ret = system(cmdline);

    if (ret != 0)
    {
      lprintf(LO_ERROR, "D_TryGetWad: Execution failed - %s\n", strerror(errno));
    }
    else
    {
      char *str = I_FindFile(name, ".wad");
      if (str)
      {
        lprintf(LO_INFO, "D_TryGetWad: Successfully received\n");
        free(str);
        result = true;
      }
    }
  }

  free(msg);
  free(cmdline);

  return result;
#else
  return false;
#endif
}
Example #21
0
//
//   FUNCTION: InstallService
//
//   PURPOSE: Install the current application as a service to the local 
//   service control manager database.
//
//   PARAMETERS:
//   * pszServiceName - the name of the service to be installed
//   * pszDisplayName - the display name of the service
//   * dwStartType - the service start option. This parameter can be one of 
//     the following values: SERVICE_AUTO_START, SERVICE_BOOT_START, 
//     SERVICE_DEMAND_START, SERVICE_DISABLED, SERVICE_SYSTEM_START.
//   * pszDependencies - a pointer to a double null-terminated array of null-
//     separated names of services or load ordering groups that the system 
//     must start before this service.
//   * pszAccount - the name of the account under which the service runs.
//   * pszPassword - the password to the account name.
//
//  RETURN VALUE:
//    TRUE if the service is successfully created, otherwise FALSE
//
//   NOTE: If the function fails to install the service, it prints the error 
//   in the standard output stream for users to diagnose the problem.
//
BOOL InstallService(PSTR pszServiceName, 
                    PSTR pszDisplayName, 
                    DWORD dwStartType,
                    PSTR pszDependencies, 
                    PSTR pszAccount, 
                    PSTR pszPassword)
{
    BOOL bRet = TRUE;
    char szPath[MAX_PATH];
	char outPath[MAX_PATH];
    SC_HANDLE schSCManager = NULL;
    SC_HANDLE schService = NULL;

	DBGPrint("Called\n");


	// Open the local default service control manager database, we do this first to see
	// if we're going to be even able to install
	schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT |
		SC_MANAGER_CREATE_SERVICE);
	if (schSCManager == NULL)
	{
		DBGPrint("OpenSCManager failed w/err 0x%08lx\n", GetLastError());
		goto Cleanup;
	}


    if (GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath)) == 0)
    {
        DBGPrint("GetModuleFileName failed w/err 0x%08lx\n", GetLastError());
        goto Cleanup;
    }
	DBGPrint("File is: %s\n", szPath);

	//Copy the file to win32 or syswow64, depending on bitness
		//Get windows system directory
		 GetSystemDirectory(outPath, MAX_PATH);
	
		 PTSTR filename = PathFindFileName(szPath);
		 //Set up the path
		 strcat(outPath, "\\");
		 strcat(outPath, filename);

		 DBGPrint("Outfile is: %s\n",outPath);

		 //Copy the file
		 if (CopyFile(szPath, outPath, TRUE) == FALSE){
			 DWORD dwError = GetLastError();
			 DBGPrint("Copyfile failed w/err 0x%08lx\n", dwError);
			 if (dwError != ERROR_FILE_EXISTS){
				 goto Cleanup;
			 }
			 DBGPrint("File exists, lets install anyway\n");
		 }


    // Install the service into SCM by calling CreateService
    schService = CreateService(
        schSCManager,                   // SCManager database
        pszServiceName,                 // Name of service
        pszDisplayName,                 // Name to display
        SERVICE_QUERY_STATUS,           // Desired access
        SERVICE_WIN32_OWN_PROCESS,      // Service type
        dwStartType,                    // Service start type
        SERVICE_ERROR_NORMAL,           // Error control type
        szPath,                         // Service's binary
        NULL,                           // No load ordering group
        NULL,                           // No tag identifier
        pszDependencies,                // Dependencies
       // pszAccount,                     // Service running account
       NULL,       
       pszPassword                     // Password of the account
        );
    if (schService == NULL)
    {
        DBGPrint("CreateService failed w/err 0x%08lx\n", GetLastError());
        bRet = FALSE;
        goto Cleanup;
    }

    DBGPrint("%s is installed.\n", pszServiceName);



Cleanup:
    // Centralized cleanup for all allocated resources.
    if (schSCManager)
    {
        CloseServiceHandle(schSCManager);
        schSCManager = NULL;
    }
    if (schService)
    {
        CloseServiceHandle(schService);
        schService = NULL;
    }

	DBGPrint("Returning\n");

    return bRet;
}
Example #22
0
static void R_DemoEx_AddParams(wadtbl_t *wadtbl)
{
  size_t i;
  int p;
  char buf[200];

  char* filename_p;
  char* fileext_p;

  char *files = NULL;
  char *iwad  = NULL;
  char *pwads = NULL;
  char *dehs  = NULL;
  char **item;

  //iwad and pwads
  for (i = 0; i < numwadfiles; i++)
  {
    filename_p = PathFindFileName(wadfiles[i].name);
    fileext_p = filename_p + strlen(filename_p) - 1;
    while (fileext_p != filename_p && *(fileext_p - 1) != '.')
      fileext_p--;
    if (fileext_p == filename_p)
      continue;

    item = NULL;

    if (wadfiles[i].src == source_iwad && !iwad && !strcasecmp(fileext_p, "wad"))
      item = &iwad;

    if (wadfiles[i].src == source_pwad && !strcasecmp(fileext_p, "wad"))
      item = &pwads;

    if (item)
    {
      AddString(item, "\"");
      AddString(item, filename_p);
      AddString(item, "\" ");
    }
  }

  //dehs
  p = M_CheckParm ("-deh");
  if (p)
  {
    while (++p != myargc && *myargv[p] != '-')
    {
      char *file = NULL;
      if ((file = I_FindFile(myargv[p], ".bex")) ||
          (file = I_FindFile(myargv[p], ".deh")))
      {
        filename_p = PathFindFileName(file);
        AddString(&dehs, "\"");
        AddString(&dehs, filename_p);
        AddString(&dehs, "\" ");
        free(file);
      }
    }
  }

  if (iwad)
  {
    AddString(&files, "-iwad ");
    AddString(&files, iwad);
  }
  
  if (pwads)
  {
    AddString(&files, "-file ");
    AddString(&files, pwads);
  }

  if (dehs)
  {
    AddString(&files, "-deh ");
    AddString(&files, dehs);
  }

  //add complevel for formats which do not have it in header
  if (demo_compatibility)
  {
    sprintf(buf, "-complevel %d ", compatibility_level);
    AddString(&files, buf);
  }

  //for recording or playback using "single-player coop" mode
  if (M_CheckParm("-solo-net"))
  {
    sprintf(buf, "-solo-net ");
    AddString(&files, buf);
  }

  if ((p = M_CheckParm("-emulate")) && (p < myargc - 1))
  {
    sprintf(buf, "-emulate %s", myargv[p + 1]);
    AddString(&files, buf);
  }

  // doom 1.2 does not store these params in header
  if (compatibility_level == doom_12_compatibility)
  {
    if (M_CheckParm("-respawn"))
    {
      sprintf(buf, "-respawn ");
      AddString(&files, buf);
    }
    if (M_CheckParm("-fast"))
    {
      sprintf(buf, "-fast ");
      AddString(&files, buf);
    }
    if (M_CheckParm("-nomonsters"))
    {
      sprintf(buf, "-nomonsters ");
      AddString(&files, buf);
    }
  }

  if (spechit_baseaddr != 0 && spechit_baseaddr != DEFAULT_SPECHIT_MAGIC)
  {
    sprintf(buf, "-spechit %d ", spechit_baseaddr);
    AddString(&files, buf);
  }

  //overflows
  {
    overrun_list_t overflow;
    for (overflow = 0; overflow < OVERFLOW_MAX; overflow++)
    {
      if (overflows[overflow].shit_happens)
      {
        sprintf(buf, "-set %s=%d ", overflow_cfgname[overflow], overflows[overflow].emulate);
        AddString(&files, buf);
      }
    }
  }

  if (files)
  {
    W_AddLump(wadtbl, DEMOEX_PARAMS_LUMPNAME, (const byte*)files, strlen(files));
  }
}
Example #23
0
INT_PTR CALLBACK CDialogPackage::SelectPluginDlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_INITDIALOG:
    {
        EnableThemeDialogTexture(hWnd, ETDT_ENABLETAB);
        c_Dialog->SetDialogFont(hWnd);

        auto plugins = (std::pair<std::wstring, std::wstring>*)lParam;
        SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)plugins);
    }
    break;

    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case IDC_PACKAGESELECTPLUGIN_32BITBROWSE_BUTTON:
        case IDC_PACKAGESELECTPLUGIN_64BITBROWSE_BUTTON:
        {
            WCHAR buffer[MAX_PATH];
            buffer[0] = L'\0';

            OPENFILENAME ofn = { sizeof(OPENFILENAME) };
            ofn.Flags = OFN_FILEMUSTEXIST;
            ofn.lpstrFilter = L"Plugins (.dll)\0*.dll";
            ofn.lpstrTitle = L"Select plugin file";
            ofn.lpstrDefExt = L"dll";
            ofn.nFilterIndex = 0;
            ofn.lpstrFile = buffer;
            ofn.nMaxFile = _countof(buffer);
            ofn.hwndOwner = c_Dialog->GetWindow();

            if (!GetOpenFileName(&ofn))
            {
                break;
            }

            bool x32 = LOWORD(wParam) == IDC_PACKAGESELECTPLUGIN_32BITBROWSE_BUTTON;

            LOADED_IMAGE* loadedImage = ImageLoad(StringUtil::NarrowUTF8(buffer).c_str(), NULL);
            if (loadedImage)
            {
                WORD machine = loadedImage->FileHeader->FileHeader.Machine;
                ImageUnload(loadedImage);

                if ((x32 && machine == IMAGE_FILE_MACHINE_I386) || (!x32 && machine == IMAGE_FILE_MACHINE_AMD64))
                {
                    // Check if same name as other DLL
                    auto plugins = (std::pair<std::wstring, std::wstring>*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
                    const WCHAR* otherName = PathFindFileName(x32 ? plugins->second.c_str() : plugins->first.c_str());
                    if (*otherName && _wcsicmp(otherName, PathFindFileName(buffer)) != 0)
                    {
                        MessageBox(hWnd, L"Plugins must have same name.", L"Rainmeter Skin Packager", MB_OK | MB_TOPMOST);
                        break;
                    }

                    PathSetDlgItemPath(hWnd, x32 ? IDC_PACKAGESELECTPLUGIN_32BIT_EDIT : IDC_PACKAGESELECTPLUGIN_64BIT_EDIT, buffer);

                    (x32 ? plugins->first : plugins->second) = buffer;

                    if (!plugins->first.empty() && !plugins->second.empty())
                    {
                        // Enable Add button if both plugins have been selected
                        EnableWindow(GetDlgItem(hWnd, IDOK), TRUE);
                    }
                    break;
                }
            }

            MessageBox(hWnd, L"Invalid plugin.", L"Rainmeter Skin Packager", MB_OK | MB_TOPMOST);
        }
        break;

        case IDOK:
            EndDialog(hWnd, 1);
            break;
        }
        break;

    case WM_CLOSE:
        EndDialog(hWnd, 0);
        break;

    default:
        return FALSE;
    }

    return TRUE;
}
Example #24
0
void CDownloadTask::RunMergeFile(CDownload* pDownload, LPCTSTR szFilename, BOOL bMergeValidation, const Fragments::List& oMissedGaps, float fProgress)
{
//	HANDLE hSource = CreateFile( szFilename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL );

	QWORD nSourceSize = 0;		// qwSourceLength
	QWORD nSourceOffset = 0;	// qwSourceOffset

	CAtlFile oSource;
	oSource.Create( szFilename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, OPEN_EXISTING );
	VERIFY_FILE_ACCESS( oSource, szFilename )
	if ( ! oSource )
	{
		// Source file open error
		theApp.Message( MSG_ERROR, IDS_DOWNLOAD_FILE_OPEN_ERROR, szFilename );
		return;
	}

	oSource.GetSize( nSourceSize );
	if ( ! nSourceSize )
		return;		// Empty source file

	CSingleLock pLock( &Transfers.m_pSection, TRUE );

	if ( ! Downloads.Check( pDownload ) ||
		  pDownload->IsCompleted() ||
		  pDownload->IsMoving() )
		return;		// Moot download almost completed

	if ( m_bMergeValidation &&
		! pDownload->IsTorrent() &&
		 pDownload->NeedTigerTree() &&
		 pDownload->NeedHashset() )
	{
	//	pLock.Unlock();
	//	MsgBox( IDS_DOWNLOAD_EDIT_COMPLETE_NOHASH, MB_ICONEXCLAMATION );
		DEBUG_ONLY( theApp.Message( MSG_DEBUG, IDS_DOWNLOAD_EDIT_COMPLETE_NOHASH ) );
		return;		// No hashsets
	}

	if ( ! pDownload->PrepareFile() )
		return;		// Destination file open error

	Fragments::List oList( pDownload->GetEmptyFragmentList() );
	if ( ! oMissedGaps.empty() )
	{
		Fragments::List::const_iterator pItr = oMissedGaps.begin();
		const Fragments::List::const_iterator pEnd = oMissedGaps.end();
		for ( ; pItr != pEnd ; ++pItr )
			oList.erase( *pItr );
	}

	if ( ! oList.size() )
		return;		// No available fragments

	// Determine offset if needed
	if ( pDownload->IsMultiFileTorrent() )
	{
		QWORD nOffset = 0;		// qwOffset
		BOOL bFound = FALSE;
		CBTInfo::CBTFile* pFile;
		CString strTargetName;
		const CString strSourceName = PathFindFileName( szFilename );

		if ( GetAsyncKeyState( VK_SHIFT ) & 0x8000 )	// Forced selection dialog
		{
			int nIndex = pDownload->SelectFile( &pLock );
			if ( nIndex == 0 )
			{
				bFound = TRUE;
			}
			else if ( nIndex > 0 )
			{
				CBTInfo::CBTFile* pSelectFile = pDownload->m_pTorrent.m_pFiles.GetAt( pDownload->m_pTorrent.m_pFiles.FindIndex( nIndex ) );
				for ( POSITION pos = pDownload->m_pTorrent.m_pFiles.GetHeadPosition() ; pos ; )
				{
					pFile = pDownload->m_pTorrent.m_pFiles.GetNext( pos );
					if ( pFile->m_sPath == pSelectFile->m_sPath )
					{
						DEBUG_ONLY( theApp.Message( MSG_DEBUG, _T("Merge Selected File: ") + pFile->m_sPath ) );
						nSourceOffset = nOffset;
						bFound = TRUE;	// Avoid checks below
						break;
					}

					nOffset += pFile->m_nSize;
				}
			}
		}

		if ( ! bFound )		// No forced match, try filename
		{
			for ( POSITION pos = pDownload->m_pTorrent.m_pFiles.GetHeadPosition() ; pos ; )
			{
				pFile = pDownload->m_pTorrent.m_pFiles.GetNext( pos );
				strTargetName = PathFindFileName( pFile->m_sPath );

				if ( strTargetName.CompareNoCase( strSourceName ) == 0 )
				{
					DEBUG_ONLY( theApp.Message( MSG_DEBUG, _T("Merge Filename: ") + pFile->m_sPath ) );
					nSourceOffset = nOffset;
					bFound = TRUE;	// Avoid fallback check below
					break;
				}

				nOffset += pFile->m_nSize;
			}
		}

		if ( ! bFound )		// No filename match, try exact size
		{
			nOffset = 0;
		//	const CString strExt = PathFindExtension( strSourceName );
			for ( POSITION pos = pDownload->m_pTorrent.m_pFiles.GetHeadPosition() ; pos ; )
			{
				pFile = pDownload->m_pTorrent.m_pFiles.GetNext( pos );

				if ( pFile->m_nSize == nSourceSize )	// && strExt == PathFindExtension( pFile->m_sPath )
				{
					DEBUG_ONLY( theApp.Message( MSG_DEBUG, _T("Merge Filesize Fallback") ) );
					nSourceOffset = nOffset;
				//	bFound = TRUE;
					break;
				}

				nOffset += pFile->m_nSize;
			}
		}
	}

	pLock.Unlock();

	const float fIncrement = fProgress / oList.size();

	const DWORD nBufferLength = 256 * 1024;		// Was 65536?

	// Read missing file fragments from selected file
	auto_array< BYTE > Buf( new BYTE [nBufferLength] );
	Fragments::List::const_iterator pItr = oList.begin();
	const Fragments::List::const_iterator pEnd = oList.end();
	for ( ; ! m_pEvent && pItr != pEnd ; ++pItr )
	{
		m_fProgress += fIncrement;		// Update tooltip

		QWORD qwLength = pItr->end() - pItr->begin();
		QWORD qwOffset = pItr->begin();

		// Check for overlapped fragments
		if ( qwOffset + qwLength <= nSourceOffset ||
			 nSourceOffset + nSourceSize <= qwOffset )
			 continue;	 // No overlaps

		// Calculate overlapped range end offset
		QWORD qwEnd = min( qwOffset + qwLength, nSourceOffset + nSourceSize );
		// Calculate overlapped range start offset
		qwOffset = max( qwOffset, nSourceOffset );
		// Calculate overlapped range length
		qwLength = qwEnd - qwOffset;
		// Calculate file offset if any
		QWORD qwFileOffset = ( qwOffset > nSourceOffset ) ? qwOffset - nSourceOffset : 0;
		if ( FAILED( oSource.Seek( qwFileOffset, FILE_BEGIN ) ) )
			continue;

		DWORD dwToRead;
		while ( ( dwToRead = (DWORD)min( qwLength, (QWORD)nBufferLength ) ) != 0 && ! m_pEvent )
		{
			DWORD dwReaded = 0;
			if ( SUCCEEDED( oSource.Read( Buf.get(), dwToRead, dwReaded ) ) && dwReaded )
			{
				pLock.Lock();

				if ( ! Downloads.Check( pDownload ) || pDownload->IsCompleted() || pDownload->IsMoving() )
					return;

				pDownload->SubmitData( qwOffset, Buf.get(), (QWORD)dwReaded );
				pLock.Unlock();
				qwOffset += (QWORD)dwReaded;
				qwLength -= (QWORD)dwReaded;
			}
			else
			{
				// File error or end of file. Non-Fatal
				break;
			}
		}

		pLock.Lock();

		if ( ! Downloads.Check( pDownload ) || pDownload->IsCompleted() || pDownload->IsMoving() )
			return;

		if ( bMergeValidation )
			pDownload->RunValidation();

		pDownload->SetModified();

		pLock.Unlock();
	}

//	m_bSuccess = true;
}
Example #25
0
int PluginsManager::loadPlugin(const generic_string& pluginFilePath, std::vector<generic_string> & dll2Remove)
{
	PluginInfo *pi = new PluginInfo;
	try {
		pi->_moduleName = PathFindFileName(pluginFilePath.c_str());

		pi->_hLib = ::LoadLibrary(pluginFilePath.c_str());
		if (!pi->_hLib)
			throw generic_string(TEXT("Load Library is failed.\nMake \"Runtime Library\" setting of this project as \"Multi-threaded(/MT)\" may cure this problem."));

		pi->_pFuncIsUnicode = (PFUNCISUNICODE)GetProcAddress(pi->_hLib, "isUnicode");
#ifdef UNICODE
		if (!pi->_pFuncIsUnicode || !pi->_pFuncIsUnicode())
			throw generic_string(TEXT("This ANSI plugin is not compatible with your Unicode Notepad++."));
#else
		if (pi->_pFuncIsUnicode)
			throw generic_string(TEXT("This Unicode plugin is not compatible with your ANSI mode Notepad++."));
#endif

		pi->_pFuncSetInfo = (PFUNCSETINFO)GetProcAddress(pi->_hLib, "setInfo");

		if (!pi->_pFuncSetInfo)
			throw generic_string(TEXT("Missing \"setInfo\" function"));

		pi->_pFuncGetName = (PFUNCGETNAME)GetProcAddress(pi->_hLib, "getName");
		if (!pi->_pFuncGetName)
			throw generic_string(TEXT("Missing \"getName\" function"));

		pi->_pBeNotified = (PBENOTIFIED)GetProcAddress(pi->_hLib, "beNotified");
		if (!pi->_pBeNotified)
			throw generic_string(TEXT("Missing \"beNotified\" function"));

		pi->_pMessageProc = (PMESSAGEPROC)GetProcAddress(pi->_hLib, "messageProc");
		if (!pi->_pMessageProc)
			throw generic_string(TEXT("Missing \"messageProc\" function"));

		pi->_pFuncSetInfo(_nppData);

		pi->_pFuncGetFuncsArray = (PFUNCGETFUNCSARRAY)GetProcAddress(pi->_hLib, "getFuncsArray");
		if (!pi->_pFuncGetFuncsArray)
			throw generic_string(TEXT("Missing \"getFuncsArray\" function"));

		pi->_funcItems = pi->_pFuncGetFuncsArray(&pi->_nbFuncItem);

		if ((!pi->_funcItems) || (pi->_nbFuncItem <= 0))
			throw generic_string(TEXT("Missing \"FuncItems\" array, or the nb of Function Item is not set correctly"));

		pi->_pluginMenu = ::CreateMenu();

		GetLexerCountFn GetLexerCount = (GetLexerCountFn)::GetProcAddress(pi->_hLib, "GetLexerCount");
		// it's a lexer plugin
		if (GetLexerCount)
		{
			GetLexerNameFn GetLexerName = (GetLexerNameFn)::GetProcAddress(pi->_hLib, "GetLexerName");
			if (!GetLexerName)
				throw generic_string(TEXT("Loading GetLexerName function failed."));

			GetLexerStatusTextFn GetLexerStatusText = (GetLexerStatusTextFn)::GetProcAddress(pi->_hLib, "GetLexerStatusText");

			if (!GetLexerStatusText)
				throw generic_string(TEXT("Loading GetLexerStatusText function failed."));

			// Assign a buffer for the lexer name.
			char lexName[MAX_EXTERNAL_LEXER_NAME_LEN];
			lexName[0] = '\0';
			TCHAR lexDesc[MAX_EXTERNAL_LEXER_DESC_LEN];
			lexDesc[0] = '\0';

			int numLexers = GetLexerCount();

			NppParameters * nppParams = NppParameters::getInstance();

			ExternalLangContainer *containers[30];
#ifdef UNICODE
			WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
#endif
			for (int x = 0; x < numLexers; x++)
			{
				GetLexerName(x, lexName, MAX_EXTERNAL_LEXER_NAME_LEN);
				GetLexerStatusText(x, lexDesc, MAX_EXTERNAL_LEXER_DESC_LEN);
#ifdef UNICODE
				const TCHAR *pLexerName = wmc->char2wchar(lexName, CP_ACP);
#else
				const TCHAR *pLexerName = lexName;
#endif
				if (!nppParams->isExistingExternalLangName(pLexerName) && nppParams->ExternalLangHasRoom())
					containers[x] = new ExternalLangContainer(pLexerName, lexDesc);
				else
					containers[x] = NULL;
			}

			TCHAR xmlPath[MAX_PATH];
            lstrcpy(xmlPath, nppParams->getNppPath().c_str());
			PathAppend(xmlPath, TEXT("plugins\\Config"));
            PathAppend(xmlPath, pi->_moduleName.c_str());
			PathRemoveExtension(xmlPath);
			PathAddExtension(xmlPath, TEXT(".xml"));

			if (!PathFileExists(xmlPath))
			{
				memset(xmlPath, 0, MAX_PATH * sizeof(TCHAR));
				lstrcpy(xmlPath, nppParams->getAppDataNppDir() );
				PathAppend(xmlPath, TEXT("plugins\\Config"));
                PathAppend(xmlPath, pi->_moduleName.c_str());
				PathRemoveExtension( xmlPath );
				PathAddExtension( xmlPath, TEXT(".xml") );

				if (! PathFileExists( xmlPath ) )
				{
					throw generic_string(generic_string(xmlPath) + TEXT(" is missing."));
				}
			}

			TiXmlDocument *_pXmlDoc = new TiXmlDocument(xmlPath);

			if (!_pXmlDoc->LoadFile())
			{
				delete _pXmlDoc;
				_pXmlDoc = NULL;
				throw generic_string(generic_string(xmlPath) + TEXT(" failed to load."));
			}

			for (int x = 0; x < numLexers; x++) // postpone adding in case the xml is missing/corrupt
				if (containers[x] != NULL)
					nppParams->addExternalLangToEnd(containers[x]);

			nppParams->getExternalLexerFromXmlTree(_pXmlDoc);
			nppParams->getExternalLexerDoc()->push_back(_pXmlDoc);
#ifdef UNICODE
			const char *pDllName = wmc->wchar2char(pluginFilePath.c_str(), CP_ACP);
#else
			const char *pDllName = pluginFilePath.c_str();
#endif
			::SendMessage(_nppData._scintillaMainHandle, SCI_LOADLEXERLIBRARY, 0, (LPARAM)pDllName);
		}

		_pluginInfos.push_back(pi);
        return (_pluginInfos.size() - 1);
	}
	catch(generic_string s)
	{
		s += TEXT("\n\n");
		s += USERMSG;
		if (::MessageBox(NULL, s.c_str(), pluginFilePath.c_str(), MB_YESNO) == IDYES)
		{
			dll2Remove.push_back(pluginFilePath);
		}
		delete pi;
        return -1;
	}
	catch(...)
	{
		generic_string msg = TEXT("Fail loaded");
		msg += TEXT("\n\n");
		msg += USERMSG;
		if (::MessageBox(NULL, msg.c_str(), pluginFilePath.c_str(), MB_YESNO) == IDYES)
		{
			dll2Remove.push_back(pluginFilePath);
		}
		delete pi;
        return -1;
	}
}
Example #26
0
DWORD _SpySrv_RequestFromDriver (LPVOID pBuffer, DWORD nSize) 
{
  SDNMHDR	*p = pBuffer ;
  VOID		*pSerial ;
  UINT		nSerialSize ;
  DWORD		nResponseSize = 0 ;

  TRACE ; 

  ASSERT (pBuffer) ;
  ASSERT (nSize>0) ;
  ASSERT (nSize>=sizeof(SDNMHDR)) ;
  
  TRACE_INFO (TEXT(" /----REQ-%d----\\ (size=%d\n"), p->dwCode, nSize) ;

  switch( p->dwCode )
    {
    case SDN_ASK:
      {
	DWORD		nReaction ;
	FILTCOND	cond ;

	pSerial = ((SDNASK*)p)->data ;
	nSerialSize = nSize - sizeof(SDNASK) ;
	
	ASSERT (nSerialSize>0) ;

	if( ! FiltCond_Unserialize (&cond, pSerial, nSerialSize) )
	  {
	    TRACE_ERROR (TEXT("FiltCond_Unserialize failed\n")) ;
	    nReaction = RULE_ACCEPT ;	    
	  }
	else
	  {   
	    nReaction = _SpySrv_Ask (((SDNASK*)p)->nProcessAddress, 
				     ((SDNASK*)p)->nDefReaction, 
				     &cond) ;
	  }
	
	*((DWORD*)pBuffer) = nReaction ;
	nResponseSize = sizeof(DWORD) ;
      }
      break ;

    case SDN_LOG:
    case SDN_ALERT:
      {
	DWORD		nReaction ;
	FILTCOND	cond ;

	nReaction = ((SDNLOG*)p)->dwReaction ;

	pSerial = ((SDNLOG*)p)->data ;
	nSerialSize = nSize - sizeof(SDNLOG) ;

	if( ! FiltCond_Unserialize (&cond, pSerial, nSerialSize) )
	  {
	    TRACE_ERROR (TEXT("FiltCond_Unserialize failed\n")) ;
	    nReaction = RULE_ACCEPT ;	    
	  }
	else
	  {
	    _SpySrv_Log (((SDNLOG*)p)->nProcessAddress, &cond, nReaction, p->dwCode==SDN_ALERT) ;
	  }
      }
      break ;

    case SDN_SCANFILE:
      {
	DWORD		nScanResult ;

	nScanResult = SpySrv_ScanFile (((SDNSCANFILE*)pBuffer)->wszFilePath, FALSE) ;

	*((DWORD*)pBuffer) = nScanResult ;
	nResponseSize = sizeof(DWORD) ;
      }
      break ;

    case SDN_PROCESSCREATED:
      {
	SDNPROCESSCREATED * pSdnpc = pBuffer ;
	PROCSTRUCT	proc ;
	
	proc.nProcessAddress	= pSdnpc->nProcessAddress ;
	proc.nProcessId		= pSdnpc->nProcessId ;
	proc.nState		= PS_HOOKED_SINCE_BIRTH ;
	wcslcpy (proc.szName, PathFindFileName(pSdnpc->wszFilePath), 32) ;
	wcslcpy (proc.szPath, pSdnpc->wszFilePath, MAX_PATH) ;
	
	ProcList_Lock () ;
	ProcList_Add (&proc) ;
	ProcList_Unlock () ;
	  
	PostMessage (g_hwndMain, WM_SPYNOTIFY, SN_PROCESSCREATED, pSdnpc->nProcessAddress) ;
      }
      break ;

    case SDN_PIDCHANGED:
      {
  	SDNPIDCHANGED	*pSdnpc = pBuffer ;
  	PROCSTRUCT	*pProc ;

	ProcList_Lock () ;	
	pProc = ProcList_Get (pSdnpc->nProcessAddress) ;
	if( pProc ) 
	  {
	    TRACE_ALWAYS (TEXT("PID changed %d -> %d\n"), pProc->nProcessId, pSdnpc->nNewProcessId) ; 
	    pProc->nProcessId = pSdnpc->nNewProcessId ;  
	  }
	ProcList_Unlock () ;

	// This notification has been disabled because it caused a dead-lock.
	// PostMessage (g_hwndMain, WM_SPYNOTIFY, SN_PIDCHANGED, pSdnpc->nProcessAddress) ;
      }
      break ;

    case SDN_PROCESSTERMINATED:
      {
	SDNPROCESSTERMINATED * pSdnpt = pBuffer ;

	TRACE_INFO (TEXT("Process terminated 0x%08X\n"),pSdnpt->nProcessAddress) ; 
	
	ProcList_Lock () ;
	ProcList_Remove (pSdnpt->nProcessAddress) ;
	ProcList_Unlock () ;
	  
	PostMessage (g_hwndMain, WM_SPYNOTIFY, SN_PROCESSTERMINATED, pSdnpt->nProcessAddress) ;
      }
      break ;

    default:

      TRACE_WARNING (TEXT("Driver request not handled (code=%d)\n"),  p->dwCode) ;
    }

  TRACE_INFO (TEXT(" \\----ANS------/\n")) ;

  return nResponseSize ;
}
Example #27
0
BOOL ParseArguments(CONST INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo)
{
	WCHAR szNamePath[MAX_PATH + 1];
	GetModuleFileName(NULL, szNamePath, MAX_PATH);
	WCHAR *szProgName = PathFindFileName(szNamePath);

	po::options_description desc("Options");
	desc.add_options()
		("help,h", "Print help page and exit")
		("version,V", "Print version and exit")
		("warning,w", po::wvalue<std::wstring>(), "Warning thershold")
		("critical,c", po::wvalue<std::wstring>(), "Critical threshold")
		("performance-counter,P", po::wvalue<std::wstring>(), "The performance counter string to use")
		("performance-wait", po::value<DWORD>(), "Sleep in milliseconds between the two perfomance querries (Default: 1000ms)")
		("fmt-countertype", po::wvalue<std::wstring>(), "Value type of counter: 'double'(default), 'long', 'int64'")
		("print-objects", "Prints all available objects to console")
		("print-object-info", "Prints all available instances and counters of --performance-counter, do not use a full perfomance counter string here")
		;

	po::basic_command_line_parser<wchar_t> parser(ac, av);

	try {
		po::store(
			parser
			.options(desc)
			.style(
			po::command_line_style::unix_style |
			po::command_line_style::allow_long_disguise)
			.run(),
			vm);
		vm.notify();
	} catch (std::exception& e) {
		std::cout << e.what() << '\n' << desc << '\n';
		return FALSE;
	}

	if (vm.count("version")) {
		std::wcout << "Version: " << VERSION << '\n';
		return FALSE;
	}

	if (vm.count("help")) {
		std::wcout << szProgName << " Help\n\tVersion: " << VERSION << '\n';
		wprintf(
			L"%s runs a check against a performance counter.\n"
			L"You can use the following options to define its behaviour:\n\n", szProgName);
		std::cout << desc;
		wprintf(
			L"\nIt will then output a string looking something like this:\n\n"
			L"\tPERFMON CRITICAL \"\\Processor(_Total)\\%% Idle Time\" = 40.34 | "
			L"perfmon=40.34;20;40;; \"\\Processor(_Total)\\%% Idle Time\"=40.34\n\n"
			L"\"tPERFMON\" being the type of the check, \"CRITICAL\" the returned status\n"
			L"and \"40.34\" is the performance counters value.\n"
			L"%s' exit codes denote the following:\n"
			L" 0\tOK,\n\tNo Thresholds were exceeded\n"
			L" 1\tWARNING,\n\tThe warning was broken, but not the critical threshold\n"
			L" 2\tCRITICAL,\n\tThe critical threshold was broken\n"
			L" 3\tUNKNOWN, \n\tNo check could be performed\n\n"
			, szProgName);
		return 0;
	}

	if (vm.count("warning")) {
		try {
			printInfo.tWarn = threshold(vm["warning"].as<std::wstring>());
		} catch (std::invalid_argument& e) {
			std::wcout << e.what() << '\n';
			return FALSE;
		}
	}

	if (vm.count("critical")) {
		try {
			printInfo.tCrit = threshold(vm["critical"].as<std::wstring>());
		} catch (std::invalid_argument& e) {
			std::wcout << e.what() << '\n';
			return FALSE;
		}
	}

	if (vm.count("fmt-countertype")) {
		if (vm["fmt-countertype"].as<std::wstring>().compare(L"double"))
			printInfo.dwRequestedType = PDH_FMT_DOUBLE;
		else if (vm["fmt-countertype"].as<std::wstring>().compare(L"int64"))
			printInfo.dwRequestedType = PDH_FMT_LARGE;
		else if (vm["fmt-countertype"].as<std::wstring>().compare(L"long"))
			printInfo.dwRequestedType = PDH_FMT_LONG;
		else {
			std::wcout << "Unknown value type " << vm["fmt-countertype"].as<std::wstring>() << '\n';
			return FALSE;
		}
	}

	if (vm.count("performance-counter"))
		printInfo.wsFullPath = vm["performance-counter"].as<std::wstring>();

	if (vm.count("performance-wait"))
		printInfo.dwPerformanceWait = vm["performance-wait"].as<DWORD>();

	return TRUE;
}
int GoProcessing(const tagCMDL & cmdl)
{
	int mode = cmdl.mode;

	CreateDirectory(cmdl.temppath, NULL);

	wchar_t tempfile[MAX_PATH];
	if( lstrlen(cmdl.temppath) == 0 )
	{
		// кодируем в файл по умолчанию
		StringCchCopy(tempfile, MAX_PATH, cmdl.outputfilename);
	}else
	{
		StringCchCopy(tempfile, MAX_PATH, cmdl.temppath);
		if( tempfile[ lstrlen(tempfile) -1 ] != L'\\')
			StringCchCat(tempfile, MAX_PATH, L"\\");
		StringCchCat(tempfile, MAX_PATH, PathFindFileName(cmdl.outputfilename));
	}


	HWND fwwnd = FindWindow(wndclassnameW, NULL);
	if(fwwnd == NULL) return 4;

	int pos = -1;
	while( pos < 0 )
	{
		if( !isProcessExist() ) // проверяем мьютекс
			return 0; // преждевременный выход
		pos = (int)SendMessage(fwwnd, MES_ONNEWTHREAD, 0, 0);
		if( pos >= 0 ) break;
		Sleep(200);
	}

	//////////////////////////////////////////////////////////////////////////
	// название файла
	if( !SendFileName(fwwnd, cmdl.outputfilename, pos) )
		return 0; // выход, лажа.

	//////////////////////////////////////////////////////////////////////////
	// читаем файл из stdin и создаём временный wav-файл
	if( !ReadAndCreateFile(tempfile) )
		return 5;
	DWORD len = CorrectHeader(tempfile);
	//////////////////////////////////////////////////////////////////////////
	// сообщаем длинну трэка: sec * 4 * 44100
	if( !MySendMessage(fwwnd, MES_SENDLENGTH, pos, len) )
	{
		DeleteFile(tempfile);
		return 0;
	}
	if( len )
	{
		UINT newpriority = (UINT)SendMessage(fwwnd, MES_GETPRIORITY, 0, 0);
		SetPriorityClass(GetCurrentProcess(), newpriority );

		if( !RunProcessing(tempfile, mode, fwwnd, pos) )
		{
			DeleteFile(tempfile);
			return 0; // пытаемся безболезненно свалить :D
		}
	}
	DeleteFile(tempfile);
	if( !TrimFile(cmdl.outputfilename, pos) )
		return 6;

	return 0;
}
Example #29
0
INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo) 
{
	WCHAR namePath[MAX_PATH];
	GetModuleFileName(NULL, namePath, MAX_PATH);
	WCHAR *progName = PathFindFileName(namePath);

	po::options_description desc;

	desc.add_options()
		("help,h", "Print help message and exit")
		("version,V", "Print version and exit")
		("debug,d", "Verbose/Debug output")
		("user,u", po::wvalue<std::wstring>(), "Count only processes of user")
		("warning,w", po::wvalue<std::wstring>(), "Warning threshold")
		("critical,c", po::wvalue<std::wstring>(), "Critical threshold")
		;

	po::basic_command_line_parser<WCHAR> parser(ac, av);

	try {
		po::store(
			parser
			.options(desc)
			.style(
			po::command_line_style::unix_style |
			po::command_line_style::allow_long_disguise)
			.run(),
			vm);
		vm.notify();
	} catch (std::exception& e) {
		std::cout << e.what() << '\n' << desc << '\n';
		return 3;
	}

	if (vm.count("help")) {
		std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n';
		wprintf(
			L"%s is a simple program to check a machines processes.\n"
			L"You can use the following options to define its behaviour:\n\n", progName);
		std::cout << desc;
		wprintf(
			L"\nIt will then output a string looking something like this:\n\n"
			L"\tPROCS WARNING 67 | load=67;50;90;0\n\n"
			L"\"PROCS\" being the type of the check, \"WARNING\" the returned status\n"
			L"and \"67\" is the returned value.\n"
			L"The performance data is found behind the \"|\", in order:\n"
			L"returned value, warning threshold, critical threshold, minimal value and,\n"
			L"if applicable, the maximal value. Performance data will only be displayed when\n"
			L"you set at least one threshold\n\n"
			L"For \"-user\" option keep in mind you need root to see other users processes\n\n"
			L"%s' exit codes denote the following:\n"
			L" 0\tOK,\n\tNo Thresholds were broken or the programs check part was not executed\n"
			L" 1\tWARNING,\n\tThe warning, but not the critical threshold was broken\n"
			L" 2\tCRITICAL,\n\tThe critical threshold was broken\n"
			L" 3\tUNKNOWN, \n\tThe program experienced an internal or input error\n\n"
			L"Threshold syntax:\n\n"
			L"-w THRESHOLD\n"
			L"warn if threshold is broken, which means VALUE > THRESHOLD\n"
			L"(unless stated differently)\n\n"
			L"-w !THRESHOLD\n"
			L"inverts threshold check, VALUE < THRESHOLD (analogous to above)\n\n"
			L"-w [THR1-THR2]\n"
			L"warn is VALUE is inside the range spanned by THR1 and THR2\n\n"
			L"-w ![THR1-THR2]\n"
			L"warn if VALUE is outside the range spanned by THR1 and THR2\n\n"
			L"-w THRESHOLD%%\n"
			L"if the plugin accepts percentage based thresholds those will be used.\n"
			L"Does nothing if the plugin does not accept percentages, or only uses\n"
			L"percentage thresholds. Ranges can be used with \"%%\", but both range values need\n"
			L"to end with a percentage sign.\n\n"
			L"All of these options work with the critical threshold \"-c\" too."
			, progName);
		std::cout << '\n';
		return 0;
	}

	if (vm.count("version")) {
		std::wcout << "Version: " << VERSION << '\n';
		return 0;
	}

	if (vm.count("warning")) {
		try {
			printInfo.warn = threshold(vm["warning"].as<std::wstring>());
		} catch (std::invalid_argument& e) {
			std::cout << e.what() << '\n';
			return 3;
		}
	}
	if (vm.count("critical")) {
		try {
			printInfo.crit = threshold(vm["critical"].as<std::wstring>());
		} catch (std::invalid_argument& e) {
			std::cout << e.what() << '\n';
			return 3;
		}
	}

	if (vm.count("user")) 
		printInfo.user = vm["user"].as<std::wstring>();

	if (vm.count("debug"))
		debug = TRUE;

	return -1;
}
Example #30
0
// operations
BOOL CMP3Info::Open(CDuiString strFile)
{
	Clear(); // make sure all data is blank

	HANDLE hFile = NULL;
	if ((hFile = ::CreateFile(strFile.GetData(),GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL))
		!= INVALID_HANDLE_VALUE)
	{
		int nNextSearch = 0;

		MP3FRAMEHEADER sFrameHeader;
		memset(&sFrameHeader,0,sizeof(sFrameHeader));

		//int nFrameBR;
		double dLength = 0; // total length of file
		ULONG nTotalBR = 0; // total frames bit rate (used to calc. average)
		DWORD dwNumBytesRead;

		// read frame by frame
		/*while (GetNextFrameHeader(hFile,&sFrameHeader,nNextSearch))
		{
			if (m_nFrames < 1)
			{
				// first read the MPEG version
				switch (sFrameHeader.mpegver)
				{
					case 0: m_enMPEGVersion = MPEGVER_25; break;
					case 1: m_enMPEGVersion = MPEGVER_NA; break;
					case 2: m_enMPEGVersion = MPEGVER_2; break;
					case 3: m_enMPEGVersion = MPEGVER_1; break;
				}

				// next, read the MPEG layer description
				switch (sFrameHeader.mpeglayer)
				{
					case 0: m_nMPEGLayer = 0; break;
					case 1: m_nMPEGLayer = 3; break;
					case 2: m_nMPEGLayer = 2; break;
					case 3: m_nMPEGLayer = 1; break;
				}

				// read the bit for CRC or no CRC
				m_bHasCRC = sFrameHeader.hascrc;
			}

			// read the bitrate, based on the mpeg layer and version
			if (m_nMPEGLayer > 0)
			{
				if (m_enMPEGVersion == MPEGVER_1)
				{
					switch (m_nMPEGLayer)
					{
						case 1: nFrameBR = g_nMP3BitRate[0][sFrameHeader.bitrate]; break;
						case 2: nFrameBR = g_nMP3BitRate[1][sFrameHeader.bitrate]; break;
						case 3: nFrameBR = g_nMP3BitRate[2][sFrameHeader.bitrate]; break;
					}
				}
				else
				{
					switch (m_nMPEGLayer)
					{
						case 1: nFrameBR = g_nMP3BitRate[3][sFrameHeader.bitrate]; break;
						case 2: nFrameBR = g_nMP3BitRate[4][sFrameHeader.bitrate]; break;
						case 3: nFrameBR = g_nMP3BitRate[5][sFrameHeader.bitrate]; break;
					}
				}
			}

			// if nFrameBR is 0 or -1 then the bitrate is either free or bad
			if (nFrameBR > 0)
				nTotalBR += nFrameBR;

			// read sample rate
			if (m_enMPEGVersion == MPEGVER_1)
				switch (sFrameHeader.samplerate)
				{
					case 0: m_nSampleRate = 44100; break;
					case 1: m_nSampleRate = 48000; break;
					case 2: m_nSampleRate = 32000; break;
				}
			else if (m_enMPEGVersion == MPEGVER_2)
				switch (sFrameHeader.samplerate)
				{
					case 0: m_nSampleRate = 22050; break;
					case 1: m_nSampleRate = 24000; break;
					case 2: m_nSampleRate = 16000; break;
				}
			else if (m_enMPEGVersion == MPEGVER_25)
				switch (sFrameHeader.samplerate)
				{
					case 0: m_nSampleRate = 11025; break;
					case 1: m_nSampleRate = 12000; break;
					case 2: m_nSampleRate = 8000; break;
				}

			if (!m_nSampleRate)
				break;

			// read channel mode
			switch (sFrameHeader.chanmode)
			{
				case 0: m_enChannelMode = MP3CM_STEREO; break;
				case 1: m_enChannelMode = MP3CM_JOINT_STEREO; break;
				case 2: m_enChannelMode = MP3CM_DUAL_CHANNEL; break;
				case 3: m_enChannelMode = MP3CM_SINGLE_CHANNEL; break;
			}

			// read the copyright and original bits
			m_bCopyrighted = sFrameHeader.copyright;
			m_bOriginal = sFrameHeader.original;

			// read the emphasis
			switch (sFrameHeader.emphasis)
			{
				case 0: m_enEmphasis = MP3EM_NONE; break;
				case 1: m_enEmphasis = MP3EM_50_15_MS; break;
				case 2: m_enEmphasis = MP3EM_RESERVED; break;
				case 3: m_enEmphasis = MP3EM_CCIT_J17; break;
			}

			// don't read the CRC -- maybe in a future version

			// nNextSearch = frame length, in bytes
			if (m_nMPEGLayer == 1)
				nNextSearch = (12000 * nFrameBR / m_nSampleRate + sFrameHeader.padding) * 4;
			else
				nNextSearch = 144000 * nFrameBR / m_nSampleRate + sFrameHeader.padding;

			nNextSearch -= 4; // the frame header was already read

			m_nFrames++;

			// calculate the length in seconds of this frame and add it to total
			if (nFrameBR)
				dLength += (double)(nNextSearch + 4) * 8 / (nFrameBR * 1000);
		}*/

		// if at least one frame was read, the MP3 is considered valid
		if (m_nFrames > 0)
		{
			m_dwValidity |= MP3VLD_DATA_VALID;
			m_nBitRate = nTotalBR / m_nFrames; // average the bitrate
			m_nLength = (int)dLength;
		}

		// read the ID3 tag

		// set up a structure for reading the ID3 version 1 tag
		MP3ID3V1INFO sID3V1;
		ZeroMemory(&sID3V1, sizeof(sID3V1)); 

		if (SetFilePointer(hFile,-128,NULL,FILE_END) != INVALID_SET_FILE_POINTER)
		{
			if( ReadFile(hFile,&sID3V1,128,&dwNumBytesRead,NULL))
			{
				if( dwNumBytesRead == 128  && strncmp(sID3V1.Identify , ("TAG"),3) == 0)
				{ 
					m_strTitle  = CSECommonUtil::StringToDuiString(sID3V1.Title);
					m_strArtist = CSECommonUtil::StringToDuiString(sID3V1.Artist);
					m_strAlbum  = CSECommonUtil::StringToDuiString(sID3V1.Album);

					m_strYear = CSECommonUtil::StringToDuiString(sID3V1.Year);

					// now, depending on the reserved byte, the comment is 28 bytes or 30 bytes
					if (sID3V1.CommentFlag)
					{
						// NOTE: even if sID3V1.album is of size 28, the reserved and tracknum
						// are right after, so they'll be included in the comment, which is what
						// we want
						char strTemp[30];
						memcpy(strTemp,sID3V1.Comment,30); 
						m_strComment = CSECommonUtil::StringToDuiString(strTemp); 
					}
					else
					{
						char strTemp[30];
						memcpy(strTemp,sID3V1.Comment,28);
						m_strComment = CSECommonUtil::StringToDuiString(strTemp);
						m_nTrack = sID3V1.Track;
						m_nGenre = sID3V1.Genre;
					}

					m_dwValidity |= MP3VLD_ID3V1_VALID;
				}
				else
				{
					m_strTitle = PathFindFileName(strFile.GetData());
					m_strArtist= PathFindFileName(strFile.GetData());
				}
			}
		}

		m_strFile = strFile;
		CloseHandle(hFile);
	}
	else
		return FALSE;

	return TRUE;
}