Exemple #1
0
/* Tar file extraction
 * gzFile in, handle of input tarball opened with gzopen
 * int cm, compressionMethod
 * int junkPaths, nonzero indicates to ignore stored path (don't create directories)
 * enum KeepMode keep, indicates to perform if file exists
 * int iCnt, char *iList[], argv style list of files to extract, {0,NULL} for all
 * int xCnt, char *xList[], argv style list of files NOT to extract, {0,NULL} for none
 * int failOnHardLinks, if nonzero then will treat failure to create a hard link same as
 *   failure to create a regular file, 0 prints a warning if fails - note that hardlinks
 *   will always fail on Windows prior to NT 5 (Win 2000) or later and non NTFS file systems.
 *
 * returns 0 (or positive value) on success
 * returns negative value on error, where
 *   -1 means error reading from tarball
 *   -2 means error extracting file from tarball
 *   -3 means error creating hard link
 */
int tgz_extract(gzFile in, int cm, int junkPaths, enum KeepMode keep, int iCnt, TCHAR *iList[], int xCnt, TCHAR *xList[], int failOnHardLinks)
{
  int           getheader = 1;    /* assume initial input has a tar header */
  HANDLE        outfile = INVALID_HANDLE_VALUE;

  union         tar_buffer buffer;
  unsigned long remaining;
  TCHAR          fname[BLOCKSIZE]; /* must be >= BLOCKSIZE bytes */
  time_t        tartime;

  /* do any prep work for extracting from compressed TAR file */
  if (cm_init(in, cm))
  {
    PrintMessage(_T("tgz_extract: unable to initialize decompression method."));
    cm_cleanup(cm);
    return -1;
  }
  
  while (1)
  {
    if (readBlock(cm, &buffer) < 0) return -1;
      
    /*
     * If we have to get a tar header
     */
    if (getheader >= 1)
    {
      /*
       * if we met the end of the tar
       * or the end-of-tar block,
       * we are done
       */
      if (/* (len == 0)  || */ (buffer.header.name[0]== 0)) break;

      /* compute and check header checksum, support signed or unsigned */
      if (!valid_checksum(&(buffer.header)))
      {
        PrintMessage(_T("tgz_extract: bad header checksum"));
        cm_cleanup(cm);
        return -1;
      }

      /* store time, so we can set the timestamp on files */
      tartime = (time_t)getoct(buffer.header.mtime,12);

      /* copy over filename chunk from header, avoiding overruns */
      if (getheader == 1) /* use normal (short or posix long) filename from header */
      {
        /* NOTE: prepends any prefix, including separator, and ensures terminated */
        memset(fname, 0, sizeof(fname));
		getFullName(&buffer, fname);
      }
      else /* use (GNU) long filename that preceeded this header */
      {
#if 0
        /* if (strncmp(fname,buffer.header.name,SHORTNAMESIZE-1) != 0) */
        char fs[SHORTNAMESIZE];   /* force strings to same max len, then compare */
        lstrcpyn(fs, fname, SHORTNAMESIZE);
        fs[SHORTNAMESIZE-1] = '\0';
        buffer.header.name[SHORTNAMESIZE-1] = '\0';
        if (lstrcmp(fs, buffer.header.name) != 0)
        {
          PrintMessage(_T("tgz_extract: mismatched long filename"));
          cm_cleanup(cm);
          return -1;
        }
#else
		PrintMessage(_T("tgz_extract: using GNU long filename [%s]"), fname);
#endif
      }
      /* LogMessage("buffer.header.name is:");  LogMessage(fname); */


      switch (buffer.header.typeflag)
      {
        case DIRTYPE:
		  dirEntry:
          if (!junkPaths)
          {
            safetyStrip(fname);
            makedir(fname);
          }
	      break;
		case LNKTYPE:   /* hard link */ 
		case CONTTYPE:  /* contiguous file, for compatibility treat as normal */
        case REGTYPE:
        case AREGTYPE:
	      /* Note: a file ending with a / may actually be a BSD tar directory entry */
	      if (fname[strlen(fname)-1] == '/')
	        goto dirEntry;

	      remaining = getoct(buffer.header.size,12);
	      if ( /* add (remaining > 0) && to ignore 0 zero byte files */
               ( (iList == NULL) || (matchname(fname, iCnt, iList, junkPaths)) ) &&
               (!matchname(fname, xCnt, xList, junkPaths))
             )
	      {
			  if (!junkPaths) /* if we want to use paths as stored */
			  {
	              /* try creating directory */
	              TCHAR *p = tstrrchr(fname, '/');
	              if (p != NULL) 
	              {
	                *p = '\0';
	                makedir(fname);
	                *p = '/';
	              }
			  }
			  else
			  {
	              /* try ignoring directory */
	              TCHAR *p = tstrrchr(fname, '/');
	              if (p != NULL) 
	              {
	                /* be sure terminating '\0' is copied and */
	                /* use ansi memcpy equivalent that handles overlapping regions */
	                MoveMemory(fname, p+1, (strlen(p+1) + 1) * sizeof(TCHAR) );
	              }
	          }
	          if (*fname) /* if after stripping path a fname still exists */
	          {
	            /* Attempt to open the output file and report action taken to user */
	            const TCHAR szERRMsg[] = _T("Error: Could not create file "),
	                        szSUCMsg[] = _T("Writing "),
	                        szSKPMsg[] = _T("Skipping ");
	            const TCHAR * szMsg = szSUCMsg;

	            safetyStrip(fname);

				if (buffer.header.typeflag == LNKTYPE)
				{
					outfile = INVALID_HANDLE_VALUE;
					/* create a hardlink if possible, else produce just a warning unless failOnHardLinks is true */
					if (!MakeHardLink(fname, buffer.header.linkname))
					{
						PrintMessage(_T("Warning: unable to create hard link %s [%d]"), fname, GetLastError());
						if (failOnHardLinks) 
						{
							cm_cleanup(cm);
							return -3;
						}
					}
					else
					{
						outfile = CreateFile(fname,GENERIC_WRITE,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
						goto setTimeAndCloseFile;
					}
				} else 
				{
	            /* Open the file for writing mode, creating if doesn't exist and truncating if exists and overwrite mode */
	            outfile = CreateFile(fname,GENERIC_WRITE,FILE_SHARE_READ,NULL,(keep==OVERWRITE)?CREATE_ALWAYS:CREATE_NEW,FILE_ATTRIBUTE_NORMAL,NULL);

	            /* failed to open file, either valid error (like open) or it already exists and in a keep mode */
	            if (outfile == INVALID_HANDLE_VALUE)
	            {
	              /* if skip existing or only update existing and failed to open becauses exists */
	              if ((keep!=OVERWRITE) && (GetLastError()==ERROR_FILE_EXISTS))
	              {
	                /* assume skipping initially (mode==SKIP or ==UPDATE with existing file newer) */
	                szMsg = szSKPMsg; /* and update output message accordingly */

					/* if in update mode, check filetimes and reopen in overwrite mode */
	                if (keep == UPDATE)
	                {
	                  FILETIME ftm_a;
                      HANDLE h;
                      WIN32_FIND_DATA ffData;
 
	                  cnv_tar2win_time(tartime, &ftm_a); /* archive file time */
	                  h = FindFirstFile(fname, &ffData); /* existing file time */

                      if (h!=INVALID_HANDLE_VALUE)
                        FindClose(h);  /* cleanup search handle */
                      else
                        goto ERR_OPENING;

                      /* compare date+times, is one in tarball newer? */
                      if (*((LONGLONG *)&ftm_a) > *((LONGLONG *)&(ffData.ftLastWriteTime)))
                      {
                        outfile = CreateFile(fname,GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
                        if (outfile == INVALID_HANDLE_VALUE) goto ERR_OPENING;
                        szMsg = szSUCMsg;
                      }
	                }
	              }
	              else /* in overwrite mode or failed for some other error than exists */
	              {
                    ERR_OPENING:
	                PrintMessage(_T("%s%s [%d]"), szERRMsg, fname, GetLastError());
	                cm_cleanup(cm);
	                return -2;
	              }
	            }

 	            /* Inform user of current extraction action (writing, skipping file XYZ) */
	            PrintMessage(_T("%s%s"), szMsg, fname);
				}
	          }
	      }
	      else
	          outfile = INVALID_HANDLE_VALUE;

	      /*
	       * could have no contents, in which case we close the file and set the times
	       */
	      if (remaining > 0)
	          getheader = 0;
		  else
	      {
	          setTimeAndCloseFile:
	          getheader = 1;
	          if (outfile != INVALID_HANDLE_VALUE)
	          {
	              FILETIME ftm;
 
	              cnv_tar2win_time(tartime, &ftm);
	              SetFileTime(outfile,&ftm,NULL,&ftm);
	              CloseHandle(outfile);
	              outfile = INVALID_HANDLE_VALUE;
	          }
		  }

	      break;
		case GNUTYPE_LONGLINK:
		case GNUTYPE_LONGNAME:
		{
	      remaining = getoct(buffer.header.size,12);
	      if (readBlock(cm, fname) < 0) return -1;
	      fname[BLOCKSIZE-1] = '\0';
	      if ((remaining >= BLOCKSIZE) || ((unsigned)strlen(fname) > remaining))
	      {
	          PrintMessage(_T("tgz_extract: invalid long name"));
	          cm_cleanup(cm);
	          return -1;
	      }
	      getheader = 2;
	      break;
		}
        default:
/*
	      if (action == TGZ_LIST)
	          printf(" %s     <---> %s\n",strtime(&tartime),fname);
*/
	      break;
      }
    }
    else  /* (getheader == 0) */
    {
      unsigned int bytes = (remaining > BLOCKSIZE) ? BLOCKSIZE : remaining;
	  unsigned long bwritten;

      if (outfile != INVALID_HANDLE_VALUE)
      {
          WriteFile(outfile,buffer.buffer,bytes,&bwritten,NULL);
		  if (bwritten != bytes)
          {
			  PrintMessage(_T("Error: write failed for %s"), fname);
              CloseHandle(outfile);
              DeleteFile(fname);

              cm_cleanup(cm);
              return -2;
          }
      }
      remaining -= bytes;
      if (remaining == 0) goto setTimeAndCloseFile;
    }
  } /* while(1) */
  
  cm_cleanup(cm);

  return 0;
}
Exemple #2
0
bool IsNeedCmd(BOOL bRootCmd, LPCWSTR asCmdLine, CEStr &szExe,
			   LPCWSTR* rsArguments /*= NULL*/, BOOL* rpbNeedCutStartEndQuot /*= NULL*/,
			   BOOL* rpbRootIsCmdExe /*= NULL*/, BOOL* rpbAlwaysConfirmExit /*= NULL*/, BOOL* rpbAutoDisableConfirmExit /*= NULL*/)
{
	bool rbNeedCutStartEndQuot = false;
	bool rbRootIsCmdExe = true;
	bool rbAlwaysConfirmExit = false;
	bool rbAutoDisableConfirmExit = false;

	wchar_t *pwszEndSpace;

	if (rsArguments) *rsArguments = NULL;

	bool lbRc = false;
	int iRc = 0;
	BOOL lbFirstWasGot = FALSE;
	LPCWSTR pwszCopy;
	int nLastChar;
	#ifdef _DEBUG
	CEStr szDbgFirst;
	#endif

	if (!asCmdLine || !*asCmdLine)
	{
		_ASSERTE(asCmdLine && *asCmdLine);
		goto wrap;
	}

	#ifdef _DEBUG
	// Это минимальные проверки, собственно к коду - не относятся
	bool bIsBatch = false;
	{
		LPCWSTR psz = asCmdLine;
		NextArg(&psz, szDbgFirst);
		psz = PointToExt(szDbgFirst);
		if (lstrcmpi(psz, L".cmd")==0 || lstrcmpi(psz, L".bat")==0)
			bIsBatch = true;
	}
	#endif

	if (!szExe.GetBuffer(MAX_PATH))
	{
		_ASSERTE(FALSE && "Failed to allocate MAX_PATH");
		lbRc = true;
		goto wrap;
	}
	szExe.Empty();

	if (!asCmdLine || *asCmdLine == 0)
	{
		_ASSERTE(asCmdLine && *asCmdLine);
		lbRc = true;
		goto wrap;
	}


	pwszCopy = asCmdLine;
	// cmd /c ""c:\program files\arc\7z.exe" -?"   // да еще и внутри могут быть двойными...
	// cmd /c "dir c:\"
	nLastChar = lstrlenW(pwszCopy) - 1;

	if (pwszCopy[0] == L'"' && pwszCopy[nLastChar] == L'"')
	{
		//if (pwszCopy[1] == L'"' && pwszCopy[2])
		//{
		//	pwszCopy ++; // Отбросить первую кавычку в командах типа: ""c:\program files\arc\7z.exe" -?"

		//	if (rbNeedCutStartEndQuot) *rbNeedCutStartEndQuot = TRUE;
		//}
		//else
			// глючила на ""F:\VCProject\FarPlugin\#FAR180\far.exe  -new_console""
			//if (wcschr(pwszCopy+1, L'"') == (pwszCopy+nLastChar)) {
			//	LPCWSTR pwszTemp = pwszCopy;
			//	// Получим первую команду (исполняемый файл?)
			//	if ((iRc = NextArg(&pwszTemp, szArg)) != 0) {
			//		//Parsing command line failed
			//		lbRc = true; goto wrap;
			//	}
			//	pwszCopy ++; // Отбросить первую кавычку в командах типа: "c:\arc\7z.exe -?"
			//	lbFirstWasGot = TRUE;
			//	if (rbNeedCutStartEndQuot) *rbNeedCutStartEndQuot = TRUE;
			//} else
		{
			// Will be dequoted in 'NextArg' function. Examples
			// "C:\GCC\msys\bin\make.EXE -f "makefile" COMMON="../../../plugins/common""
			// ""F:\VCProject\FarPlugin\#FAR180\far.exe  -new_console""
			// ""cmd""
			// cmd /c ""c:\program files\arc\7z.exe" -?"   // да еще и внутри могут быть двойными...
			// cmd /c "dir c:\"

			LPCWSTR pwszTemp = pwszCopy;

			// Получим первую команду (исполняемый файл?)
			if ((iRc = NextArg(&pwszTemp, szExe)) != 0)
			{
				//Parsing command line failed
				#ifdef WARN_NEED_CMD
				_ASSERTE(FALSE);
				#endif
				lbRc = true; goto wrap;
			}

			if (lstrcmpiW(szExe, L"start") == 0)
			{
				// Команду start обрабатывает только процессор
				#ifdef WARN_NEED_CMD
				_ASSERTE(FALSE);
				#endif
				lbRc = true; goto wrap;
			}

			LPCWSTR pwszQ = pwszCopy + 1 + lstrlen(szExe);
			wchar_t* pszExpand = NULL;

			if (*pwszQ != L'"' && IsExecutable(szExe, &pszExpand))
			{
				pwszCopy ++; // отбрасываем
				lbFirstWasGot = TRUE;

				if (pszExpand)
				{
					szExe.Set(pszExpand);
					SafeFree(pszExpand);
					if (rsArguments)
						*rsArguments = pwszQ;
				}

				rbNeedCutStartEndQuot = true;
			}
		}
	}

	// Получим первую команду (исполняемый файл?)
	if (!lbFirstWasGot)
	{
		szExe.Empty();

		// `start` command must be processed by processor itself
		if ((lstrcmpni(pwszCopy, L"start", 5) == 0)
			&& (!pwszCopy[5] || isSpace(pwszCopy[5])))
		{
			#ifdef WARN_NEED_CMD
			_ASSERTE(FALSE);
			#endif
			lbRc = true; goto wrap;
		}

		// 17.10.2010 - support executable file path without parameters, but with spaces in its path
		// 22.11.2015 - or some weirdness, like `C:\Program Files\CB/cb_console_runner.exe "C:\sources\app.exe"`
		LPCWSTR pchEnd = wcschr(pwszCopy, L' ');
		if (!pchEnd)
			pchEnd = pwszCopy + lstrlenW(pwszCopy);

		CEStr szTemp;
		DWORD nTempSize;
		while (pchEnd)
		{
			szTemp.Set(pwszCopy, (pchEnd - pwszCopy));
			_ASSERTE(szTemp[(pchEnd - pwszCopy)] == 0);

			// If this is a full path without environment variables
			if (((IsFilePath(szTemp, true) && !wcschr(szTemp, L'%'))
				// or file/dir may be found via env.var. substitution or searching in %PATH%
				|| FileExistsSearch((LPCWSTR)szTemp, szTemp))
				// Than check if it is a FILE (not a directory)
				&& FileExists(szTemp, &nTempSize) && nTempSize)
			{
				// OK, it an our executable?
				if (rsArguments)
					*rsArguments = pchEnd;
				szExe.Set(szTemp);
				break;
			}

			_ASSERTE(*pchEnd == 0 || *pchEnd == L' ');
			if (!*pchEnd)
				break;
			// Find next space after nonspace
			while (*(pchEnd) == L' ') pchEnd++;
			// If quoted string starts from here - it's supposed to be an argument
			if (*pchEnd == L'"')
			{
				// And we must not get here, because the executable must be already processed above
				// _ASSERTE(*pchEnd != L'"');
				break;
			}
			pchEnd = wcschr(pchEnd, L' ');
			if (!pchEnd)
				pchEnd = pwszCopy + lstrlenW(pwszCopy);
		}

		if (szExe[0] == 0)
		{
			if ((iRc = NextArg(&pwszCopy, szExe)) != 0)
			{
				//Parsing command line failed
				#ifdef WARN_NEED_CMD
				_ASSERTE(FALSE);
				#endif
				lbRc = true; goto wrap;
			}

			_ASSERTE(lstrcmpiW(szExe, L"start") != 0);

			// Обработка переменных окружения и поиск в PATH
			if (FileExistsSearch((LPCWSTR)szExe, szExe))
			{
				if (rsArguments)
					*rsArguments = pwszCopy;
			}
		}
	}

	if (!*szExe)
	{
		_ASSERTE(szExe[0] != 0);
	}
	else
	{
		// Если юзеру нужен редирект - то он должен явно указать ком.процессор
		// Иначе нереально (или достаточно сложно) определить, является ли символ
		// редиректом, или это просто один из аргументов команды...

		// "Левые" символы в имени файла (а вот в "первом аргументе" все однозначно)
		if (wcspbrk(szExe, L"?*<>|"))
		{
			rbRootIsCmdExe = TRUE; // запуск через "процессор"
			lbRc = true; goto wrap; // добавить "cmd.exe"
		}

		// если "путь" не указан
		if (wcschr(szExe, L'\\') == NULL)
		{
			bool bHasExt = (wcschr(szExe, L'.') != NULL);
			// Проверим, может это команда процессора (типа "DIR")?
			if (!bHasExt)
			{
				bool bIsCommand = false;
				wchar_t* pszUppr = lstrdup(szExe);
				if (pszUppr)
				{
					// избежать линковки на user32.dll
					//CharUpperBuff(pszUppr, lstrlen(pszUppr));
					for (wchar_t* p = pszUppr; *p; p++)
					{
						if (*p >= L'a' && *p <= 'z')
							*p -= 0x20;
					}

					const wchar_t* pszFind = gsInternalCommands;
					while (*pszFind)
					{
						if (lstrcmp(pszUppr, pszFind) == 0)
						{
							bIsCommand = true;
							break;
						}
						pszFind += lstrlen(pszFind)+1;
					}
					free(pszUppr);
				}
				if (bIsCommand)
				{
					#ifdef WARN_NEED_CMD
					_ASSERTE(FALSE);
					#endif
					rbRootIsCmdExe = TRUE; // запуск через "процессор"
					lbRc = true; goto wrap; // добавить "cmd.exe"
				}
			}

			// Try to find executable in %PATH%
			{
				#ifndef CONEMU_MINIMAL
				MWow64Disable wow; wow.Disable(); // Disable Wow64 file redirector
				#endif
				apiSearchPath(NULL, szExe, bHasExt ? NULL : L".exe", szExe);
			}
		} // end: if (wcschr(szExe, L'\\') == NULL)
	}

	// Если szExe не содержит путь к файлу - запускаем через cmd
	// "start "" C:\Utils\Files\Hiew32\hiew32.exe C:\00\Far.exe"
	if (!IsFilePath(szExe))
	{
		#ifdef WARN_NEED_CMD
		_ASSERTE(FALSE);
		#endif
		rbRootIsCmdExe = TRUE; // запуск через "процессор"
		lbRc = true; goto wrap; // добавить "cmd.exe"
	}

	//pwszCopy = wcsrchr(szArg, L'\\'); if (!pwszCopy) pwszCopy = szArg; else pwszCopy ++;
	pwszCopy = PointToName(szExe);
	//2009-08-27
	pwszEndSpace = szExe.ms_Val + lstrlenW(szExe) - 1;

	while ((*pwszEndSpace == L' ') && (pwszEndSpace > szExe))
	{
		*(pwszEndSpace--) = 0;
	}

#ifndef __GNUC__
#pragma warning( push )
#pragma warning(disable : 6400)
#endif

	if (lstrcmpiW(pwszCopy, L"cmd")==0 || lstrcmpiW(pwszCopy, L"cmd.exe")==0
		|| lstrcmpiW(pwszCopy, L"tcc")==0 || lstrcmpiW(pwszCopy, L"tcc.exe")==0)
	{
		rbRootIsCmdExe = TRUE; // уже должен быть выставлен, но проверим
		rbAlwaysConfirmExit = TRUE; rbAutoDisableConfirmExit = FALSE;
		_ASSERTE(!bIsBatch);
		lbRc = false; goto wrap; // уже указан командный процессор, cmd.exe в начало добавлять не нужно
	}


	// Issue 1211: Decide not to do weird heuristic.
	//   If user REALLY needs redirection (root command, huh?)
	//   - he must call "cmd /c ..." directly
	// Если есть одна из команд перенаправления, или слияния - нужен CMD.EXE
	if (!bRootCmd)
	{
		if (wcschr(asCmdLine, L'&') ||
			wcschr(asCmdLine, L'>') ||
			wcschr(asCmdLine, L'<') ||
			wcschr(asCmdLine, L'|') ||
			wcschr(asCmdLine, L'^') // или экранирования
			)
		{
			#ifdef WARN_NEED_CMD
			_ASSERTE(FALSE);
			#endif
			lbRc = true; goto wrap;
		}
	}

	//if (lstrcmpiW(pwszCopy, L"far")==0 || lstrcmpiW(pwszCopy, L"far.exe")==0)
	if (IsFarExe(pwszCopy))
	{
		bool bFound = (wcschr(pwszCopy, L'.') != NULL);
		// Если указали при запуске просто "far" - это может быть батник, расположенный в %PATH%
		if (!bFound)
		{
			CEStr szSearch;
			if (apiSearchPath(NULL, pwszCopy, L".exe", szSearch))
			{
				if (lstrcmpi(PointToExt(szSearch), L".exe") == 0)
					bFound = true;
			}
		}

		if (bFound)
		{
			rbAutoDisableConfirmExit = TRUE;
			rbRootIsCmdExe = FALSE; // FAR!
			_ASSERTE(!bIsBatch);
			lbRc = false; goto wrap; // уже указан исполняемый файл, cmd.exe в начало добавлять не нужно
		}
	}

	if (IsExecutable(szExe))
	{
		rbRootIsCmdExe = FALSE; // Для других программ - буфер не включаем
		_ASSERTE(!bIsBatch);
		lbRc = false; goto wrap; // Запускается конкретная консольная программа. cmd.exe не требуется
	}

	//Можно еще Доделать поиски с: SearchPath, GetFullPathName, добавив расширения .exe & .com
	//хотя фар сам формирует полные пути к командам, так что можно не заморачиваться
	#ifdef WARN_NEED_CMD
	_ASSERTE(FALSE);
	#endif
	rbRootIsCmdExe = TRUE;
#ifndef __GNUC__
#pragma warning( pop )
#endif

	lbRc = true;
wrap:
	if (rpbNeedCutStartEndQuot)
		*rpbNeedCutStartEndQuot = rbNeedCutStartEndQuot;
	if (rpbRootIsCmdExe)
		*rpbRootIsCmdExe = rbRootIsCmdExe;
	if (rpbAlwaysConfirmExit)
		*rpbAlwaysConfirmExit = rbAlwaysConfirmExit;
	if (rpbAutoDisableConfirmExit)
		*rpbAutoDisableConfirmExit = rbAutoDisableConfirmExit;
	return lbRc;
}
Exemple #3
0
static void test_ReadAndWriteProperties(void)
{
    HRESULT hr;
    IUniformResourceLocatorA *urlA;
    IUniformResourceLocatorA *urlAFromFile;
    WCHAR fileNameW[MAX_PATH];
    static const WCHAR shortcutW[] = {'t','e','s','t','s','h','o','r','t','c','u','t','.','u','r','l',0};
    WCHAR iconPath[] = {'f','i','l','e',':','/','/','/','C',':','/','a','r','b','i','t','r','a','r','y','/','i','c','o','n','/','p','a','t','h',0};
    int iconIndex = 7;
    char testurl[] = "http://some/bogus/url.html";
    PROPSPEC ps[2];
    ps[0].ulKind = PRSPEC_PROPID;
    U(ps[0]).propid = PID_IS_ICONFILE;
    ps[1].ulKind = PRSPEC_PROPID;
    U(ps[1]).propid = PID_IS_ICONINDEX;

    /* Make sure we have a valid temporary directory */
    GetTempPathW(MAX_PATH, fileNameW);
    lstrcatW(fileNameW, shortcutW);

    hr = CoCreateInstance(&CLSID_InternetShortcut, NULL, CLSCTX_ALL, &IID_IUniformResourceLocatorA, (void**)&urlA);
    if (hr == S_OK)
    {
        IPersistFile *pf;
        IPropertyStorage *pPropStgWrite;
        IPropertySetStorage *pPropSetStg;
        PROPVARIANT pv[2];

        /* We need to set a URL -- IPersistFile refuses to save without one. */
        hr = urlA->lpVtbl->SetURL(urlA, testurl, 0);
        ok(hr == S_OK, "Failed to set a URL.  hr=0x%x\n", hr);

        /* Write this shortcut out to a file so that we can test reading it in again. */
        hr = urlA->lpVtbl->QueryInterface(urlA, &IID_IPersistFile, (void **) &pf);
        ok(hr == S_OK, "Failed to get the IPersistFile for writing.  hr=0x%x\n", hr);

        hr = IPersistFile_Save(pf, fileNameW, TRUE);
        ok(hr == S_OK, "Failed to save via IPersistFile. hr=0x%x\n", hr);

        IPersistFile_Release(pf);

        pv[0].vt = VT_LPWSTR;
        U(pv[0]).pwszVal = (void *) iconPath;
        pv[1].vt = VT_I4;
        U(pv[1]).iVal = iconIndex;
        hr = urlA->lpVtbl->QueryInterface(urlA, &IID_IPropertySetStorage, (void **) &pPropSetStg);
        ok(hr == S_OK, "Unable to get an IPropertySetStorage, hr=0x%x\n", hr);

        hr = IPropertySetStorage_Open(pPropSetStg, &FMTID_Intshcut, STGM_READWRITE | STGM_SHARE_EXCLUSIVE, &pPropStgWrite);
        ok(hr == S_OK, "Unable to get an IPropertyStorage for writing, hr=0x%x\n", hr);

        hr = IPropertyStorage_WriteMultiple(pPropStgWrite, 2, ps, pv, 0);
        ok(hr == S_OK, "Unable to set properties, hr=0x%x\n", hr);

        hr = IPropertyStorage_Commit(pPropStgWrite, STGC_DEFAULT);
        ok(hr == S_OK, "Failed to commit properties, hr=0x%x\n", hr);

        pPropStgWrite->lpVtbl->Release(pPropStgWrite);
        urlA->lpVtbl->Release(urlA);
        IPropertySetStorage_Release(pPropSetStg);
    }
    else
        skip("could not create a CLSID_InternetShortcut for property tests, hr=0x%x\n", hr);

    hr = CoCreateInstance(&CLSID_InternetShortcut, NULL, CLSCTX_ALL, &IID_IUniformResourceLocatorA, (void**)&urlAFromFile);
    if (hr == S_OK)
    {
        IPropertySetStorage *pPropSetStg;
        IPropertyStorage *pPropStgRead;
        PROPVARIANT pvread[2];
        IPersistFile *pf;
        LPSTR url = NULL;

        /* Now read that .url file back in. */
        hr = urlAFromFile->lpVtbl->QueryInterface(urlAFromFile, &IID_IPersistFile, (void **) &pf);
        ok(hr == S_OK, "Failed to get the IPersistFile for reading.  hr=0x%x\n", hr);

        hr = IPersistFile_Load(pf, fileNameW, 0);
        ok(hr == S_OK, "Failed to load via IPersistFile. hr=0x%x\n", hr);
        IPersistFile_Release(pf);


        hr = urlAFromFile->lpVtbl->GetURL(urlAFromFile, &url);
        ok(hr == S_OK, "Unable to get url from file, hr=0x%x\n", hr);
        ok(lstrcmp(url, testurl) == 0, "Wrong url read from file: %s\n",url);


        hr = urlAFromFile->lpVtbl->QueryInterface(urlAFromFile, &IID_IPropertySetStorage, (void **) &pPropSetStg);
        ok(hr == S_OK, "Unable to get an IPropertySetStorage, hr=0x%x\n", hr);

        hr = IPropertySetStorage_Open(pPropSetStg, &FMTID_Intshcut, STGM_READ | STGM_SHARE_EXCLUSIVE, &pPropStgRead);
        ok(hr == S_OK, "Unable to get an IPropertyStorage for reading, hr=0x%x\n", hr);

        hr = IPropertyStorage_ReadMultiple(pPropStgRead, 2, ps, pvread);
        ok(hr == S_OK, "Unable to read properties, hr=0x%x\n", hr);

        todo_wine /* Wine doesn't yet support setting properties after save */
        {
            ok(U(pvread[1]).iVal == iconIndex, "Read wrong icon index: %d\n", U(pvread[1]).iVal);

            ok(lstrcmpW(U(pvread[0]).pwszVal, iconPath) == 0, "Wrong icon path read: %s\n", wine_dbgstr_w(U(pvread[0]).pwszVal));
        }

        PropVariantClear(&pvread[0]);
        PropVariantClear(&pvread[1]);
        IPropertyStorage_Release(pPropStgRead);
        IPropertySetStorage_Release(pPropSetStg);
        urlAFromFile->lpVtbl->Release(urlAFromFile);
        DeleteFileW(fileNameW);
    }
Exemple #4
0
BOOL CALLBACK SERVER::KeyServiceName_Compare (LPHASHLISTKEY pKey, PVOID pObject, PVOID pData)
{
   return !lstrcmp (((LPSERVICE)pObject)->m_szName, (LPTSTR)pData);
}
/*!
 *  This function is used to determine if a control can be safely clipped
 *  out of the parent window client area when it is repainted, usually
 *  after a resize operation.
 *  
 *  @param layout Reference to a @c LAYOUTINFO structure for the control
 *  
 *  @return The return value is @c TRUE if clipping is supported by the
 *          control, @c FALSE otherwise.
 *
 *  @remarks The default implementation tries to identify @a clippable
 *           windows by their class name and window style.
 *        @n Override this function if you need a different behavior or if
 *           you have custom controls that fail to be identified.
 *
 *  @sa NeedsRefresh InitResizeProperties
 */
BOOL CResizableLayout::LikesClipping(const LAYOUTINFO& layout) const
{
	if (layout.bMsgSupport)
	{
		CLIPPINGPROPERTY clipping;
		if (Send_LikesClipping(layout.hWnd, &clipping))
			return clipping.bLikesClipping;
	}

	DWORD style = ::GetWindowLong(layout.hWnd, GWL_STYLE);

	// skip windows that wants background repainted
	if (0 == lstrcmp(layout.sWndClass, WC_BUTTON))
	{
		CRect rect;
		switch (style & _BS_TYPEMASK)
		{
		case BS_GROUPBOX:
			return FALSE;

		case BS_OWNERDRAW:
			// ownerdraw buttons must return correct hittest code
			// to notify their transparency to the system and this library
			// or they could use the registered message (more reliable)
			::GetWindowRect(layout.hWnd, &rect);
			::SendMessage(layout.hWnd, WM_NCCALCSIZE, FALSE, (LPARAM)&rect);
			if ( HTTRANSPARENT == ::SendMessage(layout.hWnd,
				WM_NCHITTEST, 0, MAKELPARAM(rect.left, rect.top)) )
				return FALSE;
			break;
		}
		return TRUE;
	}
	else if (0 == lstrcmp(layout.sWndClass, WC_STATIC))
	{
		switch (style & SS_TYPEMASK)
		{
		case SS_LEFT:
		case SS_CENTER:
		case SS_RIGHT:
		case SS_LEFTNOWORDWRAP:
			// text
		case SS_BLACKRECT:
		case SS_GRAYRECT:
		case SS_WHITERECT:
			// filled rects
		case SS_ETCHEDHORZ:
		case SS_ETCHEDVERT:
			// etched lines
		case SS_BITMAP:
			// bitmaps
			return TRUE;
			break;

		case SS_ICON:
		case SS_ENHMETAFILE:
			if (style & SS_CENTERIMAGE)
				return FALSE;
			return TRUE;
			break;

		default:
			return FALSE;
		}
	}

	// assume the others like clipping
	return TRUE;
}
Exemple #6
0
static int sttComparePluginsByName( const pluginEntry* p1, const pluginEntry* p2 )
{	return lstrcmp( p1->pluginname, p2->pluginname );
}
Exemple #7
0
BOOL GenerateRules()
{
	char **tokens, rule[256];
	int num_tokens,j, i;
	KeyVal *opt_head, *opt_cptr, *opt_pptr;
	RuleNode *new_rule, **node_ptr, *node;
	RulesHead *rules_head;
	BOOL  bError;

	var_list = NULL;

	for (j = 0; j < 256; j++)
	{
		if (rule_text[j].rule[0] == '\0')  break;
		if (rule_text[j].bEnabled == FALSE)  continue;

		bError = FALSE;

		lstrcpy(rule, rule_text[j].rule);

		tokens = gettokens(rule, &num_tokens);

		// Add variables to the Variable linked list
		if (!lstrcmp(tokens[0], "var"))
		{
			tokens[2][lstrlen(tokens[2])-1] = '\0';  // get rid of the semicolon
			AddToVarList(tokens[1], tokens[2]);
			continue;
		}

		/* replace any variable with its actual value */
		for (i = 0; i < num_tokens; i++)
		{
			debug(tokens[i]); debug(" ");
			if (tokens[i][0] == '$')	
				tokens[i] = getValue(tokens[i]);
			
			if (tokens[i] == NULL)  // this variable has not been defined 					
			{
				bError = TRUE;
				break;
			}
		}
		
		// if there was an error, don't add this rule to chain
		if (bError)
		{
			debug(" << ERROR >> \r\n");
			continue;
		}		
		debug("\r\n");

		if (!lstrcmp(tokens[0], "alert"))		  rules_head = &root.alert;
		else if (!lstrcmp(tokens[0], "log"))	  rules_head = &root.log;
		else if (!lstrcmp(tokens[0], "counter"))  rules_head = &root.counter;
		else continue;

		if (!lstrcmp(tokens[1], "icmp"))		  node_ptr = &rules_head->IcmpList;
		else if (!lstrcmp(tokens[1], "udp"))	  node_ptr = &rules_head->UdpList;
		else if (!lstrcmp(tokens[1], "tcp"))	  node_ptr = &rules_head->TcpList;
		else if (!lstrcmp(tokens[1], "arp"))	  node_ptr = &rules_head->ArpList;
		else continue;


		new_rule = (RuleNode *) malloc(sizeof(RuleNode));
		memset(new_rule, 0, sizeof(RuleNode));

		new_rule->sip_op = getIPop(tokens[2]);
		new_rule->sip = getIP(tokens[2]);
		new_rule->smask = getMask(tokens[2]);
		new_rule->dip_op = getIPop(tokens[5]);
		new_rule->dip = getIP(tokens[5]);
		new_rule->dmask = getMask(tokens[5]);
		new_rule->lsp = getPortMin(tokens[3]);
		new_rule->hsp = getPortMax(tokens[3]);
		new_rule->ldp = getPortMin(tokens[6]);
		new_rule->hdp = getPortMax(tokens[6]);
		
		if (tokens[4][0] == '<')		// is '<>'
			new_rule->dir = BI_DIR;
		else							// is '->'
			new_rule->dir = UNI_DIR;


		opt_head = getOptionList(tokens[7]);
		PopulateOptions( new_rule, opt_head);

		DumpRule(new_rule);


		/*  Add the rule to the appropriate linked list (icmp, tcp or udp) */
		if (*node_ptr == NULL)  
			*node_ptr = new_rule;
		else
		{
			node = *node_ptr;
			while (node->next != NULL)  
				node = node->next;
			node->next = new_rule;
		}


		/* delete the keyword/value list (no longer needed) */
		opt_cptr = opt_head;
		while (opt_cptr != NULL)
		{
			opt_pptr = opt_cptr;
			opt_cptr= opt_cptr->next;
			free(opt_pptr);
		}

		free(tokens);

		debug("done generating this rule\r\n");
	}

	/* free up memory allocated for variables */
	while (var_list != NULL)
	{
		free(var_list->keyword);
		free(var_list->value);
		opt_pptr = var_list;
		var_list = var_list->next;
		free(opt_pptr);
	}

	return TRUE;
}
Exemple #8
0
/**
 * Returns true if successful.
 */
BOOL ReadConfig(DXCONFIG* config, char* cfgFile)
{
	if (config == NULL) return false;

	FILE* cfg = fopen(cfgFile, "rt");
	if (cfg == NULL) return false;

	char str[BUFLEN];
	char name[BUFLEN];
	int value = 0;

	char *pName = NULL, *pValue = NULL, *comment = NULL;
	while (true)
	{
		ZeroMemory(str, BUFLEN);
		fgets(str, BUFLEN-1, cfg);
		if (feof(cfg)) break;

		// skip comments
		comment = strstr(str, "#");
		if (comment != NULL) comment[0] = '\0';

		// parse the line
		pName = pValue = NULL;
		ZeroMemory(name, BUFLEN); value = 0;
		char* eq = strstr(str, "=");
		if (eq == NULL || eq[1] == '\0') continue;

		eq[0] = '\0';
		pName = str; pValue = eq + 1;

		ZeroMemory(name, NULL); 
		sscanf(pName, "%s", name);

		if (lstrcmp(name, "dx.fullscreen.width")==0)
		{
			if (sscanf(pValue, "%d", &value)!=1) continue;
			LogWithNumber(&k_dxtools,"ReadConfig: dx.fullscreen.width = (%d)", value);
            config->fullscreen.width = value;
		}
        else if (lstrcmp(name, "dx.fullscreen.height")==0)
		{
			if (sscanf(pValue, "%d", &value)!=1) continue;
			LogWithNumber(&k_dxtools,"ReadConfig: dx.fullscreen.height = (%d)", value);
            config->fullscreen.height = value;
		}
        else if (lstrcmp(name, "dx.window.width")==0)
		{
			if (sscanf(pValue, "%d", &value)!=1) continue;
			LogWithNumber(&k_dxtools,"ReadConfig: dx.window.width = (%d)", value);
            config->window.width = value;
		}
        else if (lstrcmp(name, "dx.window.height")==0)
		{
			if (sscanf(pValue, "%d", &value)!=1) continue;
			LogWithNumber(&k_dxtools,"ReadConfig: dx.window.height = (%d)", value);
            config->window.height = value;
		}
	}
	fclose(cfg);
	return true;
}
Exemple #9
0
void GetPrinterListBox(
/***********************************************************************/
  /* This function retrieves the current selection from the dialog box.  If
     no string is selected in the list box, an empty string is the result.
     Otherwise, the device string buffer is returned as a result.  The
     device string buffer will contain a copy of the selected string. */
HWND 	hDlg,
LPSTR 	lpDevice)
{
STRING szEntry, szDriver;
int idItem;
LPSTR lpName, lpPort, lpNext;
short SepLength;
char End;
BOOL bMatch;

idItem = SendDlgItemMessage( hDlg, IDC_PRINTSELECT, LB_GETCURSEL, 0, 0L );
if ( idItem < 0 )
	{
	*lpDevice = '\0';
	return;
	}

SendDlgItemMessage( hDlg, IDC_PRINTSELECT, LB_GETTEXT, idItem,
	(long)(LPSTR)szEntry );
if ( !lstrcmp( szEntry, NullPort ) )
	{
	*lpDevice = '\0';
	return;
	}

lpName = szEntry;
lpPort = lpName;
SepLength = lstrlen( Separator );
while ( *lpPort )
	{
	End = lpPort[SepLength];
	lpPort[SepLength] = '\0';
	bMatch = !lstrcmp( lpPort, Separator );
	lpPort[SepLength] = End;
	if ( bMatch )
		break;
	lpPort++;
	}

if ( !*lpPort )
	{
	*lpDevice = '\0';
	return;
	}
*lpPort = '\0';
lpPort += SepLength;

GetProfileString( PRINTERS, lpName, "\0", szDriver, MAX_STR_LEN );
// Format of the device is DRIVER,PORT,15,45,PORT,15,45,PORT,15,45 etc.
if ( !(lpNext = GetNextParm( szDriver )) )
	{
	*lpDevice = '\0';
	return;
	}
*lpNext = '\0';

lstrcpy( lpDevice, lpName );
lstrcat( lpDevice, "," );
lstrcat( lpDevice, szDriver );
lstrcat( lpDevice, "," );
lstrcat( lpDevice, lpPort );
}
Exemple #10
0
bool IsNeedCmd(BOOL bRootCmd, LPCWSTR asCmdLine, CmdArg &szExe,
			   LPCWSTR* rsArguments /*= NULL*/, BOOL* rpbNeedCutStartEndQuot /*= NULL*/,
			   BOOL* rpbRootIsCmdExe /*= NULL*/, BOOL* rpbAlwaysConfirmExit /*= NULL*/, BOOL* rpbAutoDisableConfirmExit /*= NULL*/)
{
	_ASSERTE(asCmdLine && *asCmdLine);

	bool rbNeedCutStartEndQuot = false;
	bool rbRootIsCmdExe = true;
	bool rbAlwaysConfirmExit = false;
	bool rbAutoDisableConfirmExit = false;
	if (rsArguments) *rsArguments = NULL;

	bool lbRc = false;
	int iRc = 0;
	BOOL lbFirstWasGot = FALSE;
	LPCWSTR pwszCopy;
	int nLastChar;

	#ifdef _DEBUG
	// Это минимальные проверки, собственно к коду - не относятся
	CmdArg szDbgFirst;
	bool bIsBatch = false;
	{
		LPCWSTR psz = asCmdLine;
		NextArg(&psz, szDbgFirst);
		psz = PointToExt(szDbgFirst);
		if (lstrcmpi(psz, L".cmd")==0 || lstrcmpi(psz, L".bat")==0)
			bIsBatch = true;
	}
	#endif

	if (!szExe.GetBuffer(MAX_PATH))
	{
		_ASSERTE(FALSE && "Failed to allocate MAX_PATH");
		lbRc = true;
		goto wrap;
	}
	szExe.Empty();

	if (!asCmdLine || *asCmdLine == 0)
	{
		_ASSERTE(asCmdLine && *asCmdLine);
		lbRc = true;
		goto wrap;
	}


	pwszCopy = asCmdLine;
	// cmd /c ""c:\program files\arc\7z.exe" -?"   // да еще и внутри могут быть двойными...
	// cmd /c "dir c:\"
	nLastChar = lstrlenW(pwszCopy) - 1;

	if (pwszCopy[0] == L'"' && pwszCopy[nLastChar] == L'"')
	{
		//if (pwszCopy[1] == L'"' && pwszCopy[2])
		//{
		//	pwszCopy ++; // Отбросить первую кавычку в командах типа: ""c:\program files\arc\7z.exe" -?"

		//	if (rbNeedCutStartEndQuot) *rbNeedCutStartEndQuot = TRUE;
		//}
		//else
			// глючила на ""F:\VCProject\FarPlugin\#FAR180\far.exe  -new_console""
			//if (wcschr(pwszCopy+1, L'"') == (pwszCopy+nLastChar)) {
			//	LPCWSTR pwszTemp = pwszCopy;
			//	// Получим первую команду (исполняемый файл?)
			//	if ((iRc = NextArg(&pwszTemp, szArg)) != 0) {
			//		//Parsing command line failed
			//		lbRc = true; goto wrap;
			//	}
			//	pwszCopy ++; // Отбросить первую кавычку в командах типа: "c:\arc\7z.exe -?"
			//	lbFirstWasGot = TRUE;
			//	if (rbNeedCutStartEndQuot) *rbNeedCutStartEndQuot = TRUE;
			//} else
		{
			// Will be dequoted in 'NextArg' function. Examples
			// "C:\GCC\msys\bin\make.EXE -f "makefile" COMMON="../../../plugins/common""
			// ""F:\VCProject\FarPlugin\#FAR180\far.exe  -new_console""
			// ""cmd""
			// cmd /c ""c:\program files\arc\7z.exe" -?"   // да еще и внутри могут быть двойными...
			// cmd /c "dir c:\"

			LPCWSTR pwszTemp = pwszCopy;

			// Получим первую команду (исполняемый файл?)
			if ((iRc = NextArg(&pwszTemp, szExe)) != 0)
			{
				//Parsing command line failed
				#ifdef WARN_NEED_CMD
				_ASSERTE(FALSE);
				#endif
				lbRc = true; goto wrap;
			}

			if (lstrcmpiW(szExe, L"start") == 0)
			{
				// Команду start обрабатывает только процессор
				#ifdef WARN_NEED_CMD
				_ASSERTE(FALSE);
				#endif
				lbRc = true; goto wrap;
			}

			LPCWSTR pwszQ = pwszCopy + 1 + lstrlen(szExe);
			wchar_t* pszExpand = NULL;

			if (*pwszQ != L'"' && IsExecutable(szExe, &pszExpand))
			{
				pwszCopy ++; // отбрасываем
				lbFirstWasGot = TRUE;

				if (pszExpand)
				{
					szExe.Set(pszExpand);
					SafeFree(pszExpand);
					if (rsArguments)
						*rsArguments = pwszQ;
				}

				rbNeedCutStartEndQuot = true;
			}
		}
	}

	// Получим первую команду (исполняемый файл?)
	if (!lbFirstWasGot)
	{
		szExe.Empty();
		// 17.10.2010 - поддержка переданного исполняемого файла без параметров, но с пробелами в пути
		LPCWSTR pchEnd = pwszCopy + lstrlenW(pwszCopy);

		while (pchEnd > pwszCopy && *(pchEnd-1) == L' ') pchEnd--;

		if ((pchEnd - pwszCopy) < MAX_PATH)
		{

			szExe.Set(pwszCopy, (pchEnd - pwszCopy));
			_ASSERTE(szExe[(pchEnd - pwszCopy)] == 0);

			if (lstrcmpiW(szExe, L"start") == 0)
			{
				// Команду start обрабатывает только процессор
				#ifdef WARN_NEED_CMD
				_ASSERTE(FALSE);
				#endif
				lbRc = true; goto wrap;
			}

			// Обработка переменных окружения и поиск в PATH
			if (FileExistsSearch((LPCWSTR)szExe, szExe))
			{
				if (rsArguments)
					*rsArguments = pchEnd;
			}
			else
			{
				szExe.Empty();
			}
		}

		if (szExe[0] == 0)
		{
			if ((iRc = NextArg(&pwszCopy, szExe)) != 0)
			{
				//Parsing command line failed
				#ifdef WARN_NEED_CMD
				_ASSERTE(FALSE);
				#endif
				lbRc = true; goto wrap;
			}

			if (lstrcmpiW(szExe, L"start") == 0)
			{
				// Команду start обрабатывает только процессор
				#ifdef WARN_NEED_CMD
				_ASSERTE(FALSE);
				#endif
				lbRc = true; goto wrap;
			}

			// Обработка переменных окружения и поиск в PATH
			if (FileExistsSearch((LPCWSTR)szExe, szExe))
			{
				if (rsArguments)
					*rsArguments = pwszCopy;
			}
		}
	}

	if (!*szExe)
	{
		_ASSERTE(szExe[0] != 0);
	}
	else
	{
		// Если юзеру нужен редирект - то он должен явно указать ком.процессор
		// Иначе нереально (или достаточно сложно) определить, является ли символ
		// редиректом, или это просто один из аргументов команды...

		// "Левые" символы в имени файла (а вот в "первом аргументе" все однозначно)
		if (wcspbrk(szExe, L"?*<>|"))
		{
			rbRootIsCmdExe = TRUE; // запуск через "процессор"
			lbRc = true; goto wrap; // добавить "cmd.exe"
		}

		// если "путь" не указан
		if (wcschr(szExe, L'\\') == NULL)
		{
			bool bHasExt = (wcschr(szExe, L'.') != NULL);
			// Проверим, может это команда процессора (типа "DIR")?
			if (!bHasExt)
			{
				bool bIsCommand = false;
				wchar_t* pszUppr = lstrdup(szExe);
				if (pszUppr)
				{
					// избежать линковки на user32.dll
					//CharUpperBuff(pszUppr, lstrlen(pszUppr));
					for (wchar_t* p = pszUppr; *p; p++)
					{
						if (*p >= L'a' && *p <= 'z')
							*p -= 0x20;
					}

					const wchar_t* pszFind = gsInternalCommands;
					while (*pszFind)
					{
						if (lstrcmp(pszUppr, pszFind) == 0)
						{
							bIsCommand = true;
							break;
						}
						pszFind += lstrlen(pszFind)+1;
					}
					free(pszUppr);
				}
				if (bIsCommand)
				{
					#ifdef WARN_NEED_CMD
					_ASSERTE(FALSE);
					#endif
					rbRootIsCmdExe = TRUE; // запуск через "процессор"
					lbRc = true; goto wrap; // добавить "cmd.exe"
				}
			}

			// Пробуем найти "по путям" соответствующий exe-шник.
			INT_PTR nCchMax = szExe.mn_MaxLen; // выделить память, длинее чем szExe вернуть не сможем
			wchar_t* pszSearch = (wchar_t*)malloc(nCchMax*sizeof(wchar_t));
			if (pszSearch)
			{
				#ifndef CONEMU_MINIMAL
				MWow64Disable wow; wow.Disable(); // Отключить редиректор!
				#endif
				wchar_t *pszName = NULL;
				INT_PTR nRc = SearchPath(NULL, szExe, bHasExt ? NULL : L".exe", (DWORD)nCchMax, pszSearch, &pszName);
				if (nRc && (nRc < nCchMax))
				{
					// Нашли, возвращаем что нашли
					szExe.Set(pszSearch);
				}
				free(pszSearch);
			}
		} // end: if (wcschr(szExe, L'\\') == NULL)
	}

	// Если szExe не содержит путь к файлу - запускаем через cmd
	// "start "" C:\Utils\Files\Hiew32\hiew32.exe C:\00\Far.exe"
	if (!IsFilePath(szExe))
	{
		#ifdef WARN_NEED_CMD
		_ASSERTE(FALSE);
		#endif
		rbRootIsCmdExe = TRUE; // запуск через "процессор"
		lbRc = true; goto wrap; // добавить "cmd.exe"
	}

	//pwszCopy = wcsrchr(szArg, L'\\'); if (!pwszCopy) pwszCopy = szArg; else pwszCopy ++;
	pwszCopy = PointToName(szExe);
	//2009-08-27
	wchar_t *pwszEndSpace = szExe.ms_Arg + lstrlenW(szExe) - 1;

	while ((*pwszEndSpace == L' ') && (pwszEndSpace > szExe))
	{
		*(pwszEndSpace--) = 0;
	}

#ifndef __GNUC__
#pragma warning( push )
#pragma warning(disable : 6400)
#endif

	if (lstrcmpiW(pwszCopy, L"cmd")==0 || lstrcmpiW(pwszCopy, L"cmd.exe")==0
		|| lstrcmpiW(pwszCopy, L"tcc")==0 || lstrcmpiW(pwszCopy, L"tcc.exe")==0)
	{
		rbRootIsCmdExe = TRUE; // уже должен быть выставлен, но проверим
		rbAlwaysConfirmExit = TRUE; rbAutoDisableConfirmExit = FALSE;
		_ASSERTE(!bIsBatch);
		lbRc = false; goto wrap; // уже указан командный процессор, cmd.exe в начало добавлять не нужно
	}


	// Issue 1211: Decide not to do weird heuristic.
	//   If user REALLY needs redirection (root command, huh?)
	//   - he must call "cmd /c ..." directly
	// Если есть одна из команд перенаправления, или слияния - нужен CMD.EXE
	if (!bRootCmd)
	{
		if (wcschr(asCmdLine, L'&') ||
			wcschr(asCmdLine, L'>') ||
			wcschr(asCmdLine, L'<') ||
			wcschr(asCmdLine, L'|') ||
			wcschr(asCmdLine, L'^') // или экранирования
			)
		{
			#ifdef WARN_NEED_CMD
			_ASSERTE(FALSE);
			#endif
			lbRc = true; goto wrap;
		}
	}

	//if (lstrcmpiW(pwszCopy, L"far")==0 || lstrcmpiW(pwszCopy, L"far.exe")==0)
	if (IsFarExe(pwszCopy))
	{
		bool bFound = (wcschr(pwszCopy, L'.') != NULL);
		// Если указали при запуске просто "far" - это может быть батник, расположенный в %PATH%
		if (!bFound)
		{
			wchar_t szSearch[MAX_PATH+1], *pszPart = NULL;
			DWORD n = SearchPath(NULL, pwszCopy, L".exe", countof(szSearch), szSearch, &pszPart);
			if (n && (n < countof(szSearch)))
			{
				if (lstrcmpi(PointToExt(pszPart), L".exe") == 0)
					bFound = true;
			}
		}

		if (bFound)
		{
			rbAutoDisableConfirmExit = TRUE;
			rbRootIsCmdExe = FALSE; // FAR!
			_ASSERTE(!bIsBatch);
			lbRc = false; goto wrap; // уже указан исполняемый файл, cmd.exe в начало добавлять не нужно
		}
	}

	if (IsExecutable(szExe))
	{
		rbRootIsCmdExe = FALSE; // Для других программ - буфер не включаем
		_ASSERTE(!bIsBatch);
		lbRc = false; goto wrap; // Запускается конкретная консольная программа. cmd.exe не требуется
	}

	//Можно еще Доделать поиски с: SearchPath, GetFullPathName, добавив расширения .exe & .com
	//хотя фар сам формирует полные пути к командам, так что можно не заморачиваться
	#ifdef WARN_NEED_CMD
	_ASSERTE(FALSE);
	#endif
	rbRootIsCmdExe = TRUE;
#ifndef __GNUC__
#pragma warning( pop )
#endif

	lbRc = true;
wrap:
	if (rpbNeedCutStartEndQuot)
		*rpbNeedCutStartEndQuot = rbNeedCutStartEndQuot;
	if (rpbRootIsCmdExe)
		*rpbRootIsCmdExe = rbRootIsCmdExe;
	if (rpbAlwaysConfirmExit)
		*rpbAlwaysConfirmExit = rbAlwaysConfirmExit;
	if (rpbAutoDisableConfirmExit)
		*rpbAutoDisableConfirmExit = rbAutoDisableConfirmExit;
	return lbRc;
}
Exemple #11
0
INT_PTR CDlgItemHelper::GetString(HWND hParent, WORD nCtrlId, wchar_t** ppszStr, LPCWSTR asNoDefault /*= NULL*/, bool abListBox /*= false*/)
{
	INT_PTR nSel = abListBox ? SendDlgItemMessage(hParent, nCtrlId, CB_GETCURSEL, 0, 0) : -1;

	INT_PTR nLen = abListBox
		? ((nSel >= 0) ? SendDlgItemMessage(hParent, nCtrlId, CB_GETLBTEXTLEN, nSel, 0) : 0)
		: SendDlgItemMessage(hParent, nCtrlId, WM_GETTEXTLENGTH, 0, 0);

	if (!ppszStr)
		return nLen;

	if (nLen<=0)
	{
		SafeFree(*ppszStr);
		return nLen;
	}

	wchar_t* pszNew = (TCHAR*)calloc(nLen+1, sizeof(TCHAR));
	if (!pszNew)
	{
		_ASSERTE(pszNew!=NULL);
	}
	else
	{
		if (abListBox)
		{
			if (nSel >= 0)
				SendDlgItemMessage(hParent, nCtrlId, CB_GETLBTEXT, nSel, (LPARAM)pszNew);
		}
		else
		{
			GetDlgItemText(hParent, nCtrlId, pszNew, nLen+1);
		}


		if (*ppszStr)
		{
			if (lstrcmp(*ppszStr, pszNew) == 0)
			{
				free(pszNew);
				return nLen; // Изменений не было
			}
		}

		// Значение "по умолчанию" не запоминаем
		if (asNoDefault && lstrcmp(pszNew, asNoDefault) == 0)
		{
			SafeFree(*ppszStr);
			SafeFree(pszNew);
			nLen = 0;
			// Reset (it is default value!)
			return nLen;
		}

		if (nLen > (*ppszStr ? (INT_PTR)_tcslen(*ppszStr) : 0))
		{
			if (*ppszStr) free(*ppszStr);
			*ppszStr = pszNew; pszNew = NULL;
		}
		else if (*ppszStr)
		{
			_wcscpy_c(*ppszStr, nLen+1, pszNew);
		}
		SafeFree(pszNew);
	}

	return nLen;
}
Exemple #12
0
/// Mount
///
/// @param pclArc Archive
///
BOOL CPaz::Mount(CArcFile* pclArc)
{
    if (pclArc->GetArcExten() != _T(".paz"))
        return FALSE;

    // Initialize Mount Key
    InitMountKey(pclArc);

    // Initialize Table
    InitTable();

    // Decode Table
    DecodeTable1();
    DecodeTable2();

    // Get index size
    DWORD dwIndexSize;
    pclArc->Read(&dwIndexSize, 4);
    Decrypt(&dwIndexSize, 4);

    // Get index
    DWORD dwIndexPtr = 0;
    YCMemory<BYTE> clmbtIndex(dwIndexSize);
    pclArc->Read(&clmbtIndex[0], dwIndexSize);

    // Decode Index
    Decrypt(&clmbtIndex[0], dwIndexSize);
    DecodeData(&clmbtIndex[0], dwIndexSize);

    // Get file count
    DWORD dwFiles = *(DWORD*)&clmbtIndex[0];
    dwIndexPtr += 4;

    // Initialization table for decoding movies
    if (pclArc->GetArcName() == _T("mov.paz"))
    {
        dwIndexPtr += InitMovieTable(&clmbtIndex[dwIndexPtr]);
    }

    // Get file info
    for (DWORD i = 0; i < dwFiles; i++)
    {
        // Get file name
        TCHAR szFileName[_MAX_FNAME];
        lstrcpy(szFileName, (LPCTSTR)&clmbtIndex[dwIndexPtr]);
        dwIndexPtr += lstrlen(szFileName) + 1;

        // Add .ogg extension if voice.paz (Don't know why they don't have extensions)

        if (pclArc->GetArcName().Left(5) == _T("voice"))
        {
            if (lstrcmp(PathFindExtension(szFileName), _T("")) == 0)
            {
                lstrcat(szFileName, _T(".ogg"));
            }
        }

        DWORD dwType = *(DWORD*)&clmbtIndex[dwIndexPtr + 20];

        // Add to list view
        SFileInfo stFileInfo;
        stFileInfo.name = szFileName;
        stFileInfo.sizeOrg = (dwType == 1) ? *(DWORD*)&clmbtIndex[dwIndexPtr + 8] : *(DWORD*)&clmbtIndex[dwIndexPtr + 12];
        stFileInfo.dwSizeOrg2 = *(DWORD*)&clmbtIndex[dwIndexPtr + 16];
        stFileInfo.sizeCmp = (dwType == 1) ? *(DWORD*)&clmbtIndex[dwIndexPtr + 16] : stFileInfo.sizeOrg;
        stFileInfo.start = *(DWORD*)&clmbtIndex[dwIndexPtr + 0];
        stFileInfo.end = stFileInfo.start + stFileInfo.sizeCmp;

        if (dwType == 1)
        {
            stFileInfo.format = _T("zlib");
        }

        pclArc->AddFileInfo(stFileInfo);

        dwIndexPtr += 24;
    }

    return TRUE;
}
Exemple #13
0
//确定函数
void CServiceSet::OnOK()
{
	//变量定义
	DWORD dwSQLIP=0;
	TCHAR szBuffer[2000];

	//挂接类型
	if (m_GameKind.GetCurSel()==CB_ERR)
	{
		AfxMessageBox(TEXT("请选择挂接类型"),MB_ICONQUESTION);
		m_GameKind.SetFocus();
		return;
	}
	m_GameKind.GetLBText(m_GameKind.GetCurSel(),szBuffer);
	if (lstrcmp(TEXT("金币类"),szBuffer)==0) m_GameRoomInit.uKindID=1;
	else if (lstrcmp(TEXT("扑克类"),szBuffer)==0) m_GameRoomInit.uKindID=2;
	else if (lstrcmp(TEXT("棋类"),szBuffer)==0) m_GameRoomInit.uKindID=3;
	else if (lstrcmp(TEXT("对战类"),szBuffer)==0) m_GameRoomInit.uKindID=4;
	else if (lstrcmp(TEXT("比赛类"),szBuffer)==0) m_GameRoomInit.uKindID=5;
	else
	{
		AfxMessageBox(TEXT("请选择正确的挂接类型"),MB_ICONQUESTION);
		m_GameKind.SetFocus();
		return;
	}

	//游戏类型
	if (m_ComType.GetCurSel()==CB_ERR)
	{
		AfxMessageBox(TEXT("请选择游戏类型"),MB_ICONQUESTION);
		m_ComType.SetFocus();
		return;
	}
	m_ComType.GetLBText(m_ComType.GetCurSel(),szBuffer);
	if (lstrcmp(TEXT("点值游戏"),szBuffer)==0) m_GameRoomInit.InitInfo.uComType=TY_NORMAL_GAME;
	else if (lstrcmp(TEXT("比赛游戏"),szBuffer)==0) m_GameRoomInit.InitInfo.uComType=TY_MATCH_GAME;
	else if (lstrcmp(TEXT("金币游戏"),szBuffer)==0) m_GameRoomInit.InitInfo.uComType=TY_MONEY_GAME;
	else
	{
		AfxMessageBox(TEXT("请选择正确的游戏类型"),MB_ICONQUESTION);
		m_ComType.SetFocus();
		return;
	}

	//监听端口
	m_GameRoomInit.InitInfo.uListenPort=GetDlgItemInt(IDC_SOCKET_PORT);
	if ((m_GameRoomInit.InitInfo.uListenPort<3000L)||((m_GameRoomInit.InitInfo.uListenPort>30000L)))
	{
		AfxMessageBox(TEXT("请正确填写监听端口,有效范围 3000 到 30000"),MB_ICONQUESTION);
		GetDlgItem(IDC_SOCKET_PORT)->SetFocus();
		return;
	}

	//房间 ID
	m_GameRoomInit.InitInfo.uRoomID=GetDlgItemInt(IDC_ROOM_ID);
	if ((m_GameRoomInit.InitInfo.uRoomID<1L)||((m_GameRoomInit.InitInfo.uRoomID>30000L)))
	{
		AfxMessageBox(TEXT("请正确填写房间 ID,有效范围 1 到 30000"),MB_ICONQUESTION);
		GetDlgItem(IDC_ROOM_ID)->SetFocus();
		return;
	}

	//桌子数目
	m_GameRoomInit.InitInfo.uDeskCount=GetDlgItemInt(IDC_DESK_COUNT);
	if ((m_GameRoomInit.InitInfo.uDeskCount<10L)||((m_GameRoomInit.InitInfo.uDeskCount>200L)))
	{
		AfxMessageBox(TEXT("请正确填写桌子数目,有效范围 10 到 200"),MB_ICONQUESTION);
		GetDlgItem(IDC_DESK_COUNT)->SetFocus();
		return;
	}

	//基础分数
	m_GameRoomInit.InitInfo.uBasePoint=GetDlgItemInt(IDC_BASE_POINT);
	if (m_GameRoomInit.InitInfo.uBasePoint>10000L)
	{
		AfxMessageBox(TEXT("请正确填写基础分数,有效范围 0 到 10000"),MB_ICONQUESTION);
		GetDlgItem(IDC_BASE_POINT)->SetFocus();
		return;
	}
	
	//最少分数
	m_GameRoomInit.InitInfo.uLessPoint=GetDlgItemInt(IDC_LESS_POINT);
	if (m_GameRoomInit.InitInfo.uLessPoint>30000L)
	{
		AfxMessageBox(TEXT("请正确填写最少分数,有效范围 0 到 30000"),MB_ICONQUESTION);
		GetDlgItem(IDC_LESS_POINT)->SetFocus();
		return;
	}

	//最少分数
	m_GameRoomInit.InitInfo.uLessPoint=GetDlgItemInt(IDC_LESS_POINT);
	if (m_GameRoomInit.InitInfo.uLessPoint>30000L)
	{
		AfxMessageBox(TEXT("请正确填写最少分数,有效范围 0 到 30000"),MB_ICONQUESTION);
		GetDlgItem(IDC_LESS_POINT)->SetFocus();
		return;
	}

	//最大人数
	m_GameRoomInit.InitInfo.uMaxPeople=GetDlgItemInt(IDC_MAX_CONNECT);
	if (m_GameRoomInit.InitInfo.uLessPoint>1000L)
	{
		AfxMessageBox(TEXT("请正确填写最大人数,有效范围 0 到 1000"),MB_ICONQUESTION);
		GetDlgItem(IDC_MAX_CONNECT)->SetFocus();
		return;
	}

	//游戏服务器 IP
	if (m_CenterSQLIP.GetAddress(dwSQLIP)!=4)
	{
		AfxMessageBox(TEXT("请正确填写游戏数据库 IP"),MB_ICONQUESTION);
		m_CenterSQLIP.SetFocus();
		return;
	}
	sprintf(m_GameRoomInit.InitInfo.szSQLIP,TEXT("%d.%d.%d.%d"),FIRST_IPADDRESS(dwSQLIP),SECOND_IPADDRESS(dwSQLIP),THIRD_IPADDRESS(dwSQLIP),FOURTH_IPADDRESS(dwSQLIP));

	//登陆服务器 IP
	if (m_LogonSQLIP.GetAddress(dwSQLIP)!=4)
	{
		AfxMessageBox(TEXT("请正确填写用户数据库 IP"),MB_ICONQUESTION);
		m_LogonSQLIP.SetFocus();
		return;
	}
	sprintf(m_GameRoomInit.InitInfo.szLogonSQLIP,TEXT("%d.%d.%d.%d"),FIRST_IPADDRESS(dwSQLIP),SECOND_IPADDRESS(dwSQLIP),THIRD_IPADDRESS(dwSQLIP),FOURTH_IPADDRESS(dwSQLIP));

	//本地服务器 IP
	if (m_NativeSQLIP.GetAddress(dwSQLIP)!=4)
	{
		AfxMessageBox(TEXT("请正确填写本地数据库 IP"),MB_ICONQUESTION);
		m_NativeSQLIP.SetFocus();
		return;
	}
	sprintf(m_GameRoomInit.InitInfo.szNativeSQLIP,TEXT("%d.%d.%d.%d"),FIRST_IPADDRESS(dwSQLIP),SECOND_IPADDRESS(dwSQLIP),THIRD_IPADDRESS(dwSQLIP),FOURTH_IPADDRESS(dwSQLIP));

	//房间名字
	GetDlgItemText(IDC_ROOM_NAME,m_GameRoomInit.InitInfo.szGameRoomName,sizeof(m_GameRoomInit.InitInfo.szGameRoomName));

	//备注信息
	GetDlgItemText(IDC_ROOM_NOTE,m_GameRoomInit.szRoomNote,sizeof(m_GameRoomInit.szRoomNote));

	//调整参数
	if (m_GameRoomInit.uKindID==1)
	{
		if ((m_ServiceInfo.ServiceInfo.uSupportType&SUP_MONEY_GAME)==0)
		{
			AfxMessageBox(TEXT("此游戏不支持金币游戏模式,请重新选择挂接类型"),MB_ICONQUESTION);
			m_GameKind.SetFocus();
			return;
		}
		m_GameRoomInit.InitInfo.uComType=TY_MONEY_GAME;
	}
	if (m_GameRoomInit.uKindID==5)
	{
		if ((m_ServiceInfo.ServiceInfo.uSupportType&SUP_MATCH_GAME)==0)
		{
			AfxMessageBox(TEXT("此游戏不支持比赛游戏模式,请重新选择挂接类型"),MB_ICONQUESTION);
			m_GameKind.SetFocus();
			return;
		}
		m_GameRoomInit.InitInfo.uComType=TY_MATCH_GAME;
	}
	if (m_GameRoomInit.InitInfo.szGameTable[0]==0) lstrcpy(m_GameRoomInit.InitInfo.szGameTable,m_ServiceInfo.ServiceInfo.szGameTable);
	if (m_GameRoomInit.InitInfo.uComType==TY_MONEY_GAME)
	{
		m_GameRoomInit.uKindID=1;
		lstrcpy(m_GameRoomInit.InitInfo.szGameTable,TEXT("MoneyGameEx"));
		if (m_GameRoomInit.InitInfo.uMoneyPoint==0) m_GameRoomInit.InitInfo.uMoneyPoint=1;
	}
	else if (m_GameRoomInit.InitInfo.uComType==TY_MATCH_GAME)
	{
		m_GameRoomInit.uKindID=5;
		m_GameRoomInit.InitInfo.uMoneyPoint=0;
	}
	UINT uLessMaxPeople=m_GameRoomInit.InitInfo.uDeskCount*m_ServiceInfo.ServiceInfo.uDeskPeople+50;
	if (m_GameRoomInit.InitInfo.uMaxPeople<uLessMaxPeople) m_GameRoomInit.InitInfo.uMaxPeople=uLessMaxPeople;

	//生成连接字符
	CString strConnect;
#ifdef _DEBUG
	strConnect.Format(TEXT("Provider=SQLOLEDB.1;Password=%s;Persist Security Info=True;User ID=%s;Initial Catalog=%s;Data Source=%s;"),
		m_pServiceManage->m_Info.m_szSQLPass,m_pServiceManage->m_Info.m_szSQLName,szLogonDataBaseName,m_pServiceManage->m_Info.m_szSQLAddr);
#else
	strConnect.Format(TEXT("Provider=SQLOLEDB.1;Password=%s;Persist Security Info=True;User ID=%s;Initial Catalog=%s;Data Source=%s,3000;"),
		m_pServiceManage->m_Info.m_szSQLPass,m_pServiceManage->m_Info.m_szSQLName,szLogonDataBaseName,m_pServiceManage->m_Info.m_szSQLAddr);
#endif
	if(stc_bUseAccessDB)
		strConnect=stc_sLogonDataConnect;


	//连接数据库
	CAFCDataBase DataBase;
	DataBase.ShowError(true);
	if (DataBase.Open(strConnect)==false) return;

	//获取数据库密码
	if (m_pServiceManage->GetSQLDataInfo(m_GameRoomInit.InitInfo.szSQLIP,m_GameRoomInit.InitInfo.szSQLName,m_GameRoomInit.InitInfo.szSQLPass,DataBase)==false)
	{
		AfxMessageBox(TEXT("获取游戏数据库信息错误,请重新设置游戏数据库 IP 信息"));
		m_CenterSQLIP.SetFocus();
		return;
	}

	//获取数据库密码
	if (m_pServiceManage->GetSQLDataInfo(m_GameRoomInit.InitInfo.szLogonSQLIP,m_GameRoomInit.InitInfo.szLogonSQLName,m_GameRoomInit.InitInfo.szLogonSQLPass,DataBase)==false)
	{
		AfxMessageBox(TEXT("获取用户数据库信息错误,请重新设置游戏数据库 IP 信息"));
		m_LogonSQLIP.SetFocus();
		return;
	}

	//获取数据库密码
	if (m_pServiceManage->GetSQLDataInfo(m_GameRoomInit.InitInfo.szNativeSQLIP,m_GameRoomInit.InitInfo.szNativeSQLName,m_GameRoomInit.InitInfo.szNativeSQLPass,DataBase)==false)
	{
		AfxMessageBox(TEXT("获取本地数据库信息错误,请重新设置游戏数据库 IP 信息"));
		m_NativeSQLIP.SetFocus();
		return;
	}

	//执行语句资料
	sprintf(szBuffer,TEXT("INSERT INTO ComRoomInfo (RoomID,RoomName,ServiceIP,CenterSQLIP,LogonSQLIP,NativaSQLIP,ServerInfoID,")
		TEXT("ComType,SocketPort,KindID,NameID,MatchInfoID,DeskCount,MaxPeople,BasePoint,LessPoint,MoneyPoint,RoomRule,UserPower,")
		TEXT("LockTable,IPRuleTable,MatchTable,Note) ")
		TEXT("VALUES (%ld,'%s','%s','%s','%s','%s',%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,'%s','%s','%s','%s')"),
		m_GameRoomInit.InitInfo.uRoomID,m_GameRoomInit.InitInfo.szGameRoomName,m_pServiceManage->m_Info.m_szServiceIP,m_GameRoomInit.InitInfo.szSQLIP,
		m_GameRoomInit.InitInfo.szLogonSQLIP,m_GameRoomInit.InitInfo.szNativeSQLIP,m_ServiceInfo.uServiceID,m_GameRoomInit.InitInfo.uComType,
		m_GameRoomInit.InitInfo.uListenPort,m_GameRoomInit.uKindID,m_ServiceInfo.ServiceInfo.uNameID,m_GameRoomInit.InitInfo.dwMatchInfoID,
		m_GameRoomInit.InitInfo.uDeskCount,m_GameRoomInit.InitInfo.uMaxPeople,m_GameRoomInit.InitInfo.uBasePoint,m_GameRoomInit.InitInfo.uLessPoint,
		m_GameRoomInit.InitInfo.uMoneyPoint,m_GameRoomInit.InitInfo.dwRoomRule,m_GameRoomInit.InitInfo.dwUserPower,m_GameRoomInit.InitInfo.szLockTable,
		m_GameRoomInit.InitInfo.szIPRuleTable,m_GameRoomInit.InitInfo.szGameTable,m_GameRoomInit.szRoomNote);
	if (DataBase.Execute(szBuffer)==false) return;

	__super::OnOK();
}
static DWORD CALLBACK GetCurrentConfigState(LPPROGRESSDISPLAY ppd, LPARAM lp)
{
    afs_status_t nStatus = 0;

    ASSERT(pProg);

    g_LogFile.Write("Checking this machine's current configuration...\r\n");

    if (!IsClientConfigured(g_CfgData.bValidClientInfo, nStatus))
	return nStatus;

    if (!IsConfigInfoValid(g_CfgData.bValidServerInfo, nStatus))
	return nStatus;

    // If the server and client have good config info, and the client is in a 
    // different cell than the server, then the config routines will want to
    // reconfigure the client.  To do so they need information that we already
    // know and don't have to ask the user for.  Prefill this information here.
    if (g_CfgData.bValidClientInfo && g_CfgData.bValidServerInfo && 
        (lstrcmp(g_CfgData.szCellName, g_CfgData.szClientCellName) != 0))
    {
        lstrcpy(g_CfgData.szCellServDbHostname, g_CfgData.szHostname);
    }

    if (!GetLibHandles(&nStatus))
	return nStatus;

    if (!CheckConfigState(DoesAPartitionExist, g_CfgData.configPartition, nStatus, IDS_CHECK_PARTITION))
	return nStatus;

    if (g_CfgData.bValidServerInfo) {
	// Must check if bos server is running, and start it if it isn't.  We can't determine
	// if the services are running except by asking the bosserver.
	if (!StartBosServer(nStatus))
	    return nStatus;

	if (!CheckConfigState(IsFSConfigured, g_CfgData.configFS, nStatus, IDS_CHECK_FS_CONFIG))
	    return nStatus;

	if (!CheckConfigState(IsDBConfigured, g_CfgData.configDB, nStatus, IDS_CHECK_DB_CONFIG))
	    return nStatus;

	if (g_CfgData.configDB == CS_ALREADY_CONFIGURED) {
	    if (!AreWeLastDBServer(g_CfgData.bLastDBServer, nStatus))
		return nStatus;
	}

	if (!CheckConfigState(IsBakConfigured, g_CfgData.configBak, nStatus, IDS_CHECK_BAK_CONFIG))
	    return nStatus;

	if (!CheckConfigState(DoRootVolumesExist, g_CfgData.configRootVolumes, nStatus, IDS_CHECK_ROOT_AFS))
            return nStatus;

        g_CfgData.bRootVolumesExistanceKnown = TRUE;

	if (!CheckConfigState(AreRootVolumesReplicated, g_CfgData.configRep, nStatus, IDS_CHECK_REP))
            return nStatus;
        
        g_CfgData.bRootVolumesReplicationKnown = TRUE;

	if (!CheckConfigState(IsSCSConfigured, g_CfgData.configSCS, nStatus, IDS_CHECK_SCS))
	    return nStatus;

	if (!CheckConfigState(IsSCCConfigured, g_CfgData.configSCC, nStatus, IDS_CHECK_SCC))
	    return nStatus;
    }		

    if (!bCancel)
	pProg->SetProgress(MAX_STEPS);
	
    return 0;
}
Exemple #15
0
LONG CuDlgReplicationServerPageStartupSetting::OnUpdateData (WPARAM wParam, LPARAM lParam)
{
	int iret,ires,irestype, nNodeHdl = -1;
	UCHAR DBAUsernameOntarget[MAXOBJECTNAME];
	UCHAR buf[EXTRADATASIZE];
	UCHAR extradata[EXTRADATASIZE];
	LPUCHAR parentstrings [MAXPLEVEL];
	CString cDefNumSvr,cDefDbName,cLocal;
	CString strMsg,strMsg1;

	LPIPMUPDATEPARAMS pUps = (LPIPMUPDATEPARAMS)lParam;
	m_pSvrDta = (LPREPLICSERVERDATAMIN)pUps->pStruct;
	EnableButtons();
	//
	// Specialize the OnUpdateData:
	if (!m_pSvrDta->m_bRefresh)
		return 0L;
	m_pSvrDta->m_bRefresh = FALSE;

	CdIpmDoc* pIpmDoc = NULL;
	CfIpmFrame* pIpmFrame = (CfIpmFrame*)GetParentFrame();
	ASSERT(pIpmFrame);
	if (pIpmFrame)
	{
		pIpmDoc = pIpmFrame->GetIpmDoc();
		ASSERT (pIpmDoc);
	}
	if (!pIpmDoc)
		return 0L;

	nNodeHdl  = LIBMON_OpenNodeStruct (m_pSvrDta->LocalDBNode);
	if (nNodeHdl == -1) {
		strMsg.LoadString(IDS_MAX_NB_CONNECT);  // _T("Maximum number of connections has been reached"
		strMsg1.LoadString (IDS_E_READ_FILE);   //    " - Cannot read file."
		strMsg += _T("\n") + strMsg1;
		MessageBox(strMsg ,NULL, MB_ICONHAND | MB_OK | MB_TASKMODAL);
		return 0L;
	}

	// Temporary for activate a session
	ires = DOMGetFirstObject (nNodeHdl, OT_DATABASE, 0, NULL, FALSE, NULL, buf, NULL, NULL);
	cDefDbName.Format(_T("%s::%s"), m_pSvrDta->LocalDBNode,m_pSvrDta->LocalDBName);
	//
	//Get DBA user name for this database
	parentstrings[0]=m_pSvrDta->LocalDBName;
	parentstrings[1]=NULL;
	memset (DBAUsernameOntarget,'\0',sizeof(DBAUsernameOntarget));
	iret = DOMGetObjectLimitedInfo( nNodeHdl,
	                                parentstrings [0],
	                                (UCHAR *)"",
	                                OT_DATABASE,
	                                0,
	                                parentstrings,
	                                TRUE,
	                                &irestype,
	                                buf,
	                                DBAUsernameOntarget,
	                                extradata
	                              );
	if (iret != RES_SUCCESS) {
		LIBMON_CloseNodeStruct(nNodeHdl);
		//wsprintf((char *)buf,"DBA owner on database : %s not found. Read file aborted.",parentstrings[0]);
		strMsg.Format(IDS_F_DB_OWNER,parentstrings[0]);
		MessageBox(strMsg, NULL, MB_ICONEXCLAMATION | MB_OK | MB_TASKMODAL);
		return 0L;
	}
	LIBMON_CloseNodeStruct(nNodeHdl);
	m_csDBAOwner=DBAUsernameOntarget;
	cDefNumSvr.Format(_T("%d"),m_pSvrDta->serverno);
	
	if (m_csDBAOwner.IsEmpty() ||cDefNumSvr.IsEmpty()||cDefDbName.IsEmpty())   {
		return 0L;
	}

	Cleanup();
	m_cListCtrl.DeleteAllItems();

	CString csVnodeAndUsers;
	// Read default flags on "LocalDBNode (user:XXX)"
	csVnodeAndUsers.Format(_T("%s%s%s%s"),  m_pSvrDta->LocalDBNode,
	                                    LPUSERPREFIXINNODENAME,
	                                    (LPCTSTR)m_csDBAOwner,
										LPUSERSUFFIXINNODENAME);
	nNodeHdl  = LIBMON_OpenNodeStruct ((LPUCHAR)(LPCTSTR)csVnodeAndUsers);
	if (nNodeHdl == -1) {
		strMsg.LoadString (IDS_MAX_NB_CONNECT);  // _T("Maximum number of connections has been reached"
		strMsg1.LoadString (IDS_E_READ_FILE);    //    " - Cannot read file."
		strMsg +=  _T("\n") + strMsg1;
		MessageBox(strMsg ,NULL, MB_ICONHAND | MB_OK | MB_TASKMODAL);
		return 0L;
	}
	memset (DBAUsernameOntarget,'\0',sizeof(DBAUsernameOntarget));
	iret = DOMGetObjectLimitedInfo( nNodeHdl,
	                                parentstrings [0],
	                                (UCHAR *)"",
	                                OT_DATABASE,
	                                0,
	                                parentstrings,
	                                TRUE,
	                                &irestype,
	                                buf,
	                                DBAUsernameOntarget,
	                                extradata
	                              );
	if (iret != RES_SUCCESS) {
		LIBMON_CloseNodeStruct(nNodeHdl);
		//wsprintf((char *)buf,"DBA owner on database : %s not found. Read file aborted.",parentstrings[0]);
		strMsg.Format(IDS_F_DB_OWNER,parentstrings[0]);
		MessageBox(strMsg, NULL, MB_ICONEXCLAMATION | MB_OK | MB_TASKMODAL);
		return 0L;
	}
	m_FlagsList.DefineAllFlagsWithDefaultValues(nNodeHdl , cDefNumSvr, cDefDbName, m_csDBAOwner);
	LIBMON_CloseNodeStruct(nNodeHdl);

	// Read Runrepl.opt from "LocalDBNode (user:XXX)" or From "RunNode"
	if (lstrcmp((char *)m_pSvrDta->LocalDBNode,(char *)m_pSvrDta->RunNode) == 0)
		csVnodeAndUsers.Format(_T("%s%s%s%s"), m_pSvrDta->LocalDBNode,
		                                   LPUSERPREFIXINNODENAME,
		                                   (LPCTSTR)m_csDBAOwner,
										   LPUSERSUFFIXINNODENAME);
	else
		csVnodeAndUsers = m_pSvrDta->RunNode;
	nNodeHdl  = LIBMON_OpenNodeStruct ((LPUCHAR)(LPCTSTR)csVnodeAndUsers);
	if (nNodeHdl == -1) {
		strMsg.LoadString(IDS_MAX_NB_CONNECT);  // _T("Maximum number of connections has been reached"
		strMsg1.LoadString (IDS_E_READ_FILE);   //    " - Cannot read file."
		strMsg += _T("\n") + strMsg1;
		MessageBox(strMsg ,NULL, MB_ICONHAND | MB_OK | MB_TASKMODAL);
		return 0L;
	}

	CWaitCursor hourglass;
	// Read file Runrepl.opt and fill m_FlagsList.
	iret = GetReplicServerParams   ( pIpmDoc, m_pSvrDta, &m_FlagsList );
	
	LIBMON_CloseNodeStruct (nNodeHdl);
	CaReplicationItem* pItem = NULL;
	while (!m_FlagsList.IsEmpty())
	{
		pItem = m_FlagsList.RemoveHead();
		if (pItem->IsDisplay())
			AddItem (pItem);
		else
			delete pItem;
	}

	EnableButtons();
	return 0L;
}
Exemple #16
0
short InitPrinterListBox(
/***********************************************************************/
  /* This function initializes the list of devices in the GetDevice dialog box.
     The list box in the dialog box contains a list of all devices installed in
     the system.  The user will select from among these various strings to
     select the current printer.  The number of printers listed in the list
     box is returned as a result.  The currently selected device (lpDevice)
     should have the form "NAME,DRIVER,PORT", and will be highlighted initially
     in the list box. */
HWND 	hDlg,
LPSTR 	lpDevice)
{
short nDevice;
char KeyBuffer[KEY_LENGTH];
STRING szDevice, Buffer, szString;
LPSTR lp, lpName, lpDriver, lpPort, lpNext;
LPSTR lpActiveName, lpActiveDriver, lpActivePort;
int CurrDevice; /* index of currently selected device */

if ( !(*lpDevice) )
	GetDefaultPrinter( lpDevice );
// Format of the device string is NAME,DRIVER,PORT etc.

lstrcpy( szDevice, lpDevice ); // Copy the device string so we won't destroy it

if ( AstralStr( IDS_PORT_SEPARATOR, &lp ) )
	lstrcpy( Separator, lp );

lpActiveName = szDevice; // get the name
if ( lpActiveDriver = GetNextParm( lpActiveName ) ) // get the driver
	{
	*lpActiveDriver++ = '\0';
	if ( lpActivePort = GetNextParm( lpActiveDriver ) ) // get the port
		*lpActivePort++ = '\0';
	}

nDevice = 0;
CurrDevice = -1;
GetProfileString( PRINTERS, NULL, "\0\0", KeyBuffer, KEY_LENGTH );
lpName = KeyBuffer;
while ( *lpName )
	{
	GetProfileString( PRINTERS, lpName, "\0", Buffer, MAX_STR_LEN );
	// Format of the buffer is DRIVER,PORT,15,45,PORT,15,45,PORT,15,45 etc.
	lpDriver = Buffer;
	lpPort = GetNextParm( lpDriver ); // skip over driver to get the port
	while ( lpPort )
		{
		*lpPort++ = '\0';
		if ( lpNext = GetNextParm( lpPort ) )
			*lpNext++ = '\0';
		lstrcpy( szString, lpName );
		lstrcat( szString, Separator );
		lstrcat( szString, lpPort );
		if ( hDlg )
			SendDlgItemMessage( hDlg, IDC_PRINTSELECT,
				LB_INSERTSTRING, -1, (long)(LPSTR)szString );
		if ( lpActiveName && !lstrcmp(lpActiveName,lpName) &&
		     lpActivePort && !lstrcmp(lpActivePort,lpPort) )
			CurrDevice = nDevice;
		nDevice++;
		if ( lpNext = GetNextParm( lpNext ) ) // skip the 15
			lpNext++;
		lpPort = GetNextParm( lpNext ); // skip the 45
		}
	lpName += (lstrlen(lpName) + 1);
	}

if ( !nDevice && hDlg )
	{
	GetProfileString( "windows", "NullPort", "None", NullPort, MAX_STR_LEN);
	SendDlgItemMessage( hDlg, IDC_PRINTSELECT, LB_INSERTSTRING, -1,
		(long)(LPSTR)NullPort );
	nDevice++;
	}

if ( CurrDevice < 0 ) // the name wasn't in the list, so pass back the default
	GetDefaultPrinter( lpDevice );

if ( hDlg )
	{
	if ( CurrDevice < 0 ) // the name wasn't in the list...
		SendDlgItemMessage( hDlg, IDC_PRINTSELECT, LB_SELECTSTRING,
			-1, (long)lpDevice );
	else	SendDlgItemMessage( hDlg, IDC_PRINTSELECT, LB_SETCURSEL,
			CurrDevice, 0L );
	}

return( nDevice );
}
void UpdateComspec(ConEmuComspec* pOpt, bool DontModifyPath /*= false*/)
{
	if (!pOpt)
	{
		_ASSERTE(pOpt!=NULL);
		return;
	}

	if (pOpt->isUpdateEnv && (pOpt->csType != cst_EnvVar))
	{
		//if (pOpt->csType == cst_AutoTccCmd) -- always, if isUpdateEnv
		{
			LPCWSTR pszNew = NULL;
			switch (pOpt->csBits)
			{
			case csb_SameOS:
				pszNew = IsWindows64() ? pOpt->Comspec64 : pOpt->Comspec32;
				break;
			case csb_SameApp:
				pszNew = WIN3264TEST(pOpt->Comspec32,pOpt->Comspec64);
				break;
			case csb_x32:
				pszNew = pOpt->Comspec32;
				break;
			default:
				_ASSERTE(pOpt->csBits==csb_SameOS || pOpt->csBits==csb_SameApp || pOpt->csBits==csb_x32);
				pszNew = NULL;
			}
			if (pszNew && *pszNew)
			{
				#ifdef SHOW_COMSPEC_CHANGE
				wchar_t szCurrent[MAX_PATH]; GetEnvironmentVariable(L"ComSpec", szCurrent, countof(szCurrent));
				if (lstrcmpi(szCurrent, pszNew))
				{
					wchar_t szMsg[MAX_PATH*4], szProc[MAX_PATH] = {}, szPid[MAX_PATH];
					GetModuleFileName(NULL, szProc, countof(szProc));
					_wsprintf(szPid, SKIPLEN(countof(szPid))
						L"PID=%u, '%s'", GetCurrentProcessId(), PointToName(szProc));
					_wsprintf(szMsg, SKIPLEN(countof(szMsg))
						L"Changing %%ComSpec%% in %s\nCur=%s\nNew=%s",
						szPid , szCurrent, pszNew);
					MessageBox(NULL, szMsg, szPid, MB_SYSTEMMODAL);
				}
				#endif

				_ASSERTE(wcschr(pszNew, L'%')==NULL);
				SetEnvVarExpanded(L"ComSpec", pszNew);
			}
		}
	}

	if (pOpt->AddConEmu2Path && !DontModifyPath)
	{
		if ((pOpt->ConEmuBaseDir[0] == 0) || (pOpt->ConEmuExeDir[0] == 0))
		{
			_ASSERTE(pOpt->ConEmuBaseDir[0] != 0);
			_ASSERTE(pOpt->ConEmuExeDir[0] != 0);
		}
		else
		{
			wchar_t* pszCur = GetEnvVar(L"PATH");

			if (!pszCur)
				pszCur = lstrdup(L"");

			DWORD n = lstrlen(pszCur);
			wchar_t* pszUpr = lstrdup(pszCur);
			wchar_t* pszDirUpr = (wchar_t*)malloc(MAX_PATH*sizeof(*pszCur));

			MCHKHEAP;

			if (!pszUpr || !pszDirUpr)
			{
				_ASSERTE(pszUpr && pszDirUpr);
			}
			else
			{
				bool bChanged = false;
				wchar_t* pszAdd = NULL;

				CharUpperBuff(pszUpr, n);

				for (int i = 0; i <= 1; i++)
				{
					// Put '%ConEmuExeDir' on first place
					switch (i)
					{
					case 1:
						if (!(pOpt->AddConEmu2Path & CEAP_AddConEmuExeDir))
							continue;
						pszAdd = pOpt->ConEmuExeDir;
						break;
					case 0:
						if (!(pOpt->AddConEmu2Path & CEAP_AddConEmuBaseDir))
							continue;
						if (lstrcmp(pOpt->ConEmuExeDir, pOpt->ConEmuBaseDir) == 0)
							continue; // второй раз ту же директорию не добавляем
						pszAdd = pOpt->ConEmuBaseDir;
						break;
					}

					int nDirLen = lstrlen(pszAdd);
					lstrcpyn(pszDirUpr, pszAdd, MAX_PATH);
					CharUpperBuff(pszDirUpr, nDirLen);

					MCHKHEAP;

					// Need to find exact match!
					bool bFound = false;

					LPCWSTR pszFind = wcsstr(pszUpr, pszDirUpr);
					while (pszFind)
					{
						if (pszFind[nDirLen] == L';' || pszFind[nDirLen] == 0)
						{
							// OK, found
							bFound = true;
							break;
						}
						// Next try (may be partial match of subdirs...)
						pszFind = wcsstr(pszFind+nDirLen, pszDirUpr);
					}

					if (!bFound)
					{
						wchar_t* pszNew = lstrmerge(pszAdd, L";", pszCur);
						if (!pszNew)
						{
							_ASSERTE(pszNew && "Failed to reallocate PATH variable");
							break;
						}
						MCHKHEAP;
						SafeFree(pszCur);
						pszCur = pszNew;
						bChanged = true; // Set flag, check next dir
					}
				}

				MCHKHEAP;

				if (bChanged)
				{
					SetEnvironmentVariable(L"PATH", pszCur);
				}
			}

			MCHKHEAP;

			SafeFree(pszUpr);
			SafeFree(pszDirUpr);

			MCHKHEAP;
			SafeFree(pszCur);
		}
	}
}
Exemple #18
0
void CFdDoc::Serialize(CArchive& ar)
{
	if (ar.IsStoring())
	{
		// TODO: add storing code here
		ElapsedTime = CTime::GetCurrentTime() - StartTime;
		ae->ElapsedTime += ElapsedTime.GetTotalSeconds();
		ae->NumberOfPaints += NumberOfPaints;
		StartTime = CTime::GetCurrentTime();
		NumberOfPaints = 0L;
		ar.Write((void far *)ae, sizeof(ACKENG));
		TRACE("...Game Saved...\n");
		if (fds) fds->TextMsg("Game Saved");
		DocAction = -1;
	}
	else
	{
		// TODO: add loading code here
HGLOBAL		haet;
ACKENG		*aet;
		haet = GlobalAlloc(GMEM_MOVEABLE|GMEM_SHARE, sizeof(ACKENG));
		if (haet == NULL)
		{
			TRACE("GlobalAlloc in CFdDoc of temporary ACKENG struct failed\n");
			return;
		}
		aet = (ACKENG far *)GlobalLock(haet);
		if (ar.GetFile()->GetLength() == sizeof(ACKENG))
		{
			ar.Read((void far *)aet, sizeof(ACKENG));
			if (aet->Version == AE_VERSION && lstrcmp(aet->Descriptor,AE_DESCRIPTOR) == 0)
			{
				memmove((void far *)ae, (void far *)aet, sizeof(ACKENG));
				//	Initialize weapons ammo pointers
				ae->WeaponsCarried[0].Ammo = &ae->Fists;
				ae->WeaponsCarried[1].Ammo = &ae->Bullets;
				ae->WeaponsCarried[2].Ammo = &ae->Shells;
				ae->WeaponsCarried[3].Ammo = &ae->Bullets;
				ae->WeaponsCarried[4].Ammo = &ae->Rockets;
				if (!ae->ObjList[PLAYER_OBJECT].Dead)
						ViewUpDown = 32 << (8 - ViewLowRes);
				TRACE("...Game Loaded...\n");
				if (fds)
				{
					fds->TextHealth();
					fds->TextAmmo();
					fds->TextMsg("Game Loaded");
					fds->DrawKeys();
				}
				StartTime = CTime::GetCurrentTime();
				NumberOfPaints = 0L;
				OurView->GetParentFrame()->SetWindowText("WinAdv");
				if (fdm) fdm->InvalidateRect(NULL,FALSE);
				DocAction = 1;
			}
			else
			{
				AfxMessageBox("Saved file format does not match\n");
				TRACE("Saved file format does not match\n");
			}
		}
		else
		{
			AfxMessageBox("Saved file size is not compatible\n");
			TRACE("Saved file size is not compatible\n");
		}
		GlobalUnlock(haet);
		GlobalFree(haet);
	}
}
Exemple #19
0
void PopulateOptions(RuleNode *options, KeyVal *list)
{

	while (list != NULL)
	{
		if (list->value && (lstrlen(list->value) > 1)) 
			if (list->value[0] == '$')		// its a var
				list->value = getValue(list->value);

		if (!lstrcmp(list->keyword, "msg"))
		{
			if (list->value != NULL)
			{
				list->value[lstrlen(list->value)-1] = '\0';
				options->msg_set = TRUE;
				options->msg = malloc(lstrlen(list->value));
				lstrcpy(options->msg, &list->value[1]);
			}
		}
		else if (!lstrcmp(list->keyword, "content"))
		{
			if (list->value != NULL)
			{
				list->value[lstrlen(list->value)-1] = '\0';
				options->content_set = TRUE;
				options->content = malloc(lstrlen(list->value));
				lstrcpy(options->content, &list->value[1]);
			}
		}
		else if (!lstrcmp(list->keyword, "counter_id"))
		{
			options->counter_id = atoi(list->value);
			if ((options->counter_id >=0) && (options->counter_id <=255))
				options->counter_id_set = TRUE;
		}
		else if (!lstrcmp(list->keyword, "depth"))
		{
			options->depth_set = TRUE;
			options->depth = atoi(list->value);
		}
		else if (!lstrcmp(list->keyword, "offset"))
		{
			options->offset_set = TRUE;
			options->offset = atoi(list->value);
		}
		else if (!lstrcmp(list->keyword, "ttl"))
		{
			options->ttl_set = TRUE;
			options->ttl = atoi(list->value);
		}
		else if (!lstrcmp(list->keyword, "tos"))
		{
			options->tos_set = TRUE;
			options->tos = atoi(list->value);
		}
		else if (!lstrcmp(list->keyword, "id"))
		{
			options->id_set = TRUE;
			options->id = atoi(list->value);
		}
		else if (!lstrcmp(list->keyword, "ipopts"))
		{
			// WRITE THIS
		}
		else if (!lstrcmp(list->keyword, "fragbits"))
		{
			options->fragbits_set = TRUE;
			options->fragbits = getFragbits(list->value, &options->fragbits_op);
		}
		else if (!lstrcmp(list->keyword, "dsize"))
		{
			options->dsize_set = TRUE;
			options->dsize = atoi(list->value);
		}
		else if (!lstrcmp(list->keyword, "flags"))
		{
			options->flags_set = TRUE;
			options->flags = getFlags(list->value, &options->flags_op);
		}
		else if (!lstrcmp(list->keyword, "seq"))
		{
			options->seqnum_set = TRUE;
			options->seqnum = atoi(list->value);
		}
		else if (!lstrcmp(list->keyword, "ack"))
		{
			options->acknum_set = TRUE;
			options->acknum = atoi(list->value);
		}
		else if (!lstrcmp(list->keyword, "itype"))
		{
			options->itype_set = TRUE;
			options->itype = atoi(list->value);
		}
		else if (!lstrcmp(list->keyword, "icode"))
		{
			options->icode_set = TRUE;
			options->icode = atoi(list->value);
		}
		else if (!lstrcmp(list->keyword, "icmp_id"))
		{
			options->icmp_id_set = TRUE;
			options->icmp_id = atoi(list->value);
		}
		else if (!lstrcmp(list->keyword, "icmp_seq"))
		{
			options->icmp_seq_set = TRUE;
			options->icmp_seq = atoi(list->value);
		}

		list = list->next;
	}
}
void WordStyleDlg::setVisualFromStyleList() 
{
	showGlobalOverrideCtrls(false);

	Style & style = getCurrentStyler();

	// Global override style
	if (style._styleDesc && lstrcmp(style._styleDesc, TEXT("Global override")) == 0)
	{
		showGlobalOverrideCtrls(true);
	}

	//--Warning text
	//bool showWarning = ((_currentLexerIndex == 0) && (style._styleID == STYLE_DEFAULT));//?SW_SHOW:SW_HIDE;

	COLORREF c = RGB(0x00, 0x00, 0xFF);
	TCHAR str[256];

	str[0] = '\0';
	
	int i = ::SendDlgItemMessage(_hSelf, IDC_LANGUAGES_LIST, LB_GETCURSEL, 0, 0);
	if (i == LB_ERR)
		return;
	::SendDlgItemMessage(_hSelf, IDC_LANGUAGES_LIST, LB_GETTEXT, i, (LPARAM)str);

	i = ::SendDlgItemMessage(_hSelf, IDC_STYLES_LIST, LB_GETCURSEL, 0, 0);
	if (i == LB_ERR)
		return;
	TCHAR styleName[64];
	::SendDlgItemMessage(_hSelf, IDC_STYLES_LIST, LB_GETTEXT, i, (LPARAM)styleName);

	lstrcat(lstrcat(str, TEXT(" : ")), styleName);

	// PAD for fix a display glitch
	lstrcat(str, TEXT("          "));
	colourHooker.setColour(c);
	::SetWindowText(_hStyleInfoStaticText, str);

	//-- 2 couleurs : fg et bg
	bool isEnable = false;
	if (HIBYTE(HIWORD(style._fgColor)) != 0xFF)
	{
		_pFgColour->setColour(style._fgColor);
		_pFgColour->setEnabled((style._colorStyle & COLORSTYLE_FOREGROUND) != 0);
		isEnable = true;
	}
	enableFg(isEnable);

	isEnable = false;
	if (HIBYTE(HIWORD(style._bgColor)) != 0xFF)
	{
		_pBgColour->setColour(style._bgColor);
		_pBgColour->setEnabled((style._colorStyle & COLORSTYLE_BACKGROUND) != 0);
		isEnable = true;
	}
	enableBg(isEnable);

	//-- font name
	isEnable = false;
	int iFontName;
	if (style._fontName != NULL)
	{
		iFontName = ::SendMessage(_hFontNameCombo, CB_FINDSTRING, 1, (LPARAM)style._fontName);
		if (iFontName == CB_ERR)
			iFontName = 0;
		isEnable = true;
	}
	else
	{
		iFontName = 0;
	}
	::SendMessage(_hFontNameCombo, CB_SETCURSEL, iFontName, 0);
	enableFontName(isEnable);

	//-- font size
	isEnable = false;
	TCHAR intStr[5] = TEXT("");
	int iFontSize = 0;
	if (style._fontSize != STYLE_NOT_USED)
	{
		wsprintf(intStr, TEXT("%d"), style._fontSize);
		iFontSize = ::SendMessage(_hFontSizeCombo, CB_FINDSTRING, 1, (LPARAM)intStr);
		isEnable = true;
	}
	::SendMessage(_hFontSizeCombo, CB_SETCURSEL, iFontSize, 0);
	enableFontSize(isEnable);

	//-- font style : bold & italic
	isEnable = false;
	int isBold, isItalic, isUnderline;
	if (style._fontStyle != STYLE_NOT_USED)
	{
		isBold = (style._fontStyle & FONTSTYLE_BOLD)?BST_CHECKED:BST_UNCHECKED;
		isItalic = (style._fontStyle & FONTSTYLE_ITALIC)?BST_CHECKED:BST_UNCHECKED;
		isUnderline = (style._fontStyle & FONTSTYLE_UNDERLINE)?BST_CHECKED:BST_UNCHECKED;
		::SendMessage(_hCheckBold, BM_SETCHECK, isBold, 0);
		::SendMessage(_hCheckItalic, BM_SETCHECK, isItalic, 0);
		::SendMessage(_hCheckUnderline, BM_SETCHECK, isUnderline, 0);
		isEnable = true;
	}
	else // STYLE_NOT_USED : reset them all
	{
		::SendMessage(_hCheckBold, BM_SETCHECK, BST_UNCHECKED, 0);
		::SendMessage(_hCheckItalic, BM_SETCHECK, BST_UNCHECKED, 0);
		::SendMessage(_hCheckUnderline, BM_SETCHECK, BST_UNCHECKED, 0);
	}

	enableFontStyle(isEnable);


	//-- Default Keywords
	bool shouldBeDisplayed = style._keywordClass != STYLE_NOT_USED;
	if (shouldBeDisplayed)
	{
		LexerStyler & lexerStyler = _lsArray.getLexerFromIndex(_currentLexerIndex - 1);

		NppParameters *pNppParams = NppParameters::getInstance();
		LangType lType = pNppParams->getLangIDFromStr(lexerStyler.getLexerName());
		if (lType == L_TEXT)
		{
			generic_string str = lexerStyler.getLexerName();
			str += TEXT(" is not defined in NppParameters::getLangIDFromStr()");
				printStr(str.c_str());
		}
		const TCHAR *kws = pNppParams->getWordList(lType, style._keywordClass);
		if (!kws)
			kws = TEXT("");
		::SendDlgItemMessage(_hSelf, IDC_DEF_KEYWORDS_EDIT, WM_SETTEXT, 0, (LPARAM)(kws));

		const TCHAR *ckwStr = (style._keywords)?style._keywords->c_str():TEXT("");
		::SendDlgItemMessage(_hSelf, IDC_USER_KEYWORDS_EDIT, WM_SETTEXT, 0, (LPARAM)(ckwStr));
	}
	int showOption = shouldBeDisplayed?SW_SHOW:SW_HIDE;
	::ShowWindow(::GetDlgItem(_hSelf, IDC_DEF_KEYWORDS_EDIT), showOption);
	::ShowWindow(::GetDlgItem(_hSelf, IDC_USER_KEYWORDS_EDIT),showOption);
	::ShowWindow(::GetDlgItem(_hSelf, IDC_DEF_KEYWORDS_STATIC), showOption);
	::ShowWindow(::GetDlgItem(_hSelf, IDC_USER_KEYWORDS_STATIC),showOption);
	::ShowWindow(::GetDlgItem(_hSelf, IDC_PLUSSYMBOL_STATIC),showOption);

	redraw();
}
Exemple #21
0
BOOL CALLBACK SERVER::KeyAggregateName_Compare (LPHASHLISTKEY pKey, PVOID pObject, PVOID pData)
{
   return !lstrcmp (((LPAGGREGATE)pObject)->m_szName, (LPTSTR)pData);
}
Exemple #22
0
data_item *InitParams(char *params) {

  data_item *d = new data_item;

  InitRestore(NULL, params);   
    
  // get message      
  char *str = RestoreStr();
  if (!lstrcmp(str, "global"))
  {
    d->state_type = STATE_GLOBAL;
    d->state = NULL;
  }
  else if (!lstrcmp(str, "new"))
  {
    d->state_type = STATE_NEW;
    d->state = NULL;
  }
  else
  {
    d->state_type = STATE_REUSE;
    d->state = new_state();
  }

  str = RestoreStr();
  if (str)
  {
    d->script = findfile(str);
  }
  else
  {
    d->script = NULL;
  }

  int i=0;

  str = RestoreStr();
  if (str)
  {
    d->command = mstrdup(str);
  }
  else
  {
    d->command = NULL;
  }

  str = RestoreStr();
  if (str)
  {
    d->args = mstrdup(str);
  }
  else
  {
    d->args = NULL;
  }


  EndRestore();

  return d;
}
Exemple #23
0
/*!
 *  This function is used to determine if a control needs to be painted when
 *  it is moved or resized by the layout manager.
 *  
 *  @param layout Reference to a @c LAYOUTINFO structure for the control
 *  @param rectOld Reference to a @c RECT structure that holds the control
 *         position and size before the layout update
 *  @param rectNew Reference to a @c RECT structure that holds the control
 *         position and size after the layout update
 *  
 *  @return The return value is @c TRUE if the control should be freshly
 *          painted after a layout update, @c FALSE if not necessary.
 *
 *  @remarks The default implementation tries to identify windows that
 *           need refresh by their class name and window style.
 *        @n Override this function if you need a different behavior or if
 *           you have custom controls that fail to be identified.
 *
 *  @sa LikesClipping InitResizeProperties
 */
BOOL CResizableLayout::NeedsRefresh(const LAYOUTINFO& layout,
								const CRect& rectOld, const CRect& rectNew) const
{
	if (layout.bMsgSupport)
	{
		REFRESHPROPERTY refresh;
		refresh.rcOld = rectOld;
		refresh.rcNew = rectNew;
		if (Send_NeedsRefresh(layout.hWnd, &refresh))
			return refresh.bNeedsRefresh;
	}

	int nDiffWidth = (rectNew.Width() - rectOld.Width());
	int nDiffHeight = (rectNew.Height() - rectOld.Height());

	// is the same size?
	if (nDiffWidth == 0 && nDiffHeight == 0)
		return FALSE;

	// optimistic, no need to refresh
	BOOL bRefresh = FALSE;

	// window classes that need refresh when resized
	if (0 == lstrcmp(layout.sWndClass, WC_STATIC))
	{
		DWORD style = ::GetWindowLong(layout.hWnd, GWL_STYLE);

		switch (style & SS_TYPEMASK)
		{
		case SS_LEFT:
		case SS_CENTER:
		case SS_RIGHT:
			// word-wrapped text
			bRefresh = bRefresh || (nDiffWidth != 0);
			// vertically centered text
			if (style & SS_CENTERIMAGE)
				bRefresh = bRefresh || (nDiffHeight != 0);
			break;

		case SS_LEFTNOWORDWRAP:
			// text with ellipsis
			if (style & SS_ELLIPSISMASK)
				bRefresh = bRefresh || (nDiffWidth != 0);
			// vertically centered text
			if (style & SS_CENTERIMAGE)
				bRefresh = bRefresh || (nDiffHeight != 0);
			break;

		case SS_ENHMETAFILE:
		case SS_BITMAP:
		case SS_ICON:
			// images
		case SS_BLACKFRAME:
		case SS_GRAYFRAME:
		case SS_WHITEFRAME:
		case SS_ETCHEDFRAME:
			// and frames
			bRefresh = TRUE;
			break;
		}
		return bRefresh;
	}

	// window classes that don't redraw client area correctly
	// when the hor scroll pos changes due to a resizing
	BOOL bHScroll = FALSE;
	if (0 == lstrcmp(layout.sWndClass, WC_LISTBOX))
		bHScroll = TRUE;

	// fix for horizontally scrollable windows, if wider
	if (bHScroll && (nDiffWidth > 0))
	{
		// get max scroll position
		SCROLLINFO info;
		info.cbSize = sizeof(SCROLLINFO);
		info.fMask = SIF_PAGE | SIF_POS | SIF_RANGE;
		if (::GetScrollInfo(layout.hWnd, SB_HORZ, &info))
		{
			// subtract the page size
			info.nMax -= __max(info.nPage - 1, 0);
		}

		// resizing will cause the text to scroll on the right
		// because the scrollbar is going beyond the right limit
		if ((info.nMax > 0) && (info.nPos + nDiffWidth > info.nMax))
		{
			// needs repainting, due to horiz scrolling
			bRefresh = TRUE;
		}
	}

	return bRefresh;
}
Exemple #24
0
BOOL CALLBACK SelectDbDlgProc(HWND hdlg,UINT message,WPARAM wParam,LPARAM lParam)
{
	BOOL bReturn;
	if ( DoMyControlProcessing( hdlg, message, wParam, lParam, &bReturn ))
		return bReturn;

	switch ( message ) {
		case WM_INITDIALOG:
		{
			TCHAR szMirandaPath[MAX_PATH];
			szMirandaPath[ 0 ] = 0;
			{	HIMAGELIST hIml;
				hIml=ImageList_Create(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON),
					(IsWinVerXPPlus() ? ILC_COLOR32 : ILC_COLOR16) | ILC_MASK, 3, 3);
				ImageList_AddIcon(hIml,LoadIcon(hInst,MAKEINTRESOURCE(IDI_PROFILEGREEN)));
				ImageList_AddIcon(hIml,LoadIcon(hInst,MAKEINTRESOURCE(IDI_PROFILEYELLOW)));
				ImageList_AddIcon(hIml,LoadIcon(hInst,MAKEINTRESOURCE(IDI_PROFILERED)));
				ImageList_AddIcon(hIml,LoadIcon(hInst,MAKEINTRESOURCE(IDI_BAD)));
				ListView_SetImageList(GetDlgItem(hdlg,IDC_DBLIST),hIml,LVSIL_SMALL);
			}
			ListView_SetExtendedListViewStyleEx(GetDlgItem(hdlg,IDC_DBLIST),LVS_EX_FULLROWSELECT,LVS_EX_FULLROWSELECT);
			{	LV_COLUMN lvc;
				lvc.mask = LVCF_WIDTH | LVCF_FMT | LVCF_TEXT;
				lvc.cx = 205;
				lvc.fmt = LVCFMT_LEFT;
				lvc.pszText = TranslateT("Database");
				ListView_InsertColumn( GetDlgItem(hdlg,IDC_DBLIST), 0, &lvc );
				lvc.cx = 68;
				lvc.fmt = LVCFMT_RIGHT;
				lvc.pszText = TranslateT("Total size");
				ListView_InsertColumn(GetDlgItem(hdlg,IDC_DBLIST), 1, &lvc );
				lvc.pszText = TranslateT("Wasted");
				ListView_InsertColumn(GetDlgItem(hdlg,IDC_DBLIST), 2, &lvc );
			}
			{
				TCHAR *str2;
				GetModuleFileName(NULL,szMirandaPath,SIZEOF(szMirandaPath));
				str2 = _tcsrchr(szMirandaPath,'\\');
				if( str2 != NULL )
					*str2=0;
			}
			{
				int i = 0;
				HKEY hKey;
				TCHAR szProfileDir[MAX_PATH];
				DWORD cbData = SIZEOF(szMirandaPath);
				TCHAR szMirandaProfiles[MAX_PATH];

				_tcscpy(szMirandaProfiles, szMirandaPath);
				_tcscat(szMirandaProfiles, _T("\\Profiles"));

				GetProfileDirectory(szMirandaPath,szProfileDir,SIZEOF(szProfileDir));
				// search in profile dir (using ini file)
				if( lstrcmpi(szProfileDir,szMirandaProfiles) )
					FindAdd(hdlg, szProfileDir, _T("[ini]\\"));

				FindAdd(hdlg, szMirandaProfiles, _T("[prf]\\"));
				// search in current dir (as DBTOOL)
				FindAdd(hdlg, szMirandaPath, _T("[ . ]\\"));

				// search in profile dir (using registry path + ini file)
				if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,_T("SOFTWARE\\Miranda"),0,KEY_QUERY_VALUE,&hKey) == ERROR_SUCCESS) {
					if(RegQueryValueEx(hKey,_T("Install_Dir"),NULL,NULL,(PBYTE)szMirandaPath,&cbData) == ERROR_SUCCESS) {
						if( lstrcmp(szProfileDir,szMirandaPath) ) {
							GetProfileDirectory(szMirandaPath,szProfileDir,SIZEOF(szProfileDir));
							FindAdd(hdlg, szProfileDir, _T("[reg]\\"));
						}
					}
					RegCloseKey(hKey);
				}
				// select
				if ( opts.filename[0] )
					i = AddDatabaseToList( GetDlgItem( hdlg, IDC_DBLIST ), opts.filename, _T("") );
				if ( i == -1 )
					i = 0;
				ListView_SetItemState( GetDlgItem(hdlg,IDC_DBLIST), i, LVIS_SELECTED, LVIS_SELECTED );
			}
			if ( opts.hFile != NULL && opts.hFile != INVALID_HANDLE_VALUE ) {
				CloseHandle( opts.hFile );
				opts.hFile = NULL;
			}
			TranslateDialog( hdlg );
			return TRUE;
		}

		case WZN_PAGECHANGING:
			GetDlgItemText( hdlg, IDC_FILE, opts.filename, SIZEOF(opts.filename));
			break;

		case WM_COMMAND:
			switch(LOWORD(wParam)) {
				case IDC_FILE:
					if(HIWORD(wParam)==EN_CHANGE)
						EnableWindow(GetDlgItem(GetParent(hdlg),IDOK),GetWindowTextLength(GetDlgItem(hdlg,IDC_FILE)));
					break;
				case IDC_OTHER:
				{	OPENFILENAME ofn={0};
					TCHAR str[MAX_PATH];

					// _T("Miranda Databases (*.dat)\0*.DAT\0All Files (*)\0*\0");
					TCHAR *filter, *tmp, *tmp1, *tmp2;
					tmp1 = TranslateT("Miranda Databases (*.dat)");
					tmp2 = TranslateT("All Files");
					filter = tmp = (TCHAR*)_malloca((_tcslen(tmp1)+_tcslen(tmp2)+11)*sizeof(TCHAR));
					tmp = addstring(tmp, tmp1);
					tmp = addstring(tmp, _T("*.DAT"));
					tmp = addstring(tmp, tmp2);
					tmp = addstring(tmp, _T("*"));
					*tmp = 0;

					GetDlgItemText( hdlg, IDC_FILE, str, SIZEOF( str ));
					ofn.lStructSize = sizeof(ofn);
					ofn.hwndOwner = hdlg;
					ofn.hInstance = NULL;
					ofn.lpstrFilter = filter;
					ofn.lpstrDefExt = _T("dat");
					ofn.lpstrFile = str;
					ofn.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
					ofn.nMaxFile = SIZEOF(str);
					ofn.nMaxFileTitle = MAX_PATH;
					if ( GetOpenFileName( &ofn )) {
						int i;
						i = AddDatabaseToList( GetDlgItem(hdlg,IDC_DBLIST), str, _T("") );
						if ( i == -1 )
							i=0;
						ListView_SetItemState( GetDlgItem(hdlg,IDC_DBLIST), i, LVIS_SELECTED, LVIS_SELECTED );
					}
					break;
				}
				case IDC_BACK:
					SendMessage(GetParent(hdlg),WZM_GOTOPAGE,IDD_WELCOME,(LPARAM)WelcomeDlgProc);
					break;
				case IDOK:
					opts.hFile = CreateFile( opts.filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
					if ( opts.hFile == INVALID_HANDLE_VALUE ) {
						opts.hFile = NULL;
						opts.error = GetLastError();
						SendMessage( GetParent(hdlg), WZM_GOTOPAGE, IDD_OPENERROR, ( LPARAM )OpenErrorDlgProc );
					}
					else SendMessage( GetParent(hdlg), WZM_GOTOPAGE, IDD_FILEACCESS, (LPARAM)FileAccessDlgProc );
					break;
			}
			break;
		case WM_NOTIFY:
			switch(((LPNMHDR)lParam)->idFrom) {
				case IDC_DBLIST:
					switch(((LPNMLISTVIEW)lParam)->hdr.code) {
						case LVN_ITEMCHANGED:
						{	LV_ITEM lvi;
							lvi.iItem=ListView_GetNextItem(GetDlgItem(hdlg,IDC_DBLIST),-1,LVNI_SELECTED);
							if(lvi.iItem==-1) break;
							lvi.mask=LVIF_PARAM;
							ListView_GetItem(GetDlgItem(hdlg,IDC_DBLIST),&lvi);
							SetDlgItemText(hdlg,IDC_FILE,(TCHAR*)lvi.lParam);
							SendMessage(hdlg,WM_COMMAND,MAKEWPARAM(IDC_FILE,EN_CHANGE),(LPARAM)GetDlgItem(hdlg,IDC_FILE));
							break;
						}
					}
					break;
			}
			break;
		case WM_DESTROY:
			{	LV_ITEM lvi;
				lvi.mask=LVIF_PARAM;
				for(lvi.iItem=ListView_GetItemCount(GetDlgItem(hdlg,IDC_DBLIST))-1;lvi.iItem>=0;lvi.iItem--) {
					ListView_GetItem(GetDlgItem(hdlg,IDC_DBLIST),&lvi);
					free((char*)lvi.lParam);
				}
			}
			break;
	}
	return FALSE;
}
INT_PTR CALLBACK RegExtDlg::run_dlgProc(UINT Message, WPARAM wParam, LPARAM lParam)
{
	switch (Message)
	{
		case WM_INITDIALOG :
		{
			getRegisteredExts();
			getDefSupportedExts();
			//goToCenter();
			::EnableWindow(::GetDlgItem(_hSelf, IDC_ADDFROMLANGEXT_BUTTON), false);
			::EnableWindow(::GetDlgItem(_hSelf, IDC_REMOVEEXT_BUTTON), false);
			::SendDlgItemMessage(_hSelf, IDC_CUSTOMEXT_EDIT, EM_SETLIMITTEXT, extNameMax-1, 0);
			return TRUE;
		}

		case WM_DRAWITEM :
		{
			HICON hIcon = ::LoadIcon(_hInst, MAKEINTRESOURCE(IDI_DELETE_ICON));
			DRAWITEMSTRUCT *pdis = (DRAWITEMSTRUCT *)lParam;
			::DrawIcon(pdis->hDC, 0, 0, hIcon);
			return TRUE;
		}

		case WM_COMMAND :
		{
			// Handle File association list extension
			if (LOWORD(wParam) == IDC_REGEXT_LANGEXT_LIST || LOWORD(wParam) == IDC_REGEXT_REGISTEREDEXTS_LIST)
			{
				// On double click an item in the list then toggle the item between both lists
				// by simulating "<-" or "->" button clicked
				if (HIWORD(wParam) == LBN_DBLCLK)
				{
					// Check whether click happened on a item not in empty area
					if (-1 != ::SendDlgItemMessage(_hSelf, LOWORD(wParam), LB_GETCURSEL, 0, 0))
					{
						HWND(lParam) == ::GetDlgItem(_hSelf, IDC_REGEXT_LANGEXT_LIST) ?
							::SendMessage(_hSelf, WM_COMMAND, IDC_ADDFROMLANGEXT_BUTTON, 0) :
							::SendMessage(_hSelf, WM_COMMAND, IDC_REMOVEEXT_BUTTON, 0);
					}
					return TRUE;
				}
			}

			switch (wParam)
			{
				case IDC_ADDFROMLANGEXT_BUTTON :
				{
					writeNppPath();

					TCHAR ext2Add[extNameMax] = TEXT("");
					if (!_isCustomize)
					{
						auto index2Add = ::SendDlgItemMessage(_hSelf, IDC_REGEXT_LANGEXT_LIST, LB_GETCURSEL, 0, 0);
						auto lbTextLen = ::SendDlgItemMessage(_hSelf, IDC_REGEXT_LANGEXT_LIST, LB_GETTEXTLEN, index2Add, 0);
						if (lbTextLen > extNameMax - 1)
							return TRUE;

						::SendDlgItemMessage(_hSelf, IDC_REGEXT_LANGEXT_LIST, LB_GETTEXT, index2Add, reinterpret_cast<LPARAM>(ext2Add));
						addExt(ext2Add);
						::SendDlgItemMessage(_hSelf, IDC_REGEXT_LANGEXT_LIST, LB_DELETESTRING, index2Add, 0);
					}
					else
					{
						::SendDlgItemMessage(_hSelf, IDC_CUSTOMEXT_EDIT, WM_GETTEXT, extNameMax, reinterpret_cast<LPARAM>(ext2Add));
						auto i = ::SendDlgItemMessage(_hSelf, IDC_REGEXT_REGISTEREDEXTS_LIST, LB_FINDSTRINGEXACT, 0, reinterpret_cast<LPARAM>(ext2Add));
						if (i != LB_ERR)
							return TRUE;
						addExt(ext2Add);
						::SendDlgItemMessage(_hSelf, IDC_CUSTOMEXT_EDIT, WM_SETTEXT, 0, reinterpret_cast<LPARAM>(TEXT("")));
					}
					::SendDlgItemMessage(_hSelf, IDC_REGEXT_REGISTEREDEXTS_LIST, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(ext2Add));
					::EnableWindow(::GetDlgItem(_hSelf, IDC_ADDFROMLANGEXT_BUTTON), false);
					return TRUE;
				}

				case IDC_REMOVEEXT_BUTTON :
				{
					TCHAR ext2Sup[extNameMax] = TEXT("");
					auto index2Sup = ::SendDlgItemMessage(_hSelf, IDC_REGEXT_REGISTEREDEXTS_LIST, LB_GETCURSEL, 0, 0);
					auto lbTextLen = ::SendDlgItemMessage(_hSelf, IDC_REGEXT_REGISTEREDEXTS_LIST, LB_GETTEXTLEN, index2Sup, 0);
					if (lbTextLen > extNameMax - 1)
						return TRUE;

					::SendDlgItemMessage(_hSelf, IDC_REGEXT_REGISTEREDEXTS_LIST, LB_GETTEXT, index2Sup, reinterpret_cast<LPARAM>(ext2Sup));
					if (deleteExts(ext2Sup))
						::SendDlgItemMessage(_hSelf, IDC_REGEXT_REGISTEREDEXTS_LIST, LB_DELETESTRING, index2Sup, 0);
					auto langIndex = ::SendDlgItemMessage(_hSelf, IDC_REGEXT_LANG_LIST, LB_GETCURSEL, 0, 0);

					::EnableWindow(::GetDlgItem(_hSelf, IDC_REMOVEEXT_BUTTON), false);

					if (langIndex != LB_ERR)
					{
						for (int i = 1 ; i < nbExtMax ; ++i)
						{
							if (!generic_stricmp(ext2Sup, defExtArray[langIndex][i]))
							{
								::SendDlgItemMessage(_hSelf, IDC_REGEXT_LANGEXT_LIST, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(ext2Sup));
								return TRUE;
							}
						}
					}
					return TRUE;
				}

				case IDCANCEL:
				{
					::EndDialog(_hSelf, 0);
					return TRUE;
				}
			}

			if (HIWORD(wParam) == EN_CHANGE)
			{
				TCHAR text[extNameMax] = TEXT("");
				::SendDlgItemMessage(_hSelf, IDC_CUSTOMEXT_EDIT, WM_GETTEXT, extNameMax, reinterpret_cast<LPARAM>(text));
				if ((lstrlen(text) == 1) && (text[0] != '.'))
				{
					text[1] = text[0];
					text[0] = '.';
					text[2] = '\0';
					::SendDlgItemMessage(_hSelf, IDC_CUSTOMEXT_EDIT, WM_SETTEXT, 0, reinterpret_cast<LPARAM>(text));
					::SendDlgItemMessage(_hSelf, IDC_CUSTOMEXT_EDIT, EM_SETSEL, 2, 2);
				}
				::EnableWindow(::GetDlgItem(_hSelf, IDC_ADDFROMLANGEXT_BUTTON), (lstrlen(text) > 1));
				return TRUE;
			}

			if (HIWORD(wParam) == LBN_SELCHANGE)
			{
				auto i = ::SendDlgItemMessage(_hSelf, LOWORD(wParam), LB_GETCURSEL, 0, 0);
				if (LOWORD(wParam) == IDC_REGEXT_LANG_LIST)
				{
					if (i != LB_ERR)
					{
						const size_t itemNameLen = 32;
						TCHAR itemName[itemNameLen + 1];
						auto lbTextLen = ::SendDlgItemMessage(_hSelf, LOWORD(wParam), LB_GETTEXTLEN, i, 0);
						if (lbTextLen > itemNameLen)
							return TRUE;

						::SendDlgItemMessage(_hSelf, LOWORD(wParam), LB_GETTEXT, i, reinterpret_cast<LPARAM>(itemName));

						if (!generic_stricmp(defExtArray[nbSupportedLang-1][0], itemName))
						{
							::ShowWindow(::GetDlgItem(_hSelf, IDC_REGEXT_LANGEXT_LIST), SW_HIDE);
							::ShowWindow(::GetDlgItem(_hSelf, IDC_CUSTOMEXT_EDIT), SW_SHOW);
							_isCustomize = true;
						}
						else
						{
							if (_isCustomize)
							{
								::ShowWindow(::GetDlgItem(_hSelf, IDC_REGEXT_LANGEXT_LIST), SW_SHOW);
								::ShowWindow(::GetDlgItem(_hSelf, IDC_CUSTOMEXT_EDIT), SW_HIDE);

								_isCustomize = false;
							}
							LRESULT count = ::SendDlgItemMessage(_hSelf, IDC_REGEXT_LANGEXT_LIST, LB_GETCOUNT, 0, 0);
							for (count -= 1 ; count >= 0 ; count--)
								::SendDlgItemMessage(_hSelf, IDC_REGEXT_LANGEXT_LIST, LB_DELETESTRING, count, 0);

							for (int j = 1 ; j < nbExtMax ; ++j)
							{
								if (lstrcmp(TEXT(""), defExtArray[i][j]))
								{
									auto index = ::SendDlgItemMessage(_hSelf, IDC_REGEXT_REGISTEREDEXTS_LIST, LB_FINDSTRINGEXACT, 0, reinterpret_cast<LPARAM>(defExtArray[i][j]));
									if (index == -1)
										::SendDlgItemMessage(_hSelf, IDC_REGEXT_LANGEXT_LIST, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(defExtArray[i][j]));
								}
							}
						}

						::EnableWindow(::GetDlgItem(_hSelf, IDC_ADDFROMLANGEXT_BUTTON), false);
					}
				}
				else if (LOWORD(wParam) == IDC_REGEXT_LANGEXT_LIST)
				{
					if (i != LB_ERR)
						::EnableWindow(::GetDlgItem(_hSelf, IDC_ADDFROMLANGEXT_BUTTON), true);
				}
				else if (LOWORD(wParam) == IDC_REGEXT_REGISTEREDEXTS_LIST)
				{
					if (i != LB_ERR)
						::EnableWindow(::GetDlgItem(_hSelf, IDC_REMOVEEXT_BUTTON), true);
				}
			}

			// break; // no break here
		}

		default :
			return FALSE;
	}
	//return FALSE;
}
INT_PTR CJabberDlgGcJoin::DlgProc(UINT msg, WPARAM wParam, LPARAM lParam)
{
	TCHAR text[128];

	switch ( msg ) {
	case WM_DELETEITEM:
	{
		LPDELETEITEMSTRUCT lpdis = (LPDELETEITEMSTRUCT)lParam;
		if (lpdis->CtlID != IDC_ROOM)
			break;

		RoomInfo *info = (RoomInfo *)lpdis->itemData;
		if (info->line1) mir_free(info->line1);
		if (info->line2) mir_free(info->line2);
		mir_free(info);

		break;
	}

	case WM_MEASUREITEM:
	{
		LPMEASUREITEMSTRUCT lpmis = (LPMEASUREITEMSTRUCT)lParam;
		if (lpmis->CtlID != IDC_ROOM)
			break;

		lpmis->itemHeight = 2*sttTextLineHeight;
		if (lpmis->itemID == -1)
			lpmis->itemHeight = sttTextLineHeight-1;

		break;
	}

	case WM_DRAWITEM:
	{
		LPDRAWITEMSTRUCT lpdis = (LPDRAWITEMSTRUCT)lParam;
		if (lpdis->CtlID != IDC_ROOM)
			break;

		if (lpdis->itemID < 0)
			break;

		RoomInfo *info = (RoomInfo *)SendDlgItemMessage(m_hwnd, IDC_ROOM, CB_GETITEMDATA, lpdis->itemID, 0);
		COLORREF clLine1, clLine2, clBack;

		if (lpdis->itemState & ODS_SELECTED)
		{
			FillRect(lpdis->hDC, &lpdis->rcItem, GetSysColorBrush(COLOR_HIGHLIGHT));
			clBack = GetSysColor(COLOR_HIGHLIGHT);
			clLine1 = GetSysColor(COLOR_HIGHLIGHTTEXT);
		} else
		{
			FillRect(lpdis->hDC, &lpdis->rcItem, GetSysColorBrush(COLOR_WINDOW));
			clBack = GetSysColor(COLOR_WINDOW);
			clLine1 = GetSysColor(COLOR_WINDOWTEXT);
		}
		clLine2 = RGB(
				GetRValue(clLine1) * 0.66 + GetRValue(clBack) * 0.34,
				GetGValue(clLine1) * 0.66 + GetGValue(clBack) * 0.34,
				GetBValue(clLine1) * 0.66 + GetBValue(clBack) * 0.34
			);

		SetBkMode(lpdis->hDC, TRANSPARENT);

		RECT rc;

		rc = lpdis->rcItem;
		rc.bottom -= (rc.bottom - rc.top) / 2;
		rc.left += 20;
		SetTextColor(lpdis->hDC, clLine1);
		DrawText(lpdis->hDC, info->line1, lstrlen(info->line1), &rc, DT_LEFT|DT_NOPREFIX|DT_SINGLELINE|DT_VCENTER|DT_WORD_ELLIPSIS);

		rc = lpdis->rcItem;
		rc.top += (rc.bottom - rc.top) / 2;
		rc.left += 20;
		SetTextColor(lpdis->hDC, clLine2);
		DrawText(lpdis->hDC, info->line2, lstrlen(info->line2), &rc, DT_LEFT|DT_NOPREFIX|DT_SINGLELINE|DT_VCENTER|DT_WORD_ELLIPSIS);

		DrawIconEx(lpdis->hDC, lpdis->rcItem.left+1, lpdis->rcItem.top+1, m_proto->LoadIconEx("group"), 16, 16, 0, NULL, DI_NORMAL);
		switch (info->overlay) {
		case RoomInfo::ROOM_WAIT:
			DrawIconEx(lpdis->hDC, lpdis->rcItem.left+1, lpdis->rcItem.top+1, m_proto->LoadIconEx("disco_progress"), 16, 16, 0, NULL, DI_NORMAL);
			break;
		case RoomInfo::ROOM_FAIL:
			DrawIconEx(lpdis->hDC, lpdis->rcItem.left+1, lpdis->rcItem.top+1, m_proto->LoadIconEx("disco_fail"), 16, 16, 0, NULL, DI_NORMAL);
			break;
		case RoomInfo::ROOM_BOOKMARK:
			DrawIconEx(lpdis->hDC, lpdis->rcItem.left+1, lpdis->rcItem.top+1, m_proto->LoadIconEx("disco_ok"), 16, 16, 0, NULL, DI_NORMAL);
			break;
		}
	}

	case WM_COMMAND:
		switch ( LOWORD( wParam )) {
		case IDC_SERVER:
			switch (HIWORD(wParam)) {
			case CBN_EDITCHANGE:
			case CBN_SELCHANGE:
				{
					int iqid = GetWindowLongPtr(GetDlgItem(m_hwnd, IDC_ROOM), GWLP_USERDATA);
					if (iqid)
					{
						m_proto->m_iqManager.ExpireIq(iqid);
						SetWindowLongPtr(GetDlgItem(m_hwnd, IDC_ROOM), GWLP_USERDATA, 0);
					}
					SendDlgItemMessage(m_hwnd, IDC_ROOM, CB_RESETCONTENT, 0, 0);
				}
				break;
			}
			break;

		case IDC_ROOM:
			switch (HIWORD(wParam)) {
			case CBN_DROPDOWN:
				if (!SendDlgItemMessage(m_hwnd, IDC_ROOM, CB_GETCOUNT, 0, 0))
				{
					int iqid = GetWindowLongPtr(GetDlgItem(m_hwnd, IDC_ROOM), GWLP_USERDATA);
					if (iqid)
					{
						m_proto->m_iqManager.ExpireIq(iqid);
						SetWindowLongPtr(GetDlgItem(m_hwnd, IDC_ROOM), GWLP_USERDATA, 0);
					}

					SendDlgItemMessage(m_hwnd, IDC_ROOM, CB_RESETCONTENT, 0, 0);

					int len = GetWindowTextLength(GetDlgItem(m_hwnd, IDC_SERVER)) + 1;
					TCHAR *server = (TCHAR *)_alloca(len * sizeof(TCHAR));
					GetWindowText(GetDlgItem(m_hwnd, IDC_SERVER), server, len);

					if (*server)
					{
						sttRoomListAppend(GetDlgItem(m_hwnd, IDC_ROOM), RoomInfo::ROOM_WAIT, TranslateT("Loading..."), TranslateT("Please wait for room list to download."), _T(""));

						CJabberIqInfo *pInfo = m_proto->m_iqManager.AddHandler( &CJabberProto::OnIqResultDiscovery, JABBER_IQ_TYPE_GET, server, 0, -1, (void *)GetDlgItem(m_hwnd, IDC_ROOM));
						pInfo->SetTimeout(30000);
						XmlNodeIq iq(pInfo);
						iq << XQUERY( _T(JABBER_FEAT_DISCO_ITEMS));
						m_proto->m_ThreadInfo->send(iq);

						SetWindowLongPtr(GetDlgItem(m_hwnd, IDC_ROOM), GWLP_USERDATA, pInfo->GetIqId());
					} else
					{
						sttRoomListAppend(GetDlgItem(m_hwnd, IDC_ROOM), RoomInfo::ROOM_FAIL,
							TranslateT("Jabber Error"),
							TranslateT("Please specify groupchat directory first."),
							_T(""));
					}
				}
				break;
			}
			break;

		case IDC_BOOKMARKS:
			{
				HMENU hMenu = CreatePopupMenu();

				LISTFOREACH(i, m_proto, LIST_BOOKMARK)
				{
					JABBER_LIST_ITEM *item = 0;
					if (item = m_proto->ListGetItemPtrFromIndex(i))
						if (!lstrcmp(item->type, _T("conference")))
							AppendMenu(hMenu, MF_STRING, (UINT_PTR)item, item->name);
				}
				AppendMenu(hMenu, MF_SEPARATOR, 0, NULL);
				AppendMenu(hMenu, MF_STRING, (UINT_PTR)-1, TranslateT("Bookmarks..."));
				AppendMenu(hMenu, MF_STRING, (UINT_PTR)0, TranslateT("Cancel"));

				RECT rc; GetWindowRect(GetDlgItem(m_hwnd, IDC_BOOKMARKS), &rc);
				CheckDlgButton(m_hwnd, IDC_BOOKMARKS, TRUE);
				int res = TrackPopupMenu(hMenu, TPM_RETURNCMD, rc.left, rc.bottom, 0, m_hwnd, NULL);
				CheckDlgButton(m_hwnd, IDC_BOOKMARKS, FALSE);
				DestroyMenu(hMenu);

				if ( res == -1 )
					m_proto->OnMenuHandleBookmarks( 0, 0 );
				else if (res) {
					JABBER_LIST_ITEM *item = (JABBER_LIST_ITEM *)res;
					TCHAR *room = NEWTSTR_ALLOCA(item->jid);
					if (room) {
						TCHAR *server = _tcschr(room, _T('@'));
						if (server) {
							*server++ = 0;

							SendMessage(m_hwnd, WM_COMMAND, MAKEWPARAM(IDC_SERVER, CBN_EDITCHANGE), (LPARAM)GetDlgItem(m_hwnd, IDC_SERVER));

							SetDlgItemText(m_hwnd, IDC_SERVER, server);
							SetDlgItemText(m_hwnd, IDC_ROOM, room);
							SetDlgItemText(m_hwnd, IDC_NICK, item->nick);
							SetDlgItemText(m_hwnd, IDC_PASSWORD, item->password);
			}	}	}	}
			break;

		case IDC_RECENT1:
		case IDC_RECENT2:
		case IDC_RECENT3:
		case IDC_RECENT4:
		case IDC_RECENT5:
			{
				JabberGcRecentInfo info( m_proto, LOWORD( wParam ) - IDC_RECENT1);
				info.fillForm(m_hwnd);
				if (GetAsyncKeyState(VK_CONTROL))
					break;
			}
			// fall through

		case IDOK:
			{
				GetDlgItemText( m_hwnd, IDC_SERVER, text, SIZEOF( text ));
				TCHAR* server = NEWTSTR_ALLOCA( text ), *room;

				m_proto->ComboAddRecentString(m_hwnd, IDC_SERVER, "joinWnd_rcSvr", server);

				GetDlgItemText( m_hwnd, IDC_ROOM, text, SIZEOF( text ));
				room = NEWTSTR_ALLOCA( text );

				GetDlgItemText( m_hwnd, IDC_NICK, text, SIZEOF( text ));
				TCHAR* nick = NEWTSTR_ALLOCA( text );

				GetDlgItemText( m_hwnd, IDC_PASSWORD, text, SIZEOF( text ));
				TCHAR* password = NEWTSTR_ALLOCA( text );
				m_proto->GroupchatJoinRoom( server, room, nick, password );
			}
			// fall through
		case IDCANCEL:
			Close();
			break;
		}
		break;
	case WM_JABBER_CHECK_ONLINE:
		if ( !m_proto->m_bJabberOnline )
			EndDialog( m_hwnd, 0 );
		break;
	}
Exemple #27
0
bool CAttachDlg::OnStartAttach()
{
	bool lbRc = false;
	// Тут нужно получить инфу из списка и дернуть собственно аттач
	wchar_t szItem[128] = {};
	//DWORD nPID = 0, nBits = WIN3264TEST(32,64);
	//AttachProcessType nType = apt_Unknown;
	wchar_t *psz;
	int iSel, iCur;
	DWORD nTID;
	HANDLE hThread = NULL;
	AttachParm *pParm = NULL;
	MArray<AttachParm> Parms;
	//HWND hAttachWnd = NULL;

	ShowWindow(mh_Dlg, SW_HIDE);

	BOOL bAlternativeMode = (IsDlgButtonChecked(mh_Dlg, IDC_ATTACH_ALT) != 0);

	iSel = ListView_GetNextItem(mh_List, -1, LVNI_SELECTED);
	while (iSel >= 0)
	{
		iCur = iSel;
		iSel = ListView_GetNextItem(mh_List, iCur, LVNI_SELECTED);

		AttachParm L = {NULL, 0, WIN3264TEST(32,64), apt_Unknown, bAlternativeMode};

		ListView_GetItemText(mh_List, iCur, alc_PID, szItem, countof(szItem)-1);
		L.nPID = wcstoul(szItem, &psz, 10);
		if (L.nPID)
		{
			psz = wcschr(szItem, L'*');
			if (psz)
				L.nBits = wcstoul(psz+1, &psz, 10);
		}
		ListView_GetItemText(mh_List, iCur, alc_Type, szItem, countof(szItem));
		if (lstrcmp(szItem, szTypeCon) == 0)
			L.nType = apt_Console;
		else if (lstrcmp(szItem, szTypeGui) == 0)
			L.nType = apt_Gui;

		ListView_GetItemText(mh_List, iCur, alc_HWND, szItem, countof(szItem));
		L.hAttachWnd = (szItem[0]==L'0' && szItem[1]==L'x') ? (HWND)wcstoul(szItem+2, &psz, 16) : NULL;

		if (!L.nPID || !L.nBits || !L.nType || !L.hAttachWnd)
		{
			MBoxAssert(L.nPID && L.nBits && L.nType && L.hAttachWnd);
			goto wrap;
		}

		Parms.push_back(L);
	}

	if (Parms.empty())
	{
		goto wrap;
	}
	else
	{
		AttachParm N = {NULL};
		Parms.push_back(N);
	}

	//// Чтобы клик от мышки в консоль не провалился
	//WARNING("Клик от мышки в консоль проваливается");
	//gpConEmu->mouse.nSkipEvents[0] = WM_LBUTTONUP;
	//gpConEmu->mouse.nSkipEvents[1] = 0;
	//gpConEmu->mouse.nReplaceDblClk = 0;

	// Все, диалог закрываем, чтобы не мешался
	Close();

	// Работу делаем в фоновом потоке, чтобы не блокировать главный
	// (к окну ConEmu должна подцепиться новая вкладка)
	pParm = Parms.detach();
	if (!pParm)
	{
		_wsprintf(szItem, SKIPLEN(countof(szItem)) L"ConEmu Attach, PID=%u, TID=%u", GetCurrentProcessId(), GetCurrentThreadId());
		DisplayLastError(L"Parms.detach() failed", -1, 0, szItem);
		goto wrap;
	}
	else
	{
		hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)StartAttachThread, pParm, 0, &nTID);
		if (!hThread)
		{
			DWORD dwErr = GetLastError();
			_wsprintf(szItem, SKIPLEN(countof(szItem)) L"ConEmu Attach, PID=%u, TID=%u", GetCurrentProcessId(), GetCurrentThreadId());
			DisplayLastError(L"Can't start attach thread", dwErr, 0, szItem);
		}
		else
			lbRc = true;
	}
wrap:
	// We don't need this handle
	if (hThread)
		CloseHandle(hThread);

	return lbRc;
}
Exemple #28
0
static void test_SetupCopyOEMInf(void)
{
    CHAR toolong[MAX_PATH * 2];
    CHAR path[MAX_PATH], dest[MAX_PATH];
    CHAR tmpfile[MAX_PATH], dest_save[MAX_PATH];
    LPSTR inf;
    DWORD size;
    BOOL res;

    /* try NULL SourceInfFileName */
    SetLastError(0xdeadbeef);
    res = pSetupCopyOEMInfA(NULL, NULL, 0, SP_COPY_NOOVERWRITE, NULL, 0, NULL, NULL);
    ok(res == FALSE, "Expected FALSE, got %d\n", res);
    ok(GetLastError() == ERROR_INVALID_PARAMETER,
       "Expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());

    /* try empty SourceInfFileName */
    SetLastError(0xdeadbeef);
    res = pSetupCopyOEMInfA("", NULL, 0, SP_COPY_NOOVERWRITE, NULL, 0, NULL, NULL);
    ok(res == FALSE, "Expected FALSE, got %d\n", res);
    ok(GetLastError() == ERROR_FILE_NOT_FOUND,
       "Expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError());

    /* try a relative nonexistent SourceInfFileName */
    SetLastError(0xdeadbeef);
    res = pSetupCopyOEMInfA("nonexistent", NULL, 0, SP_COPY_NOOVERWRITE, NULL, 0, NULL, NULL);
    ok(res == FALSE, "Expected FALSE, got %d\n", res);
    ok(GetLastError() == ERROR_FILE_NOT_FOUND,
       "Expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError());

    /* try an absolute nonexistent SourceInfFileName */
    lstrcpy(path, CURR_DIR);
    lstrcat(path, "\\nonexistent");
    SetLastError(0xdeadbeef);
    res = pSetupCopyOEMInfA(path, NULL, 0, SP_COPY_NOOVERWRITE, NULL, 0, NULL, NULL);
    ok(res == FALSE, "Expected FALSE, got %d\n", res);
    ok(GetLastError() == ERROR_FILE_NOT_FOUND,
       "Expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError());

    /* try a long SourceInfFileName */
    memset(toolong, 'a', MAX_PATH * 2);
    toolong[MAX_PATH * 2 - 1] = '\0';
    SetLastError(0xdeadbeef);
    res = pSetupCopyOEMInfA(toolong, NULL, 0, SP_COPY_NOOVERWRITE, NULL, 0, NULL, NULL);
    ok(res == FALSE, "Expected FALSE, got %d\n", res);
    ok(GetLastError() == ERROR_FILE_NOT_FOUND,
       "Expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError());

    get_temp_filename(tmpfile);
    create_inf_file(tmpfile);

    /* try a relative SourceInfFileName */
    SetLastError(0xdeadbeef);
    res = pSetupCopyOEMInfA(tmpfile, NULL, 0, SP_COPY_NOOVERWRITE, NULL, 0, NULL, NULL);
    ok(res == FALSE, "Expected FALSE, got %d\n", res);
    ok(GetLastError() == ERROR_FILE_NOT_FOUND,
       "Expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError());
    ok(file_exists(tmpfile), "Expected tmpfile to exist\n");

    /* try SP_COPY_REPLACEONLY, dest does not exist */
    SetLastError(0xdeadbeef);
    res = pSetupCopyOEMInfA(path, NULL, SPOST_NONE, SP_COPY_REPLACEONLY, NULL, 0, NULL, NULL);
    ok(res == FALSE, "Expected FALSE, got %d\n", res);
    ok(GetLastError() == ERROR_FILE_NOT_FOUND,
       "Expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError());
    ok(file_exists(tmpfile), "Expected source inf to exist\n");

    /* try an absolute SourceInfFileName, without DestinationInfFileName */
    lstrcpy(path, CURR_DIR);
    lstrcat(path, "\\");
    lstrcat(path, tmpfile);
    SetLastError(0xdeadbeef);
    res = pSetupCopyOEMInfA(path, NULL, SPOST_NONE, 0, NULL, 0, NULL, NULL);
    ok(res == TRUE, "Expected TRUE, got %d\n", res);
    ok(GetLastError() == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", GetLastError());
    ok(file_exists(path), "Expected source inf to exist\n");

    /* try SP_COPY_REPLACEONLY, dest exists */
    SetLastError(0xdeadbeef);
    res = pSetupCopyOEMInfA(path, NULL, SPOST_NONE, SP_COPY_REPLACEONLY, NULL, 0, NULL, NULL);
    ok(res == TRUE, "Expected TRUE, got %d\n", res);
    ok(GetLastError() == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", GetLastError());
    ok(file_exists(path), "Expected source inf to exist\n");

    /* try SP_COPY_NOOVERWRITE */
    SetLastError(0xdeadbeef);
    res = pSetupCopyOEMInfA(path, NULL, SPOST_NONE, SP_COPY_NOOVERWRITE, NULL, 0, NULL, NULL);
    ok(res == FALSE, "Expected FALSE, got %d\n", res);
    ok(GetLastError() == ERROR_FILE_EXISTS,
       "Expected ERROR_FILE_EXISTS, got %d\n", GetLastError());

    /* get the DestinationInfFileName */
    SetLastError(0xdeadbeef);
    res = pSetupCopyOEMInfA(path, NULL, SPOST_NONE, 0, dest, MAX_PATH, NULL, NULL);
    ok(res == TRUE, "Expected TRUE, got %d\n", res);
    ok(GetLastError() == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", GetLastError());
    ok(lstrlen(dest) != 0, "Expected a non-zero length string\n");
    ok(file_exists(dest), "Expected destination inf to exist\n");
    ok(check_format(dest, NULL), "Expected %%windir%%\\inf\\OEMx.inf, got %s\n", dest);
    ok(file_exists(path), "Expected source inf to exist\n");

    lstrcpy(dest_save, dest);
    DeleteFile(dest_save);

    /* get the DestinationInfFileName, DestinationInfFileNameSize is too small
     *   - inf is still copied
     */
    lstrcpy(dest, "aaa");
    size = 0;
    SetLastError(0xdeadbeef);
    res = pSetupCopyOEMInfA(path, NULL, SPOST_NONE, 0, dest, 5, &size, NULL);
    ok(res == FALSE, "Expected FALSE, got %d\n", res);
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
    ok(file_exists(path), "Expected source inf to exist\n");
    ok(file_exists(dest_save), "Expected dest inf to exist\n");
    ok(!lstrcmp(dest, "aaa"), "Expected dest to be unchanged\n");
    ok(size == lstrlen(dest_save) + 1, "Expected size to be lstrlen(dest_save) + 1\n");

    /* get the DestinationInfFileName and DestinationInfFileNameSize */
    SetLastError(0xdeadbeef);
    res = pSetupCopyOEMInfA(path, NULL, SPOST_NONE, 0, dest, MAX_PATH, &size, NULL);
    ok(res == TRUE, "Expected TRUE, got %d\n", res);
    ok(GetLastError() == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", GetLastError());
    ok(lstrlen(dest) + 1 == size, "Expected sizes to match, got (%d, %d)\n", lstrlen(dest), size);
    ok(file_exists(dest), "Expected destination inf to exist\n");
    ok(check_format(dest, NULL), "Expected %%windir%%\\inf\\OEMx.inf, got %s\n", dest);
    ok(file_exists(path), "Expected source inf to exist\n");
    ok(size == lstrlen(dest_save) + 1, "Expected size to be lstrlen(dest_save) + 1\n");

    test_original_file_name(strrchr(path, '\\') + 1, dest);

    /* get the DestinationInfFileName, DestinationInfFileNameSize, and DestinationInfFileNameComponent */
    SetLastError(0xdeadbeef);
    res = pSetupCopyOEMInfA(path, NULL, SPOST_NONE, 0, dest, MAX_PATH, &size, &inf);
    ok(res == TRUE, "Expected TRUE, got %d\n", res);
    ok(GetLastError() == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", GetLastError());
    ok(lstrlen(dest) + 1 == size, "Expected sizes to match, got (%d, %d)\n", lstrlen(dest), size);
    ok(file_exists(dest), "Expected destination inf to exist\n");
    ok(check_format(dest, inf), "Expected %%windir%%\\inf\\OEMx.inf, got %s\n", dest);
    ok(file_exists(path), "Expected source inf to exist\n");
    ok(size == lstrlen(dest_save) + 1, "Expected size to be lstrlen(dest_save) + 1\n");

    /* try SP_COPY_DELETESOURCE */
    SetLastError(0xdeadbeef);
    res = pSetupCopyOEMInfA(path, NULL, SPOST_NONE, SP_COPY_DELETESOURCE, NULL, 0, NULL, NULL);
    ok(res == TRUE, "Expected TRUE, got %d\n", res);
    ok(GetLastError() == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", GetLastError());
    ok(!file_exists(path), "Expected source inf to not exist\n");
}
Exemple #29
0
static int sttTreeList_SortItems_Cmp0(const void *p1, const void *p2) { return  lstrcmp((*(HTREELISTITEM *)p1)->text[0], (*(HTREELISTITEM *)p2)->text[0]); }
Exemple #30
0
void PreInitNProtect()
{
	switch( ::GetLanguage() )
	{
	case LANG_KOR:
		g_szNPGKey = "Flyff";
		break;
#ifdef __NO_SUB_LANG
	case LANG_USA:
		g_szNPGKey = "FlyffENG";
		break;
#else // __NO_SUB_LANG
	case LANG_USA:
		if( ::GetSubLanguage() == LANG_SUB_USA )
		{
			g_szNPGKey = "FlyffENG";
		}
		else if( ::GetSubLanguage() == LANG_SUB_IND )
		{
			g_szNPGKey = "FlyffIND";
		}
		else
		{
			if( lstrcmp( g_Neuz.m_lpCertifierAddr, "125.5.127.16" ) == 0 )	// 테스트
				g_szNPGKey	= "FlyffPHTest";
			else
				g_szNPGKey = "FlyffPH";
		}
		break;
#endif // __NO_SUB_LANG
	case LANG_JAP:
		g_szNPGKey = "FlyffJP";		// 아직 사용하지 않고 있다.
		break;
	case LANG_CHI:
	case LANG_TWN:
		{
			if( lstrcmp( g_Neuz.m_lpCertifierAddr, "210.242.174.100" ) == 0 )		// 테스트
				g_szNPGKey = "FlyffTWTest";
			else	// 정식
				g_szNPGKey = "FlyffTW";
		}
		break;
	case LANG_HK:
		{
			if( lstrcmp( g_Neuz.m_lpCertifierAddr, "203.174.49.231" ) == 0 )		// 정식 서버
				g_szNPGKey = "FlyffHK";
			else	// 테스트 서버
				g_szNPGKey = "FlyffHKTest";
		}
		break;
	case LANG_THA:
		g_szNPGKey = "FlyffTH";
		break;
	case LANG_GER:
		{
			if( lstrcmp( g_Neuz.m_lpCertifierAddr, "195.59.138.10" ) == 0 )		// 정식 서버
				g_szNPGKey = "FlyffEU";
			else	// 테스트 서버
				g_szNPGKey = "FlyffEUTest";
		}
		break;
	case LANG_SPA:
		{
		//	mulcom	BEGIN100419 스페니시 버전 NPGKey 설정.
//			g_szNPGKey = "FlyffSP";
			g_szNPGKey = "FlyffES";
		//	mulcom	END100419	스페니시 버전 NPGKey 설정.
		}
		break;
	case LANG_POR:
		{
			if( lstrcmp( g_Neuz.m_lpCertifierAddr, "204.2.134.191" ) == 0 )		// 정식 서버
				g_szNPGKey = "FlyffBR";
			else	// 테스트 서버
				g_szNPGKey = "FlyffBRTest";
		}
		break;
	case LANG_FRE:
		{
			if( lstrcmp( g_Neuz.m_lpCertifierAddr, "195.59.138.5" ) == 0 )		// 정식 서버
				g_szNPGKey = "FlyffEU";
			else	// 테스트 서버
				g_szNPGKey = "FlyffEUTest";
		}
		break;
	case LANG_VTN:
		g_szNPGKey = "FlyffVT";
		break;
	case LANG_RUS:
		g_szNPGKey = "FlyffRUS";
		break;
	}
}