Пример #1
0
/***********************************************************************
 *      AdvInstallFileW (ADVPACK.@)
 *
 * Copies a file from the source to a destination.
 *
 * PARAMS
 *   hwnd           [I] Handle to the window used for messages.
 *   lpszSourceDir  [I] Source directory.
 *   lpszSourceFile [I] Source filename.
 *   lpszDestDir    [I] Destination directory.
 *   lpszDestFile   [I] Optional destination filename.
 *   dwFlags        [I] See advpub.h.
 *   dwReserved     [I] Reserved.  Must be 0.
 *
 * RETURNS
 *   Success: S_OK.
 *   Failure: E_FAIL.
 *
 * NOTES
 *   If lpszDestFile is NULL, the destination filename is the same as
 *   lpszSourceFIle.
 */
HRESULT WINAPI AdvInstallFileW(HWND hwnd, LPCWSTR lpszSourceDir, LPCWSTR lpszSourceFile,
                               LPCWSTR lpszDestDir, LPCWSTR lpszDestFile,
                               DWORD dwFlags, DWORD dwReserved)
{
    PSP_FILE_CALLBACK_W pFileCallback;
    LPWSTR szDestFilename;
    LPCWSTR szPath;
    WCHAR szRootPath[ROOT_LENGTH];
    DWORD dwLen, dwLastError;
    HSPFILEQ fileQueue;
    PVOID pContext;

    TRACE("(%p, %s, %s, %s, %s, %d, %d)\n", hwnd, debugstr_w(lpszSourceDir),
          debugstr_w(lpszSourceFile), debugstr_w(lpszDestDir),
          debugstr_w(lpszDestFile), dwFlags, dwReserved);

    if (!lpszSourceDir || !lpszSourceFile || !lpszDestDir)
        return E_INVALIDARG;
        
    fileQueue = SetupOpenFileQueue();
    if (fileQueue == INVALID_HANDLE_VALUE)
        return HRESULT_FROM_WIN32(GetLastError());

    pContext = NULL;
    dwLastError = ERROR_SUCCESS;

    lstrcpynW(szRootPath, lpszSourceDir, ROOT_LENGTH);
    szPath = lpszSourceDir + ROOT_LENGTH;

    /* use lpszSourceFile as destination filename if lpszDestFile is NULL */
    if (lpszDestFile)
    {
        dwLen = lstrlenW(lpszDestFile);
        szDestFilename = HeapAlloc(GetProcessHeap(), 0, (dwLen+1) * sizeof(WCHAR));
        lstrcpyW(szDestFilename, lpszDestFile);
    }
    else
    {
        dwLen = lstrlenW(lpszSourceFile);
        szDestFilename = HeapAlloc(GetProcessHeap(), 0, (dwLen+1) * sizeof(WCHAR));
        lstrcpyW(szDestFilename, lpszSourceFile);
    }

    /* add the file copy operation to the setup queue */
    if (!SetupQueueCopyW(fileQueue, szRootPath, szPath, lpszSourceFile, NULL,
                         NULL, lpszDestDir, szDestFilename, dwFlags))
    {
        dwLastError = GetLastError();
        goto done;
    }

    pContext = SetupInitDefaultQueueCallbackEx(hwnd, INVALID_HANDLE_VALUE,
                                               0, 0, NULL);
    if (!pContext)
    {
        dwLastError = GetLastError();
        goto done;
    }

    /* don't output anything for AIF_QUIET */
    if (dwFlags & AIF_QUIET)
        pFileCallback = pQuietQueueCallback;
    else
        pFileCallback = pQueueCallback;

    /* perform the file copy */
    if (!SetupCommitFileQueueW(hwnd, fileQueue, pFileCallback, pContext))
    {
        dwLastError = GetLastError();
        goto done;
    }

done:
    SetupTermDefaultQueueCallback(pContext);
    SetupCloseFileQueue(fileQueue);
    
    HeapFree(GetProcessHeap(), 0, szDestFilename);
    
    return HRESULT_FROM_WIN32(dwLastError);
}
Пример #2
0
static void SuggestKeys(HKEY hRootKey, LPCWSTR pszKeyPath, LPWSTR pszSuggestions,
                        size_t iSuggestionsLength)
{
    WCHAR szBuffer[256];
    WCHAR szLastFound[256];
    size_t i;
    HKEY hOtherKey, hSubKey;
    BOOL bFound;

    memset(pszSuggestions, 0, iSuggestionsLength * sizeof(*pszSuggestions));
    iSuggestionsLength--;

    /* Are we a root key in HKEY_CLASSES_ROOT? */
    if ((hRootKey == HKEY_CLASSES_ROOT) && pszKeyPath[0] && !wcschr(pszKeyPath, L'\\'))
    {
        do
        {
            bFound = FALSE;

            /* Check default key */
            if (QueryStringValue(hRootKey, pszKeyPath, NULL,
                                 szBuffer, COUNT_OF(szBuffer)) == ERROR_SUCCESS)
            {
                /* Sanity check this key; it cannot be empty, nor can it be a
                 * loop back */
                if ((szBuffer[0] != L'\0') && _wcsicmp(szBuffer, pszKeyPath))
                {
                    if (RegOpenKeyW(hRootKey, szBuffer, &hOtherKey) == ERROR_SUCCESS)
                    {
                        lstrcpynW(pszSuggestions, L"HKCR\\", (int) iSuggestionsLength);
                        i = wcslen(pszSuggestions);
                        pszSuggestions += i;
                        iSuggestionsLength -= i;

                        lstrcpynW(pszSuggestions, szBuffer, (int) iSuggestionsLength);
                        i = MIN(wcslen(pszSuggestions) + 1, iSuggestionsLength);
                        pszSuggestions += i;
                        iSuggestionsLength -= i;
                        RegCloseKey(hOtherKey);

                        bFound = TRUE;
                        wcscpy(szLastFound, szBuffer);
                        pszKeyPath = szLastFound;
                    }
                }
            }
        }
        while(bFound && (iSuggestionsLength > 0));

        /* Check CLSID key */
        if (RegOpenKeyW(hRootKey, pszKeyPath, &hSubKey) == ERROR_SUCCESS)
        {
            if (QueryStringValue(hSubKey, L"CLSID", NULL, szBuffer,
                                 COUNT_OF(szBuffer)) == ERROR_SUCCESS)
            {
                lstrcpynW(pszSuggestions, L"HKCR\\CLSID\\", (int)iSuggestionsLength);
                i = wcslen(pszSuggestions);
                pszSuggestions += i;
                iSuggestionsLength -= i;

                lstrcpynW(pszSuggestions, szBuffer, (int)iSuggestionsLength);
                i = MIN(wcslen(pszSuggestions) + 1, iSuggestionsLength);
                pszSuggestions += i;
                iSuggestionsLength -= i;
            }
            RegCloseKey(hSubKey);
        }
    }
}
Пример #3
0
LONG FD31_WMInitDialog(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
  int i, n;
  WCHAR tmpstr[BUFFILE];
  LPWSTR pstr, old_pstr;
  LPOPENFILENAMEW ofn;
  PFD31_DATA lfs = (PFD31_DATA) lParam;

  if (!lfs) return FALSE;
  SetPropA(hWnd, FD31_OFN_PROP, (HANDLE)lfs);
  lfs->hwnd = hWnd;
  ofn = lfs->ofnW;

  TRACE("flags=%lx initialdir=%s\n", ofn->Flags, debugstr_w(ofn->lpstrInitialDir));

  SetWindowTextW( hWnd, ofn->lpstrTitle );
  /* read custom filter information */
  if (ofn->lpstrCustomFilter)
    {
      pstr = ofn->lpstrCustomFilter;
      n = 0;
      TRACE("lpstrCustomFilter = %p\n", pstr);
      while(*pstr)
	{
	  old_pstr = pstr;
          i = SendDlgItemMessageW(hWnd, cmb1, CB_ADDSTRING, 0,
                                   (LPARAM)(ofn->lpstrCustomFilter) + n );
          n += lstrlenW(pstr) + 1;
	  pstr += lstrlenW(pstr) + 1;
	  TRACE("add str=%s associated to %s\n",
                debugstr_w(old_pstr), debugstr_w(pstr));
          SendDlgItemMessageW(hWnd, cmb1, CB_SETITEMDATA, i, (LPARAM)pstr);
          n += lstrlenW(pstr) + 1;
	  pstr += lstrlenW(pstr) + 1;
	}
    }
  /* read filter information */
  if (ofn->lpstrFilter) {
	pstr = (LPWSTR) ofn->lpstrFilter;
	n = 0;
	while(*pstr) {
	  old_pstr = pstr;
	  i = SendDlgItemMessageW(hWnd, cmb1, CB_ADDSTRING, 0,
				       (LPARAM)(ofn->lpstrFilter + n) );
	  n += lstrlenW(pstr) + 1;
	  pstr += lstrlenW(pstr) + 1;
	  TRACE("add str=%s associated to %s\n",
                debugstr_w(old_pstr), debugstr_w(pstr));
	  SendDlgItemMessageW(hWnd, cmb1, CB_SETITEMDATA, i, (LPARAM)pstr);
	  n += lstrlenW(pstr) + 1;
	  pstr += lstrlenW(pstr) + 1;
	}
  }
  /* set default filter */
  if (ofn->nFilterIndex == 0 && ofn->lpstrCustomFilter == NULL)
  	ofn->nFilterIndex = 1;
  SendDlgItemMessageW(hWnd, cmb1, CB_SETCURSEL, ofn->nFilterIndex - 1, 0);
  lstrcpynW(tmpstr, FD31_GetFileType(ofn->lpstrCustomFilter,
	     (LPWSTR)ofn->lpstrFilter, ofn->nFilterIndex - 1),BUFFILE);
  TRACE("nFilterIndex = %ld, SetText of edt1 to %s\n",
  			ofn->nFilterIndex, debugstr_w(tmpstr));
  SetDlgItemTextW( hWnd, edt1, tmpstr );
  /* get drive list */
  *tmpstr = 0;
  DlgDirListComboBoxW(hWnd, tmpstr, cmb2, 0, DDL_DRIVES | DDL_EXCLUSIVE);
  /* read initial directory */
  /* FIXME: Note that this is now very version-specific (See MSDN description of
   * the OPENFILENAME structure).  For example under 2000/XP any path in the
   * lpstrFile overrides the lpstrInitialDir, but not under 95/98/ME
   */
  if (ofn->lpstrInitialDir != NULL)
    {
      int len;
      lstrcpynW(tmpstr, ofn->lpstrInitialDir, 511);
      len = lstrlenW(tmpstr);
      if (len > 0 && tmpstr[len-1] != '\\'  && tmpstr[len-1] != ':') {
        tmpstr[len]='\\';
        tmpstr[len+1]='\0';
      }
    }
  else
    *tmpstr = 0;
  if (!FD31_ScanDir(hWnd, tmpstr)) {
    *tmpstr = 0;
    if (!FD31_ScanDir(hWnd, tmpstr))
      WARN("Couldn't read initial directory %s!\n", debugstr_w(tmpstr));
  }
  /* select current drive in combo 2, omit missing drives */
  {
      char dir[MAX_PATH];
      char str[4] = "a:\\";
      GetCurrentDirectoryA( sizeof(dir), dir );
      for(i = 0, n = -1; i < 26; i++)
      {
          str[0] = 'a' + i;
          if (GetDriveTypeA(str) > DRIVE_NO_ROOT_DIR) n++;
          if (toupper(str[0]) == toupper(dir[0])) break;
      }
  }
  SendDlgItemMessageW(hWnd, cmb2, CB_SETCURSEL, n, 0);
  if (!(ofn->Flags & OFN_SHOWHELP))
    ShowWindow(GetDlgItem(hWnd, pshHelp), SW_HIDE);
  if (ofn->Flags & OFN_HIDEREADONLY)
    ShowWindow(GetDlgItem(hWnd, chx1), SW_HIDE);
  if (lfs->hook)
      return (BOOL) FD31_CallWindowProc(lfs, WM_INITDIALOG, wParam, lfs->lParam);
  return TRUE;
}
Пример #4
0
/***********************************************************************
 *			SymLoadModuleExW (DBGHELP.@)
 */
DWORD64 WINAPI  SymLoadModuleExW(HANDLE hProcess, HANDLE hFile, PCWSTR wImageName,
                                 PCWSTR wModuleName, DWORD64 BaseOfDll, DWORD SizeOfDll,
                                 PMODLOAD_DATA Data, DWORD Flags)
{
    struct process*     pcs;
    struct module*	module = NULL;

    TRACE("(%p %p %s %s %s %08x %p %08x)\n",
          hProcess, hFile, debugstr_w(wImageName), debugstr_w(wModuleName),
          wine_dbgstr_longlong(BaseOfDll), SizeOfDll, Data, Flags);

    if (Data)
        FIXME("Unsupported load data parameter %p for %s\n",
              Data, debugstr_w(wImageName));
    if (!validate_addr64(BaseOfDll)) return FALSE;

    if (!(pcs = process_find_by_handle(hProcess))) return FALSE;

    if (Flags & SLMFLAG_VIRTUAL)
    {
        if (!wImageName) return FALSE;
        module = module_new(pcs, wImageName, module_get_type_by_name(wImageName),
                            TRUE, BaseOfDll, SizeOfDll, 0, 0);
        if (!module) return FALSE;
        if (wModuleName) module_set_module(module, wModuleName);
        module->module.SymType = SymVirtual;

        return TRUE;
    }
    if (Flags & ~(SLMFLAG_VIRTUAL))
        FIXME("Unsupported Flags %08x for %s\n", Flags, debugstr_w(wImageName));

    refresh_module_list(pcs);

    /* this is a Wine extension to the API just to redo the synchronisation */
    if (!wImageName && !hFile) return 0;

    /* check if the module is already loaded, or if it's a builtin PE module with
     * an containing ELF module
     */
    if (wImageName)
    {
        module = module_is_already_loaded(pcs, wImageName);
        if (!module && module_is_container_loaded(pcs, wImageName, BaseOfDll))
        {
            /* force the loading of DLL as builtin */
            module = pe_load_builtin_module(pcs, wImageName, BaseOfDll, SizeOfDll);
        }
    }
    if (!module)
    {
        /* otherwise, try a regular PE module */
        if (!(module = pe_load_native_module(pcs, wImageName, hFile, BaseOfDll, SizeOfDll)) &&
            wImageName)
        {
            /* and finally an ELF or Mach-O module */
            switch (module_get_type_by_name(wImageName))
            {
                case DMT_ELF:
                    module = elf_load_module(pcs, wImageName, BaseOfDll);
                    break;
                case DMT_MACHO:
                    module = macho_load_module(pcs, wImageName, BaseOfDll);
                    break;
                default:
                    /* Ignored */
                    break;
            }
        }
    }
    if (!module)
    {
        WARN("Couldn't locate %s\n", debugstr_w(wImageName));
        return 0;
    }
    module->module.NumSyms = module->ht_symbols.num_elts;
    /* by default module_new fills module.ModuleName from a derivation
     * of LoadedImageName. Overwrite it, if we have better information
     */
    if (wModuleName)
        module_set_module(module, wModuleName);
    if (wImageName)
        lstrcpynW(module->module.ImageName, wImageName,
              sizeof(module->module.ImageName) / sizeof(WCHAR));

    return module->module.BaseOfImage;
}
Пример #5
0
void SetConsoleFontSizeTo(HWND inConWnd, int inSizeY, int inSizeX, const wchar_t *asFontName, WORD anTextColors /*= 0*/, WORD anPopupColors /*= 0*/)
{
	_ASSERTE(_WIN32_WINNT_VISTA==0x600);
	OSVERSIONINFOEXW osvi = {sizeof(osvi), HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA)};
	DWORDLONG const dwlConditionMask = VerSetConditionMask(VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL);
	if (VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION, dwlConditionMask))
	{
		// We have Vista
		apiSetConsoleFontSize(GetStdHandle(STD_OUTPUT_HANDLE), inSizeY, inSizeX, asFontName);
	}
	else 
	{
		// We have older NT (Win2k, WinXP)
		// So... using undocumented hack

		const COLORREF DefaultColors[16] =
		{
			0x00000000, 0x00800000, 0x00008000, 0x00808000,
			0x00000080, 0x00800080, 0x00008080, 0x00c0c0c0,
			0x00808080,	0x00ff0000, 0x0000ff00, 0x00ffff00,
			0x000000ff, 0x00ff00ff,	0x0000ffff, 0x00ffffff
		};

		if (!gpConsoleInfoStr)
		{
			gpConsoleInfoStr = (CONSOLE_INFO*)LocalAlloc(LPTR, sizeof(CONSOLE_INFO));

			if (!gpConsoleInfoStr)
			{
				_ASSERTE(gpConsoleInfoStr!=NULL);
				return; // memory allocation failed
			}

			gpConsoleInfoStr->Length = sizeof(CONSOLE_INFO);
		}

		if (!anTextColors)
		{
			CONSOLE_SCREEN_BUFFER_INFO csbi = {};
			GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
			anTextColors = csbi.wAttributes ? csbi.wAttributes : MAKEWORD(0x7, 0x0);
		}
		if (!anPopupColors)
		{
			anPopupColors = MAKEWORD(0x5, 0xf);
		}

		// get current size/position settings rather than using defaults..
		GetConsoleSizeInfo(gpConsoleInfoStr);
		// set these to zero to keep current settings
		gpConsoleInfoStr->FontSize.X				= inSizeX;
		gpConsoleInfoStr->FontSize.Y				= inSizeY;
		gpConsoleInfoStr->FontFamily				= 0;//0x30;//FF_MODERN|FIXED_PITCH;//0x30;
		gpConsoleInfoStr->FontWeight				= 0;//0x400;
		lstrcpynW(gpConsoleInfoStr->FaceName, asFontName ? asFontName : L"Lucida Console", countof(gpConsoleInfoStr->FaceName)); //-V303
		gpConsoleInfoStr->CursorSize				= 25;
		gpConsoleInfoStr->FullScreen				= FALSE;
		gpConsoleInfoStr->QuickEdit					= FALSE;
		//gpConsoleInfoStr->AutoPosition			= 0x10000;
		gpConsoleInfoStr->AutoPosition				= FALSE;
		RECT rcCon; GetWindowRect(inConWnd, &rcCon);
		gpConsoleInfoStr->WindowPosX = rcCon.left;
		gpConsoleInfoStr->WindowPosY = rcCon.top;
		gpConsoleInfoStr->InsertMode				= TRUE;
		gpConsoleInfoStr->ScreenColors				= anTextColors; //MAKEWORD(0x7, 0x0);
		gpConsoleInfoStr->PopupColors				= anPopupColors; //MAKEWORD(0x5, 0xf);
		gpConsoleInfoStr->HistoryNoDup				= FALSE;
		gpConsoleInfoStr->HistoryBufferSize			= 50;
		gpConsoleInfoStr->NumberOfHistoryBuffers	= 32; //-V112

		// Issue 700: Default history buffers count too small.
		HKEY hkConsole = NULL;
		LONG lRegRc;
		if (0 == (lRegRc = RegCreateKeyEx(HKEY_CURRENT_USER, L"Console\\ConEmu", 0, NULL, 0, KEY_READ, NULL, &hkConsole, NULL)))
		{
			DWORD nSize = sizeof(DWORD), nValue, nType;
			struct {
				LPCWSTR pszName;
				DWORD nMin, nMax;
				ULONG *pnVal;
			} BufferValues[] = {
				{L"HistoryBufferSize", 16, 999, &gpConsoleInfoStr->HistoryBufferSize},
				{L"NumberOfHistoryBuffers", 16, 999, &gpConsoleInfoStr->NumberOfHistoryBuffers}
			};
			for (size_t i = 0; i < countof(BufferValues); ++i)
			{
				lRegRc = RegQueryValueEx(hkConsole, BufferValues[i].pszName, NULL, &nType, (LPBYTE)&nValue, &nSize);
				if ((lRegRc == 0) && (nType == REG_DWORD) && (nSize == sizeof(DWORD)))
				{
					if (nValue < BufferValues[i].nMin)
						nValue = BufferValues[i].nMin;
					else if (nValue > BufferValues[i].nMax)
						nValue = BufferValues[i].nMax;

					if (nValue != *BufferValues[i].pnVal)
						*BufferValues[i].pnVal = nValue;
				}
			}
		}

		// color table
		for(size_t i = 0; i < 16; i++)
			gpConsoleInfoStr->ColorTable[i] = DefaultColors[i];

		gpConsoleInfoStr->CodePage					= GetConsoleOutputCP();//0;//0x352;
		gpConsoleInfoStr->Hwnd						= inConWnd;
		gpConsoleInfoStr->ConsoleTitle[0] = 0;

		// Send data to console window
		SetConsoleInfo(inConWnd, gpConsoleInfoStr);
	}
}
Пример #6
0
/*******************************************************************
 * GAMEUX_loadGameStatisticsFromFile
 * Helper function, loads game statistics from file and stores them
 * in the structure.
 *
 * Parameters:
 *  data                [I/O]   structure containing file name to
 *                              load and data fields to store data in
 */
static HRESULT GAMEUX_loadStatisticsFromFile(struct GAMEUX_STATS *data)
{
    static const WCHAR sStatistics[] = {'S','t','a','t','i','s','t','i','c','s',0};
    static const WCHAR sCategory[] = {'C','a','t','e','g','o','r','y',0};
    static const WCHAR sIndex[] = {'I','n','d','e','x',0};
    static const WCHAR sStatistic[] = {'S','t','a','t','i','s','t','i','c',0};
    static const WCHAR sName[] = {'N','a','m','e',0};
    static const WCHAR sValue[] = {'V','a','l','u','e',0};

    HRESULT hr = S_OK;
    IXMLDOMDocument *document = NULL;
    IXMLDOMElement *root = NULL, *categoryElement, *statisticElement;
    IXMLDOMNode *categoryNode, *statisticNode;
    IXMLDOMNodeList *rootChildren = NULL, *categoryChildren;
    VARIANT vStatsFilePath, vValue;
    BSTR bstrStatistics = NULL, bstrCategory = NULL, bstrIndex = NULL,
        bstrStatistic = NULL, bstrName = NULL, bstrValue = NULL;
    VARIANT_BOOL isSuccessful =  VARIANT_FALSE;
    int i, j;

    TRACE("(%p)\n", data);

    V_VT(&vStatsFilePath) = VT_BSTR;
    V_BSTR(&vStatsFilePath) = SysAllocString(data->sStatsFile);
    if(!V_BSTR(&vStatsFilePath))
        hr = E_OUTOFMEMORY;

    if(SUCCEEDED(hr))
        hr = CoCreateInstance(&CLSID_DOMDocument30, NULL, CLSCTX_INPROC_SERVER, &IID_IXMLDOMDocument, (void**)&document);

    if(SUCCEEDED(hr))
    {
        bstrStatistics = SysAllocString(sStatistics);
        if(!bstrStatistics)
            hr = E_OUTOFMEMORY;
    }

    if(SUCCEEDED(hr))
    {
        bstrCategory = SysAllocString(sCategory);
        if(!bstrCategory)
            hr = E_OUTOFMEMORY;
    }

    if(SUCCEEDED(hr))
    {
        bstrIndex = SysAllocString(sIndex);
        if(!bstrIndex)
            hr = E_OUTOFMEMORY;
    }

    if(SUCCEEDED(hr))
    {
        bstrStatistic = SysAllocString(sStatistic);
        if(!bstrStatistic)
            hr = E_OUTOFMEMORY;
    }

    if(SUCCEEDED(hr))
    {
        bstrName = SysAllocString(sName);
        if(!bstrName)
            hr = E_OUTOFMEMORY;
    }

    if(SUCCEEDED(hr))
    {
        bstrValue = SysAllocString(sValue);
        if(!bstrValue)
            hr = E_OUTOFMEMORY;
    }

    if(SUCCEEDED(hr))
        hr = IXMLDOMDocument_load(document, vStatsFilePath, &isSuccessful);

    if(hr == S_OK && isSuccessful != VARIANT_TRUE)
        hr = S_FALSE;

    if( hr == S_OK )
        hr = IXMLDOMDocument_get_documentElement(document, &root);

    if(hr == S_OK)
        hr = IXMLDOMElement_get_childNodes(root, &rootChildren);

    if(hr == S_OK)
    {
        hr = S_OK;
        while(hr == S_OK)
        {
            hr = IXMLDOMNodeList_nextNode(rootChildren, &categoryNode);

            if(hr == S_OK)
            {
                hr = IXMLDOMNode_QueryInterface(categoryNode, &IID_IXMLDOMElement, (LPVOID*)&categoryElement);

                if(SUCCEEDED(hr))
                {
                    hr = IXMLDOMElement_getAttribute(categoryElement, bstrIndex, &vValue);
                    if( hr == S_OK && V_VT(&vValue) != VT_BSTR)
                        hr = E_FAIL;

                    if(SUCCEEDED(hr))
                    {
                        i = StrToIntW(V_BSTR(&vValue));
                        hr = IXMLDOMElement_getAttribute(categoryElement, bstrName, &vValue);
                        if( hr == S_OK && V_VT(&vValue) != VT_BSTR)
                            hr = E_FAIL;
                    }

                    if(SUCCEEDED(hr))
                    {
                        lstrcpynW(data->categories[i].sName, V_BSTR(&vValue), MAX_CATEGORY_LENGTH);
                        TRACE("category %d name %s\n", i, debugstr_w(data->categories[i].sName));
                        hr = IXMLDOMElement_get_childNodes(categoryElement, &categoryChildren);
                    }

                    if(SUCCEEDED(hr))
                    {
                        hr = S_OK;
                        while(hr == S_OK)
                        {
                            hr = IXMLDOMNodeList_nextNode(categoryChildren, &statisticNode);

                            if(hr == S_OK)
                            {
                                hr = IXMLDOMNode_QueryInterface(statisticNode, &IID_IXMLDOMElement, (LPVOID*)&statisticElement);

                                if(SUCCEEDED(hr))
                                {
                                    hr = IXMLDOMElement_getAttribute(statisticElement, bstrIndex, &vValue);
                                    if( hr == S_OK && V_VT(&vValue) != VT_BSTR)
                                        hr = E_FAIL;

                                    if(SUCCEEDED(hr))
                                    {
                                        j = StrToIntW(V_BSTR(&vValue));
                                        hr = IXMLDOMElement_getAttribute(statisticElement, bstrName, &vValue);
                                        if( hr == S_OK && V_VT(&vValue) != VT_BSTR)
                                            hr = E_FAIL;
                                    }

                                    if(SUCCEEDED(hr))
                                    {
                                        lstrcpynW(data->categories[i].stats[j].sName, V_BSTR(&vValue), MAX_NAME_LENGTH);
                                        hr = IXMLDOMElement_getAttribute(statisticElement, bstrValue, &vValue);
                                        if( hr == S_OK && V_VT(&vValue) != VT_BSTR)
                                            hr = E_FAIL;
                                    }

                                    if(SUCCEEDED(hr))
                                    {
                                        lstrcpynW(data->categories[i].stats[j].sValue, V_BSTR(&vValue), MAX_VALUE_LENGTH);
                                        TRACE("statistic %d name %s value %s\n", j,
                                              debugstr_w(data->categories[i].stats[j].sName),
                                              debugstr_w(data->categories[i].stats[j].sValue));
                                    }
                                    IXMLDOMElement_Release(statisticElement);
                                }

                                IXMLDOMNode_Release(statisticNode);
                            }
                        }

                        if(SUCCEEDED(hr))
                            hr = S_OK;
                    }
                    IXMLDOMElement_Release(categoryElement);
                }

                IXMLDOMNode_Release(categoryNode);
            }
        }
        if(SUCCEEDED(hr))
            hr = S_OK;
    }

    if(rootChildren) IXMLDOMNodeList_Release(rootChildren);
    if(root) IXMLDOMElement_Release(root);
    if(document) IXMLDOMDocument_Release(document);

    SysFreeString(bstrValue);
    SysFreeString(bstrName);
    SysFreeString(bstrStatistic);
    SysFreeString(bstrIndex);
    SysFreeString(bstrCategory);
    SysFreeString(bstrStatistics);
    SysFreeString(V_BSTR(&vStatsFilePath));
    return hr;
}
Пример #7
0
static HMODULE load_graphics_driver( const WCHAR *driver, const GUID *guid )
{
    static const WCHAR device_keyW[] = {
        'S','y','s','t','e','m','\\',
        'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
        'C','o','n','t','r','o','l','\\',
        'V','i','d','e','o','\\',
        '{','%','0','8','x','-','%','0','4','x','-','%','0','4','x','-',
        '%','0','2','x','%','0','2','x','-','%','0','2','x','%','0','2','x','%','0','2','x',
        '%','0','2','x','%','0','2','x','%','0','2','x','}','\\','0','0','0','0',0};
    static const WCHAR graphics_driverW[] = {'G','r','a','p','h','i','c','s','D','r','i','v','e','r',0};
    static const WCHAR driversW[] = {'S','o','f','t','w','a','r','e','\\',
                                     'W','i','n','e','\\','D','r','i','v','e','r','s',0};
    static const WCHAR graphicsW[] = {'G','r','a','p','h','i','c','s',0};
    static const WCHAR drv_formatW[] = {'w','i','n','e','%','s','.','d','r','v',0};

    WCHAR buffer[MAX_PATH], libname[32], *name, *next;
    WCHAR key[sizeof(device_keyW)/sizeof(WCHAR) + 39];
    HMODULE module = 0;
    HKEY hkey;
    char error[80];

    if (!driver)
    {
        strcpyW( buffer, default_driver );

        /* @@ Wine registry key: HKCU\Software\Wine\Drivers */
        if (!RegOpenKeyW( HKEY_CURRENT_USER, driversW, &hkey ))
        {
            DWORD count = sizeof(buffer);
            RegQueryValueExW( hkey, graphicsW, 0, NULL, (LPBYTE)buffer, &count );
            RegCloseKey( hkey );
        }
    }
    else lstrcpynW( buffer, driver, sizeof(buffer)/sizeof(WCHAR) );

    name = buffer;
    while (name)
    {
        next = strchrW( name, ',' );
        if (next) *next++ = 0;

        snprintfW( libname, sizeof(libname)/sizeof(WCHAR), drv_formatW, name );
        if ((module = LoadLibraryW( libname )) != 0) break;
        switch (GetLastError())
        {
        case ERROR_MOD_NOT_FOUND:
            strcpy( error, "The graphics driver is missing. Check your build!" );
            break;
        case ERROR_DLL_INIT_FAILED:
            strcpy( error, "Make sure that your X server is running and that $DISPLAY is set correctly." );
            break;
        default:
            sprintf( error, "Unknown error (%u).", GetLastError() );
            break;
        }
        name = next;
    }

    if (module)
    {
        GetModuleFileNameW( module, buffer, MAX_PATH );
        TRACE( "display %s driver %s\n", debugstr_guid(guid), debugstr_w(buffer) );
    }

    sprintfW( key, device_keyW, guid->Data1, guid->Data2, guid->Data3,
              guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
              guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7] );

    if (!RegCreateKeyExW( HKEY_LOCAL_MACHINE, key, 0, NULL,
                          REG_OPTION_VOLATILE, KEY_SET_VALUE, NULL, &hkey, NULL  ))
    {
        if (module)
            RegSetValueExW( hkey, graphics_driverW, 0, REG_SZ,
                            (BYTE *)buffer, (strlenW(buffer) + 1) * sizeof(WCHAR) );
        else
            RegSetValueExA( hkey, "DriverError", 0, REG_SZ, (BYTE *)error, strlen(error) + 1 );
        RegCloseKey( hkey );
    }

    return module;
}
Пример #8
0
HRESULT DSoundRender_create(IUnknown * pUnkOuter, LPVOID * ppv)
{
    HRESULT hr;
    PIN_INFO piInput;
    DSoundRenderImpl * pDSoundRender;

    TRACE("(%p, %p)\n", pUnkOuter, ppv);

    *ppv = NULL;

    if (pUnkOuter)
        return CLASS_E_NOAGGREGATION;
    
    pDSoundRender = CoTaskMemAlloc(sizeof(DSoundRenderImpl));
    if (!pDSoundRender)
        return E_OUTOFMEMORY;
    ZeroMemory(pDSoundRender, sizeof(DSoundRenderImpl));

    pDSoundRender->lpVtbl = &DSoundRender_Vtbl;
    pDSoundRender->IBasicAudio_vtbl = &IBasicAudio_Vtbl;
    pDSoundRender->IReferenceClock_vtbl = &IReferenceClock_Vtbl;
    pDSoundRender->refCount = 1;
    InitializeCriticalSection(&pDSoundRender->csFilter);
    pDSoundRender->csFilter.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": DSoundRenderImpl.csFilter");
    pDSoundRender->state = State_Stopped;

    /* construct input pin */
    piInput.dir = PINDIR_INPUT;
    piInput.pFilter = (IBaseFilter *)pDSoundRender;
    lstrcpynW(piInput.achName, wcsInputPinName, sizeof(piInput.achName) / sizeof(piInput.achName[0]));
    hr = InputPin_Construct(&DSoundRender_InputPin_Vtbl, &piInput, DSoundRender_Sample, pDSoundRender, DSoundRender_QueryAccept, NULL, &pDSoundRender->csFilter, NULL, (IPin **)&pDSoundRender->pInputPin);

    if (SUCCEEDED(hr))
    {
        hr = DirectSoundCreate8(NULL, &pDSoundRender->dsound, NULL);
        if (FAILED(hr))
            ERR("Cannot create Direct Sound object (%x)\n", hr);
        else
            IDirectSound_SetCooperativeLevel(pDSoundRender->dsound, GetDesktopWindow(), DSSCL_PRIORITY);
    }

    if (SUCCEEDED(hr))
    {
        MediaSeekingImpl_Init((IBaseFilter*)pDSoundRender, sound_mod_stop, sound_mod_start, sound_mod_rate, &pDSoundRender->mediaSeeking, &pDSoundRender->csFilter);
        pDSoundRender->mediaSeeking.lpVtbl = &IMediaSeeking_Vtbl;

        pDSoundRender->state_change = CreateEventW(NULL, TRUE, TRUE, NULL);
        pDSoundRender->blocked = CreateEventW(NULL, FALSE, FALSE, NULL);

        if (!pDSoundRender->state_change || !pDSoundRender->blocked)
        {
            IUnknown_Release((IUnknown *)pDSoundRender);
            return HRESULT_FROM_WIN32(GetLastError());
        }

        *ppv = (LPVOID)pDSoundRender;
    }
    else
    {
        if (pDSoundRender->pInputPin)
            IPin_Release((IPin*)pDSoundRender->pInputPin);
        pDSoundRender->csFilter.DebugInfo->Spare[0] = 0;
        DeleteCriticalSection(&pDSoundRender->csFilter);
        CoTaskMemFree(pDSoundRender);
    }

    return hr;
}
Пример #9
0
/*****************************************************
 * localmon_XcvDataPort [exported through MONITOREX]
 *
 * Execute command through a Communication-Channel
 *
 * PARAMS
 *  hXcv            [i] The Handle to work with
 *  pszDataName     [i] Name of the command to execute
 *  pInputData      [i] Buffer for extra Input Data (needed only for some commands)
 *  cbInputData     [i] Size in Bytes of Buffer at pInputData
 *  pOutputData     [o] Buffer to receive additional Data (needed only for some commands)
 *  cbOutputData    [i] Size in Bytes of Buffer at pOutputData
 *  pcbOutputNeeded [o] PTR to receive the minimal Size in Bytes of the Buffer at pOutputData
 *
 * RETURNS
 *  Success: ERROR_SUCCESS
 *  Failure: win32 error code
 *
 * NOTES
 *
 *  Minimal List of commands, that every Printmonitor DLL should support:
 *
 *| "MonitorUI" : Return the Name of the Userinterface-DLL as WSTR in pOutputData
 *| "AddPort"   : Add a Port (Name as WSTR in pInputData)
 *| "DeletePort": Delete a Port (Name as WSTR in pInputData)
 *
 *
 */
static DWORD WINAPI localmon_XcvDataPort(HANDLE hXcv, LPCWSTR pszDataName, PBYTE pInputData, DWORD cbInputData,
                                         PBYTE pOutputData, DWORD cbOutputData, PDWORD pcbOutputNeeded)
{
    WCHAR   buffer[16];     /* buffer for a decimal number */
    LPWSTR  ptr;
    DWORD   res;
    DWORD   needed;
    HKEY    hroot;

    TRACE("(%p, %s, %p, %d, %p, %d, %p)\n", hXcv, debugstr_w(pszDataName),
          pInputData, cbInputData, pOutputData, cbOutputData, pcbOutputNeeded);

    if (!lstrcmpW(pszDataName, cmd_AddPortW)) {
        TRACE("InputData (%d): %s\n", cbInputData, debugstr_w( (LPWSTR) pInputData));
        res = RegOpenKeyW(HKEY_LOCAL_MACHINE, WinNT_CV_PortsW, &hroot);
        if (res == ERROR_SUCCESS) {
            if (does_port_exist((LPWSTR) pInputData)) {
                RegCloseKey(hroot);
                TRACE("=> %u\n", ERROR_ALREADY_EXISTS);
                return ERROR_ALREADY_EXISTS;
            }
            res = RegSetValueExW(hroot, (LPWSTR) pInputData, 0, REG_SZ, (const BYTE *) emptyW, sizeof(emptyW));
            RegCloseKey(hroot);
        }
        TRACE("=> %u\n", res);
        return res;
    }


    if (!lstrcmpW(pszDataName, cmd_ConfigureLPTPortCommandOKW)) {
        TRACE("InputData (%d): %s\n", cbInputData, debugstr_w( (LPWSTR) pInputData));
        res = RegCreateKeyW(HKEY_LOCAL_MACHINE, WinNT_CV_WindowsW, &hroot);
        if (res == ERROR_SUCCESS) {
            res = RegSetValueExW(hroot, TransmissionRetryTimeoutW, 0, REG_SZ, pInputData, cbInputData);
            RegCloseKey(hroot);
        }
        return res;
    }

    if (!lstrcmpW(pszDataName, cmd_DeletePortW)) {
        TRACE("InputData (%d): %s\n", cbInputData, debugstr_w( (LPWSTR) pInputData));
        res = RegOpenKeyW(HKEY_LOCAL_MACHINE, WinNT_CV_PortsW, &hroot);
        if (res == ERROR_SUCCESS) {
            res = RegDeleteValueW(hroot, (LPWSTR) pInputData);
            RegCloseKey(hroot);
            TRACE("=> %u with %u\n", res, GetLastError() );
            return res;
        }
        return ERROR_FILE_NOT_FOUND;
    }

    if (!lstrcmpW(pszDataName, cmd_GetDefaultCommConfigW)) {
        TRACE("InputData (%d): %s\n", cbInputData, debugstr_w( (LPWSTR) pInputData));
        *pcbOutputNeeded = cbOutputData;
        res = GetDefaultCommConfigW((LPWSTR) pInputData, (LPCOMMCONFIG) pOutputData, pcbOutputNeeded);
        TRACE("got %u with %u\n", res, GetLastError() );
        return res ? ERROR_SUCCESS : GetLastError();
    }

    if (!lstrcmpW(pszDataName, cmd_GetTransmissionRetryTimeoutW)) {
        * pcbOutputNeeded = sizeof(DWORD);
        if (cbOutputData >= sizeof(DWORD)) {
            /* the w2k resource kit documented a default of 90, but that's wrong */
            *((LPDWORD) pOutputData) = 45;

            res = RegOpenKeyW(HKEY_LOCAL_MACHINE, WinNT_CV_WindowsW, &hroot);
            if (res == ERROR_SUCCESS) {
                needed = sizeof(buffer) - sizeof(WCHAR);
                res = RegQueryValueExW(hroot, TransmissionRetryTimeoutW, NULL, NULL, (LPBYTE) buffer, &needed);
                if ((res == ERROR_SUCCESS) && (buffer[0])) {
                    *((LPDWORD) pOutputData) = strtoulW(buffer, NULL, 0);
                }
                RegCloseKey(hroot);
            }
            return ERROR_SUCCESS;
        }
        return ERROR_INSUFFICIENT_BUFFER;
    }


    if (!lstrcmpW(pszDataName, cmd_MonitorUIW)) {
        * pcbOutputNeeded = sizeof(dllnameuiW);
        if (cbOutputData >= sizeof(dllnameuiW)) {
            memcpy(pOutputData, dllnameuiW, sizeof(dllnameuiW));
            return ERROR_SUCCESS;
        }
        return ERROR_INSUFFICIENT_BUFFER;
    }

    if (!lstrcmpW(pszDataName, cmd_PortIsValidW)) {
        TRACE("InputData (%d): %s\n", cbInputData, debugstr_w( (LPWSTR) pInputData));
        res = get_type_from_name((LPCWSTR) pInputData);
        TRACE("detected as %u\n",  res);
        /* names, that we have recognized, are valid */
        if (res) return ERROR_SUCCESS;

        /* ERROR_ACCESS_DENIED, ERROR_PATH_NOT_FOUND or something else */
        TRACE("=> %u\n", GetLastError());
        return GetLastError();
    }

    if (!lstrcmpW(pszDataName, cmd_SetDefaultCommConfigW)) {
        /* get the portname from the Handle */
        ptr =  strchrW(((xcv_t *)hXcv)->nameW, ' ');
        if (ptr) {
            ptr++;  /* skip the space */
        }
        else
        {
            ptr =  ((xcv_t *)hXcv)->nameW;
        }
        lstrcpynW(buffer, ptr, sizeof(buffer)/sizeof(WCHAR));
        if (buffer[0]) buffer[lstrlenW(buffer)-1] = '\0';  /* remove the ':' */
        res = SetDefaultCommConfigW(buffer, (LPCOMMCONFIG) pInputData, cbInputData);
        TRACE("got %u with %u\n", res, GetLastError() );
        return res ? ERROR_SUCCESS : GetLastError();
    }

    FIXME("command not supported: %s\n", debugstr_w(pszDataName));
    return ERROR_INVALID_PARAMETER;
}
Пример #10
0
bool graphicD3d::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, float screenDepth, float screenNear)
{
	HRESULT hr;

	IDXGIFactory*			factory;
	IDXGIAdapter*			adapter;
	IDXGIOutput*			adapterOutput;
	UINT					nummodes, numerator, denominator;
	DXGI_MODE_DESC*			displayModelist;
	DXGI_ADAPTER_DESC		adapterDesc;

	DXGI_SWAP_CHAIN_DESC			swapchainDesc;
	D3D11_TEXTURE2D_DESC			depthBufferDesc;
	D3D11_DEPTH_STENCIL_DESC		depthStencilDesc;
	D3D11_DEPTH_STENCIL_VIEW_DESC	depthStencilViewDesc;	
	D3D11_RASTERIZER_DESC			rasterDesc;
	D3D11_VIEWPORT					viewport;


	// 수직동기화 설정 ( true / false )
	m_vsync = vsync;

	//DirectX Graphic Infrastructure 인터페이스 팩토리 만들기.
	hr = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
	if (FAILED(hr))
		return false;
	
	//첫번째 그래픽 카드 어댑터 만들기.
	hr = factory->EnumAdapters(0, &adapter);
	if (FAILED(hr))
		return false;

	//첫번째 모니터의 어댑터 만들기.
	hr = adapter->EnumOutputs(0, &adapterOutput);
	if (FAILED(hr))
		return false;

	//DXGI_FORMAT_R8G8B8A8_UNORM 모니터 출력 포멧에 맞는 모드의 개수 구하기.
	hr = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &nummodes, NULL);
	if (FAILED(hr))
		return false;

	//사용 가능한 모든 모니터와 그래픽카드 조합을 저장할 리스트 생성.
	displayModelist = new DXGI_MODE_DESC[nummodes];
	if (!displayModelist)
		return false;

	//displayModelist 에 값들 채워넣기.
	hr = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &nummodes, displayModelist);
	if (FAILED(hr))
		return false;

	//그래픽 카드와 모니터의 화면 너비/높이 조합을 찾기 완료.
	//모니터의 refresh rate 의 분모 와 분자 값을 저장.
	for (int i = 0; i < nummodes; i++)
	{
		if (displayModelist[i].Width == (UINT)screenWidth &&
			displayModelist[i].Height == (UINT)screenHeight)
		{
			numerator = displayModelist[i].RefreshRate.Numerator;
			denominator = displayModelist[i].RefreshRate.Denominator;
		}
	}


	/*
	*/


	//그래픽 카드 정보 가져오기.
	hr = adapter->GetDesc(&adapterDesc);
	if (FAILED(hr))
		return false;

	//그래픽 카드 메모리 크기 가져오기. ( MegaBytes )
	m_videoMemory = UINT(adapterDesc.DedicatedVideoMemory / 1024 / 1024);
	
	//그래픽 카드 이름 가져오기.
	lstrcpynW(m_videoDescription, adapterDesc.Description, 128);


	/*
	*/
	// 원하는 정보 조회 끝나면, 해당 리소스들 해제
	delete [] displayModelist;
	displayModelist = nullptr;

	//모니터 출력 어댑터 해제
	adapterOutput->Release();
	adapterOutput = nullptr;

	//그래픽카드 어댑터 해제
	adapter->Release();
	adapter = nullptr;

	//팩토리 해제
	factory->Release();
	factory = nullptr;
	

	/*
		스왑체인 설정
	*/

    ZeroMemory( &swapchainDesc, sizeof( swapchainDesc ) );
	//백버퍼 개수를 1개로 설정.
    swapchainDesc.BufferCount = 1;
	swapchainDesc.BufferDesc.Width = screenWidth;
	swapchainDesc.BufferDesc.Height = screenHeight;
    swapchainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	if (m_vsync) {
		//vsync 수치에 맞춰서 page flip 이 일어난다.
		swapchainDesc.BufferDesc.RefreshRate.Numerator = numerator;
		swapchainDesc.BufferDesc.RefreshRate.Denominator = denominator;
	}
	else {
		//vsync 와 상관없이 최대한 많이 그리게 한다.
		swapchainDesc.BufferDesc.RefreshRate.Numerator = 0;
		swapchainDesc.BufferDesc.RefreshRate.Denominator = 1;
	}
	// 백버퍼를 렌더 타겟 용도로 사용 설정.
    swapchainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    swapchainDesc.OutputWindow = hwnd;
	//멀티샘플링 설정을 안함.
    swapchainDesc.SampleDesc.Count = 1;
    swapchainDesc.SampleDesc.Quality = 0;
	//전체화면 모드 창 모드 설정.
	if (fullscreen) {
		swapchainDesc.Windowed = FALSE;
	}
	else {
		swapchainDesc.Windowed = TRUE;
	}
	//스캔라인 정렬 및 사용여부를 안함 (unspecified) 으로 설정.
	swapchainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	swapchainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
	//출력 후 백버퍼 내용 버림으로 설정.
	swapchainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	//추가 옵션 플랙 사용 안함.
	swapchainDesc.Flags = 0;


	/*
		디바이스 설정
	*/
    UINT createDeviceFlags = 0;
#ifdef _DEBUG
    createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

	//그래픽 카드가 dx11 지원되면  HARDWARE,
	//실패하면 REFERENCE 로 처리된다. ( 속도는 HARDWARE 대비 1/1000 정도 느림 )
    D3D_DRIVER_TYPE driverTypes[] =
    {
        D3D_DRIVER_TYPE_HARDWARE,
        D3D_DRIVER_TYPE_WARP,
        D3D_DRIVER_TYPE_REFERENCE,
    };
    UINT numDriverTypes = ARRAYSIZE( driverTypes );

	//directx 버젼 설정
    D3D_FEATURE_LEVEL featureLevels[] =
    {
        D3D_FEATURE_LEVEL_11_0,
        D3D_FEATURE_LEVEL_10_1,
        D3D_FEATURE_LEVEL_10_0,
    };
	UINT numFeatureLevels = ARRAYSIZE( featureLevels );

    

    for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ )
    {
        m_driverType = driverTypes[driverTypeIndex];
        hr = D3D11CreateDeviceAndSwapChain( NULL, m_driverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels,
                                            D3D11_SDK_VERSION, &swapchainDesc, &m_swapChain, &m_device, &m_featureLevel, &m_deviceContext );
        if( SUCCEEDED( hr ) )
            break;
    }
    if( FAILED( hr ) )
        return false;



	/*
		렌더타겟뷰 (render target view) 만들기
	*/
    //백버퍼 포인터를 가져오기.
    ID3D11Texture2D* pBackBuffer = NULL;
	hr = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
    if( FAILED( hr ) )
        return false;

	//백버퍼 포인터로 렌더타겟뷰 생성.
    hr = m_device->CreateRenderTargetView( pBackBuffer, NULL, &m_renderTargetView );
    if( FAILED( hr ) )
        return false;

	//렌더타겟 생성되면 백버퍼 포인터 필요없으므로 제거.
    pBackBuffer->Release();
	pBackBuffer = nullptr;



	/*
		깊이버퍼 (depth buffer) 만들기 (옵션)
	*/
	ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
	depthBufferDesc.Width = screenWidth;
	depthBufferDesc.Height = screenHeight;
	depthBufferDesc.MipLevels = 1;
	depthBufferDesc.ArraySize = 1;
	depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthBufferDesc.SampleDesc.Count = 1;
	depthBufferDesc.SampleDesc.Quality = 0;
	depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthBufferDesc.CPUAccessFlags = 0;
	depthBufferDesc.MiscFlags = 0;

	//깊이버퍼 2D텍스쳐 생성
	hr = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilbuffer);
	if (FAILED(hr))
		return false;


	/*
		깊이 스텐실 정의 (옵션)
	*/
	ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
	depthStencilDesc.DepthEnable = true;
	depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
	depthStencilDesc.StencilEnable = true;
	depthStencilDesc.StencilReadMask = 0xFF;
	depthStencilDesc.StencilWriteMask = 0xFF;
	//픽셀 전면부 스텐실 연산 처리
	depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
	//픽셀 후면부 스텐실 연산 처리
	depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
	
	//깊이 스텐실 상태 생성
	hr = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState);
	if (FAILED(hr))
		return false;

	//디바이스 컨텍스트에 깊이 스텐실 상태 적용.
	m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);
	
	
	/*
		깊이 스텐실 뷰 만들기
	*/
	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
	depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;

	// 깊이-스텐실 뷰를 생성.
	hr = m_device->CreateDepthStencilView(m_depthStencilbuffer, &depthStencilViewDesc, &m_depthStencilView);
	if (FAILED(hr))
		return false;


	/*
		디바이스 컨텍스트에 렌더타겟뷰 와 깊이스텐실뷰를 적용.
	*/
	m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);

	
	/*
		래스터라이징 설정 (옵션)
		- 도형을 어떻게 그릴지 결정 ( 와이어프레임, 2 side 렌더링 등등.. )
	*/

	rasterDesc.AntialiasedLineEnable = false;
	rasterDesc.CullMode = D3D11_CULL_BACK;
	rasterDesc.DepthBias = 0;
	rasterDesc.DepthBiasClamp = 0.0f;
	rasterDesc.DepthClipEnable = true;
	rasterDesc.FillMode = D3D11_FILL_SOLID;
	rasterDesc.FrontCounterClockwise = false;
	rasterDesc.MultisampleEnable = false;
	rasterDesc.ScissorEnable = false;
	rasterDesc.SlopeScaledDepthBias = 0.0f;

	//디바이스로 래스터라이징 상태 생성.
	hr = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState);
	if (FAILED(hr))
		return false;
	
	//디바이스 컨텍스트로 래스터라이징 상태 적용.
	m_deviceContext->RSSetState(m_rasterState);

	

	/*
		뷰포트 생성 
	*/    
	viewport.Width = (FLOAT)screenWidth;
	viewport.Height = (FLOAT)screenHeight;
    viewport.MinDepth = 0.0f;
    viewport.MaxDepth = 1.0f;
    viewport.TopLeftX = 0;
    viewport.TopLeftY = 0;
    m_deviceContext->RSSetViewports( 1, &viewport );


	/*
		투영 행렬 ( projection matrix ) 생성
		- 3d 화면을 2d 뷰포트 공간으로 변환
		- 복사본으로 셰이더에서 사용 할 수 있게 한다.
	*/
	float fieldOfView = (float)XM_PI / 4.0f;
	float screenAspect = (float)screenWidth / (float)screenHeight;

	m_projectionMatrix = XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth);


	/*
		월드 행렬 ( world matrix ) 생성
		- 오브젝트들을 3d 좌표로 변환하기 위한 행렬 
		- 이동 / 회전 / 크기 에 사용.
		- 복사본으로 셰이더에 사용 할 수 있게 한다.
	*/
	// 월드 행렬을 단위 행렬로 초기화
	m_worldMatrix = XMMatrixIdentity();


	/*
		뷰 행렬 ( view matrix )
		- 카메라에서 따로 생성하기 위해 일단 생략.
	*/


	/*
		정사영 행렬 ( Orthographic matix 생성 )
		- 원근감이 없는 행렬
		- 2d 이미지나 UI 등을 표현할 때 사용.
	*/
	// 2D 렌더링에 사용될 정사영 행렬을 생성.
	m_orthoMatrix = XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth);
	
	return true;
}
Пример #11
0
static void ApplicationPageOnNotify(WPARAM wParam, LPARAM lParam)
{
    LPNMHDR         pnmh;
    LV_DISPINFOW*   pnmdi;
    LPAPPLICATION_PAGE_LIST_ITEM pAPLI;
    WCHAR    wszNotResponding[255];
    WCHAR    wszRunning[255];

    LoadStringW(hInst, IDS_APPLICATION_NOT_RESPONDING, wszNotResponding, sizeof(wszNotResponding)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_APPLICATION_RUNNING, wszRunning, sizeof(wszRunning)/sizeof(WCHAR));

    pnmh = (LPNMHDR) lParam;
    pnmdi = (LV_DISPINFOW*) lParam;

    if (pnmh->hwndFrom == hApplicationPageListCtrl) {
        switch (pnmh->code) {
        case LVN_ITEMCHANGED:
            ApplicationPageUpdate();
            break;
            
        case LVN_GETDISPINFOW:
            pAPLI = (LPAPPLICATION_PAGE_LIST_ITEM)pnmdi->item.lParam;

            /* Update the item text */
            if (pnmdi->item.iSubItem == 0)
            {
                lstrcpynW(pnmdi->item.pszText, pAPLI->wszTitle, pnmdi->item.cchTextMax);
            }

            /* Update the item status */
            else if (pnmdi->item.iSubItem == 1)
            {
                if (pAPLI->bHung)
                    lstrcpynW(pnmdi->item.pszText, wszNotResponding, pnmdi->item.cchTextMax);
                else
                    lstrcpynW(pnmdi->item.pszText, wszRunning, pnmdi->item.cchTextMax);
            }

            break;

        case NM_RCLICK:

            if (SendMessageW(hApplicationPageListCtrl, LVM_GETSELECTEDCOUNT, 0, 0) < 1)
            {
                ApplicationPageShowContextMenu1();
            }
            else
            {
                ApplicationPageShowContextMenu2();
            }

            break;

        case NM_DBLCLK:

            ApplicationPage_OnSwitchTo();

            break;
        }
    }
    else if (pnmh->hwndFrom == (HWND)SendMessageW(hApplicationPageListCtrl, LVM_GETHEADER, 0, 0))
    {
        switch (pnmh->code)
        {
        case NM_RCLICK:

            if (SendMessageW(hApplicationPageListCtrl, LVM_GETSELECTEDCOUNT, 0, 0) < 1)
            {
                ApplicationPageShowContextMenu1();
            }
            else
            {
                ApplicationPageShowContextMenu2();
            }

            break;

        case HDN_ITEMCLICKW:

            SendMessageW(hApplicationPageListCtrl, LVM_SORTITEMS, 0, (LPARAM) ApplicationPageCompareFunc);
            bSortAscending = !bSortAscending;

            break;
        }
    }

}
Пример #12
0
/*************************************************************************
 * SHGetFileInfoW            [SHELL32.@]
 *
 */
DWORD_PTR WINAPI SHGetFileInfoW(LPCWSTR path,DWORD dwFileAttributes,
                                SHFILEINFOW *psfi, UINT sizeofpsfi, UINT flags )
{
    WCHAR szLocation[MAX_PATH], szFullPath[MAX_PATH];
    int iIndex;
    DWORD_PTR ret = TRUE;
    DWORD dwAttributes = 0;
    IShellFolder * psfParent = NULL;
    IExtractIconW * pei = NULL;
    LPITEMIDLIST    pidlLast = NULL, pidl = NULL;
    HRESULT hr = S_OK;
    BOOL IconNotYetLoaded=TRUE;
    UINT uGilFlags = 0;

    TRACE("%s fattr=0x%x sfi=%p(attr=0x%08x) size=0x%x flags=0x%x\n",
          (flags & SHGFI_PIDL)? "pidl" : debugstr_w(path), dwFileAttributes,
          psfi, psfi->dwAttributes, sizeofpsfi, flags);

    if (!path)
        return FALSE;

    /* windows initializes these values regardless of the flags */
    if (psfi != NULL)
    {
        psfi->szDisplayName[0] = '\0';
        psfi->szTypeName[0] = '\0';
        psfi->iIcon = 0;
    }

    if (!(flags & SHGFI_PIDL))
    {
        /* SHGetFileInfo should work with absolute and relative paths */
        if (PathIsRelativeW(path))
        {
            GetCurrentDirectoryW(MAX_PATH, szLocation);
            PathCombineW(szFullPath, szLocation, path);
        }
        else
        {
            lstrcpynW(szFullPath, path, MAX_PATH);
        }
    }

    if (flags & SHGFI_EXETYPE)
    {
        if (flags != SHGFI_EXETYPE)
            return 0;
        return shgfi_get_exe_type(szFullPath);
    }

    /*
     * psfi is NULL normally to query EXE type. If it is NULL, none of the
     * below makes sense anyway. Windows allows this and just returns FALSE
     */
    if (psfi == NULL)
        return FALSE;

    /*
     * translate the path into a pidl only when SHGFI_USEFILEATTRIBUTES
     * is not specified.
     * The pidl functions fail on not existing file names
     */

    if (flags & SHGFI_PIDL)
    {
        pidl = ILClone((LPCITEMIDLIST)path);
    }
    else if (!(flags & SHGFI_USEFILEATTRIBUTES))
    {
        hr = SHILCreateFromPathW(szFullPath, &pidl, &dwAttributes);
    }

    if ((flags & SHGFI_PIDL) || !(flags & SHGFI_USEFILEATTRIBUTES))
    {
        /* get the parent shellfolder */
        if (pidl)
        {
            hr = SHBindToParent( pidl, &IID_IShellFolder, (LPVOID*)&psfParent,
                                (LPCITEMIDLIST*)&pidlLast );
            if (SUCCEEDED(hr))
                pidlLast = ILClone(pidlLast);
            ILFree(pidl);
        }
        else
        {
            ERR("pidl is null!\n");
            return FALSE;
        }
    }

    /* get the attributes of the child */
    if (SUCCEEDED(hr) && (flags & SHGFI_ATTRIBUTES))
    {
        if (!(flags & SHGFI_ATTR_SPECIFIED))
        {
            psfi->dwAttributes = 0xffffffff;
        }
        if (psfParent)
            IShellFolder_GetAttributesOf( psfParent, 1, (LPCITEMIDLIST*)&pidlLast,
                                      &(psfi->dwAttributes) );
    }

    /* get the displayname */
    if (SUCCEEDED(hr) && (flags & SHGFI_DISPLAYNAME))
    {
        if (flags & SHGFI_USEFILEATTRIBUTES && !(flags & SHGFI_PIDL))
        {
            lstrcpyW (psfi->szDisplayName, PathFindFileNameW(szFullPath));
        }
        else
        {
            STRRET str;
            hr = IShellFolder_GetDisplayNameOf( psfParent, pidlLast,
                                                SHGDN_INFOLDER, &str);
            StrRetToStrNW (psfi->szDisplayName, MAX_PATH, &str, pidlLast);
        }
    }

    /* get the type name */
    if (SUCCEEDED(hr) && (flags & SHGFI_TYPENAME))
    {
        static const WCHAR szFile[] = { 'F','i','l','e',0 };
        static const WCHAR szDashFile[] = { '-','f','i','l','e',0 };

        if (!(flags & SHGFI_USEFILEATTRIBUTES) || (flags & SHGFI_PIDL))
        {
            char ftype[80];

            _ILGetFileType(pidlLast, ftype, 80);
            MultiByteToWideChar(CP_ACP, 0, ftype, -1, psfi->szTypeName, 80 );
        }
        else
        {
            if (dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                strcatW (psfi->szTypeName, szFile);
            else 
            {
                WCHAR sTemp[64];

                lstrcpyW(sTemp,PathFindExtensionW(szFullPath));
                if (!( HCR_MapTypeToValueW(sTemp, sTemp, 64, TRUE) &&
                    HCR_MapTypeToValueW(sTemp, psfi->szTypeName, 80, FALSE )))
                {
                    lstrcpynW (psfi->szTypeName, sTemp, 64);
                    strcatW (psfi->szTypeName, szDashFile);
                }
            }
        }
    }

    /* ### icons ###*/
    if (flags & SHGFI_OPENICON)
        uGilFlags |= GIL_OPENICON;

    if (flags & SHGFI_LINKOVERLAY)
        uGilFlags |= GIL_FORSHORTCUT;
    else if ((flags&SHGFI_ADDOVERLAYS) ||
             (flags&(SHGFI_ICON|SHGFI_SMALLICON))==SHGFI_ICON)
    {
        if (SHELL_IsShortcut(pidlLast))
            uGilFlags |= GIL_FORSHORTCUT;
    }

    if (flags & SHGFI_OVERLAYINDEX)
        FIXME("SHGFI_OVERLAYINDEX unhandled\n");

    if (flags & SHGFI_SELECTED)
        FIXME("set icon to selected, stub\n");

    if (flags & SHGFI_SHELLICONSIZE)
        FIXME("set icon to shell size, stub\n");

    /* get the iconlocation */
    if (SUCCEEDED(hr) && (flags & SHGFI_ICONLOCATION ))
    {
        UINT uDummy,uFlags;

        if (flags & SHGFI_USEFILEATTRIBUTES && !(flags & SHGFI_PIDL))
        {
            if (dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                lstrcpyW(psfi->szDisplayName, swShell32Name);
                psfi->iIcon = -IDI_SHELL_FOLDER;
            }
            else
            {
                WCHAR* szExt;
                static const WCHAR p1W[] = {'%','1',0};
                WCHAR sTemp [MAX_PATH];

                szExt = PathFindExtensionW(szFullPath);
                TRACE("szExt=%s\n", debugstr_w(szExt));
                if ( szExt &&
                     HCR_MapTypeToValueW(szExt, sTemp, MAX_PATH, TRUE) &&
                     HCR_GetDefaultIconW(sTemp, sTemp, MAX_PATH, &psfi->iIcon))
                {
                    if (lstrcmpW(p1W, sTemp))
                        strcpyW(psfi->szDisplayName, sTemp);
                    else
                    {
                        /* the icon is in the file */
                        strcpyW(psfi->szDisplayName, szFullPath);
                    }
                }
                else
                    ret = FALSE;
            }
        }
        else
        {
            hr = IShellFolder_GetUIObjectOf(psfParent, 0, 1,
                (LPCITEMIDLIST*)&pidlLast, &IID_IExtractIconW,
                &uDummy, (LPVOID*)&pei);
            if (SUCCEEDED(hr))
            {
                hr = IExtractIconW_GetIconLocation(pei, uGilFlags,
                    szLocation, MAX_PATH, &iIndex, &uFlags);

                if (uFlags & GIL_NOTFILENAME)
                    ret = FALSE;
                else
                {
                    lstrcpyW (psfi->szDisplayName, szLocation);
                    psfi->iIcon = iIndex;
                }
                IExtractIconW_Release(pei);
            }
        }
    }

    /* get icon index (or load icon)*/
    if (SUCCEEDED(hr) && (flags & (SHGFI_ICON | SHGFI_SYSICONINDEX)))
    {
        if (flags & SHGFI_USEFILEATTRIBUTES && !(flags & SHGFI_PIDL))
        {
            WCHAR sTemp [MAX_PATH];
            WCHAR * szExt;
            int icon_idx=0;

            lstrcpynW(sTemp, szFullPath, MAX_PATH);

            if (dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                psfi->iIcon = SIC_GetIconIndex(swShell32Name, -IDI_SHELL_FOLDER, 0);
            else
            {
                static const WCHAR p1W[] = {'%','1',0};

                psfi->iIcon = 0;
                szExt = PathFindExtensionW(sTemp);
                if ( szExt &&
                     HCR_MapTypeToValueW(szExt, sTemp, MAX_PATH, TRUE) &&
                     HCR_GetDefaultIconW(sTemp, sTemp, MAX_PATH, &icon_idx))
                {
                    if (!lstrcmpW(p1W,sTemp))            /* icon is in the file */
                        strcpyW(sTemp, szFullPath);

                    if (flags & SHGFI_SYSICONINDEX) 
                    {
                        psfi->iIcon = SIC_GetIconIndex(sTemp,icon_idx,0);
                        if (psfi->iIcon == -1)
                            psfi->iIcon = 0;
                    }
                    else 
                    {
                        UINT ret;
                        if (flags & SHGFI_SMALLICON)
                            ret = PrivateExtractIconsW( sTemp,icon_idx,
                                GetSystemMetrics( SM_CXSMICON ),
                                GetSystemMetrics( SM_CYSMICON ),
                                &psfi->hIcon, 0, 1, 0);
                        else
                            ret = PrivateExtractIconsW( sTemp, icon_idx,
                                GetSystemMetrics( SM_CXICON),
                                GetSystemMetrics( SM_CYICON),
                                &psfi->hIcon, 0, 1, 0);
                        if (ret != 0 && ret != (UINT)-1)
                        {
                            IconNotYetLoaded=FALSE;
                            psfi->iIcon = icon_idx;
                        }
                    }
                }
            }
        }
        else
        {
            if (!(PidlToSicIndex(psfParent, pidlLast, !(flags & SHGFI_SMALLICON),
                uGilFlags, &(psfi->iIcon))))
            {
                ret = FALSE;
            }
        }
        if (ret && (flags & SHGFI_SYSICONINDEX))
        {
            if (flags & SHGFI_SMALLICON)
                ret = (DWORD_PTR) ShellSmallIconList;
            else
                ret = (DWORD_PTR) ShellBigIconList;
        }
    }

    /* icon handle */
    if (SUCCEEDED(hr) && (flags & SHGFI_ICON) && IconNotYetLoaded)
    {
        if (flags & SHGFI_SMALLICON)
            psfi->hIcon = ImageList_GetIcon( ShellSmallIconList, psfi->iIcon, ILD_NORMAL);
        else
            psfi->hIcon = ImageList_GetIcon( ShellBigIconList, psfi->iIcon, ILD_NORMAL);
    }

    if (flags & ~SHGFI_KNOWN_FLAGS)
        FIXME("unknown flags %08x\n", flags & ~SHGFI_KNOWN_FLAGS);

    if (psfParent)
        IShellFolder_Release(psfParent);

    if (hr != S_OK)
        ret = FALSE;

    SHFree(pidlLast);

    TRACE ("icon=%p index=0x%08x attr=0x%08x name=%s type=%s ret=0x%08lx\n",
           psfi->hIcon, psfi->iIcon, psfi->dwAttributes,
           debugstr_w(psfi->szDisplayName), debugstr_w(psfi->szTypeName), ret);

    return ret;
}
Пример #13
0
/***********************************************************************
 * SYSLINK_ParseText
 * Parses the window text string and creates a document. Returns the
 * number of document items created.
 */
static UINT SYSLINK_ParseText (SYSLINK_INFO *infoPtr, LPCWSTR Text)
{
    LPCWSTR current, textstart = NULL, linktext = NULL, firsttag = NULL;
    int taglen = 0, textlen = 0, linklen = 0, docitems = 0;
    PDOC_ITEM Last = NULL;
    SL_ITEM_TYPE CurrentType = slText;
    LPCWSTR lpID, lpUrl;
    UINT lenId, lenUrl;

    TRACE("(%p %s)\n", infoPtr, debugstr_w(Text));

    for(current = Text; *current != 0;)
    {
        if(*current == '<')
        {
            if(!StrCmpNIW(current, SL_LINKOPEN, 2) && (CurrentType == slText))
            {
                BOOL ValidParam = FALSE, ValidLink = FALSE;

                if(*(current + 2) == '>')
                {
                    /* we just have to deal with a <a> tag */
                    taglen = 3;
                    ValidLink = TRUE;
                    ValidParam = TRUE;
                    firsttag = current;
                    linklen = 0;
                    lpID = NULL;
                    lpUrl = NULL;
                }
                else if(*(current + 2) == infoPtr->BreakChar)
                {
                    /* we expect parameters, parse them */
                    LPCWSTR *CurrentParameter = NULL, tmp;
                    UINT *CurrentParameterLen = NULL;

                    taglen = 3;
                    tmp = current + taglen;
                    lpID = NULL;
                    lpUrl = NULL;
                    
CheckParameter:
                    /* compare the current position with all known parameters */
                    if(!StrCmpNIW(tmp, SL_HREF, 6))
                    {
                        taglen += 6;
                        ValidParam = TRUE;
                        CurrentParameter = &lpUrl;
                        CurrentParameterLen = &lenUrl;
                    }
                    else if(!StrCmpNIW(tmp, SL_ID, 4))
                    {
                        taglen += 4;
                        ValidParam = TRUE;
                        CurrentParameter = &lpID;
                        CurrentParameterLen = &lenId;
                    }
                    else
                    {
                        ValidParam = FALSE;
                    }
                    
                    if(ValidParam)
                    {
                        /* we got a known parameter, now search until the next " character.
                           If we can't find a " character, there's a syntax error and we just assume it's text */
                        ValidParam = FALSE;
                        *CurrentParameter = current + taglen;
                        *CurrentParameterLen = 0;

                        for(tmp = *CurrentParameter; *tmp != 0; tmp++)
                        {
                            taglen++;
                            if(*tmp == '\"')
                            {
                                ValidParam = TRUE;
                                tmp++;
                                break;
                            }
                            (*CurrentParameterLen)++;
                        }
                    }
                    if(ValidParam)
                    {
                        /* we're done with this parameter, now there are only 2 possibilities:
                         * 1. another parameter is coming, so expect a ' ' (space) character
                         * 2. the tag is being closed, so expect a '<' character
                         */
                        if(*tmp == infoPtr->BreakChar)
                        {
                            /* we expect another parameter, do the whole thing again */
                            taglen++;
                            tmp++;
                            goto CheckParameter;
                        }
                        else if(*tmp == '>')
                        {
                            /* the tag is being closed, we're done */
                            ValidLink = TRUE;
                            taglen++;
                        }
                    }
                }
                
                if(ValidLink && ValidParam)
                {
                    /* the <a ...> tag appears to be valid. save all information
                       so we can add the link if we find a valid </a> tag later */
                    CurrentType = slLink;
                    linktext = current + taglen;
                    linklen = 0;
                    firsttag = current;
                }
                else
                {
                    taglen = 1;
                    lpID = NULL;
                    lpUrl = NULL;
                    if(textstart == NULL)
                    {
                        textstart = current;
                    }
                }
            }
            else if(!StrCmpNIW(current, SL_LINKCLOSE, 4) && (CurrentType == slLink) && firsttag)
            {
                /* there's a <a...> tag opened, first add the previous text, if present */
                if(textstart != NULL && textlen > 0 && firsttag > textstart)
                {
                    Last = SYSLINK_AppendDocItem(infoPtr, textstart, firsttag - textstart, slText, Last);
                    if(Last == NULL)
                    {
                        ERR("Unable to create new document item!\n");
                        return docitems;
                    }
                    docitems++;
                    textstart = NULL;
                    textlen = 0;
                }
                
                /* now it's time to add the link to the document */
                current += 4;
                if(linktext != NULL && linklen > 0)
                {
                    Last = SYSLINK_AppendDocItem(infoPtr, linktext, linklen, slLink, Last);
                    if(Last == NULL)
                    {
                        ERR("Unable to create new document item!\n");
                        return docitems;
                    }
                    docitems++;
                    if(CurrentType == slLink)
                    {
                        int nc;

                        if(!(infoPtr->Style & WS_DISABLED))
                        {
                            Last->u.Link.state |= LIS_ENABLED;
                        }
                        /* Copy the tag parameters */
                        if(lpID != NULL)
                        {
                            nc = min(lenId, strlenW(lpID));
                            nc = min(nc, MAX_LINKID_TEXT - 1);
                            Last->u.Link.szID = Alloc((nc + 1) * sizeof(WCHAR));
                            if(Last->u.Link.szID != NULL)
                            {
                                lstrcpynW(Last->u.Link.szID, lpID, nc + 1);
                            }
                        }
                        else
                            Last->u.Link.szID = NULL;
                        if(lpUrl != NULL)
                        {
                            nc = min(lenUrl, strlenW(lpUrl));
                            nc = min(nc, L_MAX_URL_LENGTH - 1);
                            Last->u.Link.szUrl = Alloc((nc + 1) * sizeof(WCHAR));
                            if(Last->u.Link.szUrl != NULL)
                            {
                                lstrcpynW(Last->u.Link.szUrl, lpUrl, nc + 1);
                            }
                        }
                        else
                            Last->u.Link.szUrl = NULL;
                    }
                    linktext = NULL;
                }
                CurrentType = slText;
                firsttag = NULL;
                textstart = NULL;
                continue;
            }
            else
            {
                /* we don't know what tag it is, so just continue */
                taglen = 1;
                linklen++;
                if(CurrentType == slText && textstart == NULL)
                {
                    textstart = current;
                }
            }
            
            textlen += taglen;
            current += taglen;
        }
        else
        {
            textlen++;
            linklen++;

            /* save the pointer of the current text item if we couldn't find a tag */
            if(textstart == NULL && CurrentType == slText)
            {
                textstart = current;
            }
            
            current++;
        }
    }
    
    if(textstart != NULL && textlen > 0)
    {
        Last = SYSLINK_AppendDocItem(infoPtr, textstart, textlen, CurrentType, Last);
        if(Last == NULL)
        {
            ERR("Unable to create new document item!\n");
            return docitems;
        }
        if(CurrentType == slLink)
        {
            int nc;

            if(!(infoPtr->Style & WS_DISABLED))
            {
                Last->u.Link.state |= LIS_ENABLED;
            }
            /* Copy the tag parameters */
            if(lpID != NULL)
            {
                nc = min(lenId, strlenW(lpID));
                nc = min(nc, MAX_LINKID_TEXT - 1);
                Last->u.Link.szID = Alloc((nc + 1) * sizeof(WCHAR));
                if(Last->u.Link.szID != NULL)
                {
                    lstrcpynW(Last->u.Link.szID, lpID, nc + 1);
                }
            }
            else
                Last->u.Link.szID = NULL;
            if(lpUrl != NULL)
            {
                nc = min(lenUrl, strlenW(lpUrl));
                nc = min(nc, L_MAX_URL_LENGTH - 1);
                Last->u.Link.szUrl = Alloc((nc + 1) * sizeof(WCHAR));
                if(Last->u.Link.szUrl != NULL)
                {
                    lstrcpynW(Last->u.Link.szUrl, lpUrl, nc + 1);
                }
            }
            else
                Last->u.Link.szUrl = NULL;
        }
        docitems++;
    }

    if(linktext != NULL && linklen > 0)
    {
        /* we got an unclosed link, just display the text */
        Last = SYSLINK_AppendDocItem(infoPtr, linktext, linklen, slText, Last);
        if(Last == NULL)
        {
            ERR("Unable to create new document item!\n");
            return docitems;
        }
        docitems++;
    }

    return docitems;
}
Пример #14
0
/***********************************************************************
 *           SYSLINK_SetItem
 * Sets the states and attributes of a link item.
 */
static LRESULT SYSLINK_SetItem (const SYSLINK_INFO *infoPtr, const LITEM *Item)
{
    PDOC_ITEM di;
    int nc;
    PWSTR szId = NULL;
    PWSTR szUrl = NULL;
    BOOL Repaint = FALSE;

    if(!(Item->mask & LIF_ITEMINDEX) || !(Item->mask & (LIF_FLAGSMASK)))
    {
        ERR("Invalid Flags!\n");
        return FALSE;
    }

    di = SYSLINK_GetLinkItemByIndex(infoPtr, Item->iLink);
    if(di == NULL)
    {
        ERR("Link %d couldn't be found\n", Item->iLink);
        return FALSE;
    }

    if(Item->mask & LIF_ITEMID)
    {
        nc = min(lstrlenW(Item->szID), MAX_LINKID_TEXT - 1);
        szId = Alloc((nc + 1) * sizeof(WCHAR));
        if(szId)
        {
            lstrcpynW(szId, Item->szID, nc + 1);
        }
        else
        {
            ERR("Unable to allocate memory for link id\n");
            return FALSE;
        }
    }

    if(Item->mask & LIF_URL)
    {
        nc = min(lstrlenW(Item->szUrl), L_MAX_URL_LENGTH - 1);
        szUrl = Alloc((nc + 1) * sizeof(WCHAR));
        if(szUrl)
        {
            lstrcpynW(szUrl, Item->szUrl, nc + 1);
        }
        else
        {
            Free(szId);

            ERR("Unable to allocate memory for link url\n");
            return FALSE;
        }
    }

    if(Item->mask & LIF_ITEMID)
    {
        Free(di->u.Link.szID);
        di->u.Link.szID = szId;
    }

    if(Item->mask & LIF_URL)
    {
        Free(di->u.Link.szUrl);
        di->u.Link.szUrl = szUrl;
    }

    if(Item->mask & LIF_STATE)
    {
        UINT oldstate = di->u.Link.state;
        /* clear the masked bits */
        di->u.Link.state &= ~(Item->stateMask & LIS_MASK);
        /* copy the bits */
        di->u.Link.state |= (Item->state & Item->stateMask) & LIS_MASK;
        Repaint = (oldstate != di->u.Link.state);
        
        /* update the focus */
        SYSLINK_SetFocusLink(infoPtr, ((di->u.Link.state & LIS_FOCUSED) ? di : NULL));
    }
    
    if(Repaint)
    {
        SYSLINK_RepaintLink(infoPtr, di);
    }
    
    return TRUE;
}
Пример #15
0
time_t ConvertTimeString(LPCWSTR asctime)
{
    WCHAR tmpChar[TIME_STRING_LEN];
    WCHAR *tmpChar2;
    struct tm t;
    int timelen = strlenW(asctime);

    if(!timelen)
        return 0;

    /* FIXME: the atoiWs below rely on that tmpChar is \0 padded */
    memset( tmpChar, 0, sizeof(tmpChar) );
    lstrcpynW(tmpChar, asctime, TIME_STRING_LEN);

    /* Assert that the string is the expected length */
    if (strlenW(asctime) >= TIME_STRING_LEN) FIXME("\n");

    /* Convert a time such as 'Mon, 15 Nov 1999 16:09:35 GMT' into a SYSTEMTIME structure
     * We assume the time is in this format
     * and divide it into easy to swallow chunks
     */
    tmpChar[3]='\0';
    tmpChar[7]='\0';
    tmpChar[11]='\0';
    tmpChar[16]='\0';
    tmpChar[19]='\0';
    tmpChar[22]='\0';
    tmpChar[25]='\0';

    memset( &t, 0, sizeof(t) );
    t.tm_year = atoiW(tmpChar+12) - 1900;
    t.tm_mday = atoiW(tmpChar+5);
    t.tm_hour = atoiW(tmpChar+17);
    t.tm_min = atoiW(tmpChar+20);
    t.tm_sec = atoiW(tmpChar+23);

    /* and month */
    tmpChar2 = tmpChar + 8;
    switch(tmpChar2[2])
    {
        case 'n':
            if(tmpChar2[1]=='a')
                t.tm_mon = 0;
            else
                t.tm_mon = 5;
            break;
        case 'b':
            t.tm_mon = 1;
            break;
        case 'r':
            if(tmpChar2[1]=='a')
                t.tm_mon = 2;
            else
                t.tm_mon = 3;
            break;
        case 'y':
            t.tm_mon = 4;
            break;
        case 'l':
            t.tm_mon = 6;
            break;
        case 'g':
            t.tm_mon = 7;
            break;
        case 'p':
            t.tm_mon = 8;
            break;
        case 't':
            t.tm_mon = 9;
            break;
        case 'v':
            t.tm_mon = 10;
            break;
        case 'c':
            t.tm_mon = 11;
            break;
        default:
            FIXME("\n");
    }

    return mktime(&t);
}
Пример #16
0
void  FileMon::WatchCallback(DWORD dwErrorCode,DWORD dwNumberOfBytesTransfered,LPOVERLAPPED lpOverlapped) {
  TCHAR szFile[MAX_PATH];
  PFILE_NOTIFY_INFORMATION pNotify;
  WatchStruct* pWatch = (WatchStruct*)lpOverlapped;
  size_t offset = 0;

  if(dwNumberOfBytesTransfered == 0) {
    return;
  }

  if(dwErrorCode == ERROR_SUCCESS) {
    do {
      pNotify = (PFILE_NOTIFY_INFORMATION)&pWatch->mBuffer[offset];
      offset += pNotify->NextEntryOffset;

#ifdef UNICODE
      int fnLen=pNotify->FileNameLength/sizeof(WCHAR)+1;
      fnLen=(fnLen<MAX_PATH)?fnLen:MAX_PATH;
      lstrcpynW(szFile,pNotify->FileName,fnLen);
#else
      int count = WideCharToMultiByte(CP_ACP,0,pNotify->FileName,
        pNotify->FileNameLength / sizeof(WCHAR),
        szFile,MAX_PATH - 1,NULL,NULL);

      szFile[count] = TEXT('\0');
#endif

      char vOut[512];
      wcstombs_s(NULL,vOut,sizeof(vOut),szFile,512);

      std::string n=pWatch->mDirName + "/" + vOut;
      time_t t=time(0);

      DWORD dwWaitResult = WaitForSingleObject(pWatch->fileMon->ghMutex,INFINITE);

      while(true) {
        if(dwWaitResult==WAIT_OBJECT_0) {
          if(pNotify->Action==FILE_ACTION_RENAMED_NEW_NAME||pNotify->Action==FILE_ACTION_ADDED) {
            pWatch->fileMon->changeTimes.insert(std::make_pair(n,t));
          } else if(pNotify->Action==FILE_ACTION_RENAMED_OLD_NAME||pNotify->Action==FILE_ACTION_REMOVED) {
          } else if(pNotify->Action==FILE_ACTION_MODIFIED) {
            pWatch->fileMon->changeTimes.insert(std::make_pair(n,t));
          }

          if(!ReleaseMutex(pWatch->fileMon->ghMutex)) {
            std::cout << "FileMon : Release mutex err.\n";
          }

          break;
        } else if(dwWaitResult==WAIT_ABANDONED) {
          break;
        }
      }

    } while(pNotify->NextEntryOffset != 0);
  }

  DWORD dwWaitResult = WaitForSingleObject(pWatch->fileMon->ghMutex,INFINITE);

  while(true) {
    if(dwWaitResult==WAIT_OBJECT_0) {
      if(!pWatch->mStopNow) {
        ReadDirectoryChangesW(
          pWatch->mDirHandle,pWatch->mBuffer,sizeof(pWatch->mBuffer),FALSE,
          pWatch->mNotifyFilter,NULL,&pWatch->mOverlapped,WatchCallback);
      }

      if(!ReleaseMutex(pWatch->fileMon->ghMutex)) {
        std::cout << "FileMon : Release mutex err.\n";
      }

      break;
    } else if(dwWaitResult==WAIT_ABANDONED) {
      break;
    }
  }


}
Пример #17
0
/**************************************************************************
 * DoOpenProperties
 */
static void DoOpenProperties(ItemCmImpl *This, HWND hwnd)
{
	static const UINT MAX_PROP_PAGES = 99;
	static const WCHAR wszFolder[] = {'F','o','l','d','e','r', 0};
	static const WCHAR wszFiletypeAll[] = {'*',0};
	LPSHELLFOLDER lpDesktopSF;
	LPSHELLFOLDER lpSF;
	LPDATAOBJECT lpDo;
	WCHAR wszFiletype[MAX_PATH];
	WCHAR wszFilename[MAX_PATH];
	PROPSHEETHEADERW psh;
	HPROPSHEETPAGE hpages[MAX_PROP_PAGES];
	HPSXA hpsxa;
	UINT ret;

	TRACE("(%p)->(wnd=%p)\n", This, hwnd);

	ZeroMemory(&psh, sizeof(PROPSHEETHEADERW));
	psh.dwSize = sizeof (PROPSHEETHEADERW);
	psh.hwndParent = hwnd;
	psh.dwFlags = PSH_PROPTITLE;
	psh.nPages = 0;
	psh.u3.phpage = hpages;
	psh.u2.nStartPage = 0;

	_ILSimpleGetTextW(This->apidl[0], (LPVOID)&wszFilename, MAX_PATH);
	psh.pszCaption = (LPCWSTR)&wszFilename;

	/* Find out where to look for the shell extensions */
	if (_ILIsValue(This->apidl[0]))
	{
	    char sTemp[64];
	    sTemp[0] = 0;
	    if (_ILGetExtension(This->apidl[0], sTemp, 64))
	    {
		HCR_MapTypeToValueA(sTemp, sTemp, 64, TRUE);
		MultiByteToWideChar(CP_ACP, 0, sTemp, -1, wszFiletype, MAX_PATH);
	    }
	    else
	    {
		wszFiletype[0] = 0;
	    }
	}
	else if (_ILIsFolder(This->apidl[0]))
	{
	    lstrcpynW(wszFiletype, wszFolder, 64);
	}
	else if (_ILIsSpecialFolder(This->apidl[0]))
	{
	    LPGUID folderGUID;
	    static const WCHAR wszclsid[] = {'C','L','S','I','D','\\', 0};
	    folderGUID = _ILGetGUIDPointer(This->apidl[0]);
	    lstrcpyW(wszFiletype, wszclsid);
	    StringFromGUID2(folderGUID, &wszFiletype[6], MAX_PATH - 6);
	}
	else
	{
	    FIXME("Requested properties for unknown type.\n");
	    return;
	}

	/* Get a suitable DataObject for accessing the files */
	SHGetDesktopFolder(&lpDesktopSF);
	if (_ILIsPidlSimple(This->pidl))
	{
	    ret = IShellFolder_GetUIObjectOf(lpDesktopSF, hwnd, This->cidl, (LPCITEMIDLIST*)This->apidl,
					     &IID_IDataObject, NULL, (LPVOID *)&lpDo);
	    IShellFolder_Release(lpDesktopSF);
	}
	else
	{
	    IShellFolder_BindToObject(lpDesktopSF, This->pidl, NULL, &IID_IShellFolder, (LPVOID*) &lpSF);
	    ret = IShellFolder_GetUIObjectOf(lpSF, hwnd, This->cidl, (LPCITEMIDLIST*)This->apidl,
					     &IID_IDataObject, NULL, (LPVOID *)&lpDo);
	    IShellFolder_Release(lpSF);
	    IShellFolder_Release(lpDesktopSF);
	}

	if (SUCCEEDED(ret))
	{
	    hpsxa = SHCreatePropSheetExtArrayEx(HKEY_CLASSES_ROOT, wszFiletype, MAX_PROP_PAGES - psh.nPages, lpDo);
	    if (hpsxa != NULL)
	    {
		SHAddFromPropSheetExtArray(hpsxa, Properties_AddPropSheetCallback, (LPARAM)&psh);
		SHDestroyPropSheetExtArray(hpsxa);
	    }
	    hpsxa = SHCreatePropSheetExtArrayEx(HKEY_CLASSES_ROOT, wszFiletypeAll, MAX_PROP_PAGES - psh.nPages, lpDo);
	    if (hpsxa != NULL)
	    {
		SHAddFromPropSheetExtArray(hpsxa, Properties_AddPropSheetCallback, (LPARAM)&psh);
		SHDestroyPropSheetExtArray(hpsxa);
	    }
	    IDataObject_Release(lpDo);
	}

	if (psh.nPages)
	    PropertySheetW(&psh);
	else
	    FIXME("No property pages found.\n");
}
Пример #18
0
/* loads the LDIDs specified in the install section of an INF */
void set_ldids(HINF hInf, LPCWSTR pszInstallSection, LPCWSTR pszWorkingDir)
{
    WCHAR field[MAX_FIELD_LENGTH];
    WCHAR line[MAX_FIELD_LENGTH];
    WCHAR dest[MAX_PATH];
    INFCONTEXT context;
    DWORD size;
    int ldid;

    static const WCHAR source_dir[] = {'S','o','u','r','c','e','D','i','r',0};

    static const WCHAR custDestW[] = {
        'C','u','s','t','o','m','D','e','s','t','i','n','a','t','i','o','n',0
    };

    if (!SetupGetLineTextW(NULL, hInf, pszInstallSection, custDestW,
                           field, MAX_FIELD_LENGTH, &size))
        return;

    if (!SetupFindFirstLineW(hInf, field, NULL, &context))
        return;

    do
    {
        LPWSTR value, ptr, key, key_copy = NULL;
        DWORD flags = 0;

        SetupGetLineTextW(&context, NULL, NULL, NULL,
                          line, MAX_FIELD_LENGTH, &size);

        /* SetupGetLineTextW returns the value if there is only one key, but
         * returns the whole line if there is more than one key
         */
        if (!(value = strchrW(line, '=')))
        {
            SetupGetStringFieldW(&context, 0, NULL, 0, &size);
            key = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
            key_copy = key;
            SetupGetStringFieldW(&context, 0, key, size, &size);
            value = line;
        }
        else
        {
            key = line;
            *(value++) = '\0';
        }

        /* remove leading whitespace from the value */
        while (*value == ' ')
            value++;

        /* Extract the flags */
        ptr = strchrW(value, ',');
        if (ptr) {
            *ptr = '\0';
            flags = atolW(ptr+1);
        }

        /* set dest to pszWorkingDir if key is SourceDir */
        if (pszWorkingDir && !lstrcmpiW(value, source_dir))
            lstrcpynW(dest, pszWorkingDir, MAX_PATH);
        else
            get_dest_dir(hInf, value, dest, MAX_PATH);

        /* If prompting required, provide dialog to request path */
        if (flags & 0x04)
            FIXME("Need to support changing paths - default will be used\n");

        /* set all ldids to dest */
        while ((ptr = get_parameter(&key, ',', FALSE)))
        {
            ldid = atolW(ptr);
            SetupSetDirectoryIdW(hInf, ldid, dest);
        }
        HeapFree(GetProcessHeap(), 0, key_copy);
    } while (SetupFindNextLine(&context, &context));
}
Пример #19
0
static NTSTATUS
TH32CreateSnapshotSectionInitialize(DWORD dwFlags,
                                    DWORD th32ProcessID,
                                    PRTL_DEBUG_INFORMATION HeapDebug,
                                    PRTL_DEBUG_INFORMATION ModuleDebug,
                                    PVOID ProcThrdInfo,
                                    HANDLE *SectionHandle)
{
  PSYSTEM_PROCESS_INFORMATION ProcessInfo;
  LPHEAPLIST32 HeapListEntry;
  LPMODULEENTRY32W ModuleListEntry;
  LPPROCESSENTRY32W ProcessListEntry;
  LPTHREADENTRY32 ThreadListEntry;
  OBJECT_ATTRIBUTES ObjectAttributes;
  LARGE_INTEGER SSize, SOffset;
  HANDLE hSection;
  PTH32SNAPSHOT Snapshot;
  ULONG_PTR DataOffset;
  SIZE_T ViewSize;
  ULONG i, nProcesses = 0, nThreads = 0, nHeaps = 0, nModules = 0;
  ULONG RequiredSnapshotSize = sizeof(TH32SNAPSHOT);
  PRTL_PROCESS_HEAPS hi = NULL;
  PRTL_PROCESS_MODULES mi = NULL;
  NTSTATUS Status = STATUS_SUCCESS;

  /*
   * Determine the required size for the heap snapshot
   */
  if(dwFlags & TH32CS_SNAPHEAPLIST)
  {
    hi = (PRTL_PROCESS_HEAPS)HeapDebug->Heaps;
    nHeaps = hi->NumberOfHeaps;
    RequiredSnapshotSize += nHeaps * sizeof(HEAPLIST32);
  }

  /*
   * Determine the required size for the module snapshot
   */
  if(dwFlags & TH32CS_SNAPMODULE)
  {
    mi = (PRTL_PROCESS_MODULES)ModuleDebug->Modules;
    nModules = mi->NumberOfModules;
    RequiredSnapshotSize += nModules * sizeof(MODULEENTRY32W);
  }

  /*
   * Determine the required size for the processes and threads snapshot
   */
  if(dwFlags & (TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD))
  {
    ULONG ProcOffset = 0;

    ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)ProcThrdInfo;
    do
    {
      ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)((ULONG_PTR)ProcessInfo + ProcOffset);
      nProcesses++;
      nThreads += ProcessInfo->NumberOfThreads;
      ProcOffset = ProcessInfo->NextEntryOffset;
    } while(ProcOffset != 0);

    if(dwFlags & TH32CS_SNAPPROCESS)
    {
      RequiredSnapshotSize += nProcesses * sizeof(PROCESSENTRY32W);
    }
    if(dwFlags & TH32CS_SNAPTHREAD)
    {
      RequiredSnapshotSize += nThreads * sizeof(THREADENTRY32);
    }
  }

  /*
   * Create and map the section
   */

  SSize.QuadPart = RequiredSnapshotSize;

  InitializeObjectAttributes(&ObjectAttributes,
                             NULL,
                             ((dwFlags & TH32CS_INHERIT) ? OBJ_INHERIT : 0),
			     NULL,
			     NULL);

  Status = NtCreateSection(&hSection,
                           SECTION_ALL_ACCESS,
                           &ObjectAttributes,
                           &SSize,
                           PAGE_READWRITE,
                           SEC_COMMIT,
                           NULL);
  if(!NT_SUCCESS(Status))
  {
    return Status;
  }

  SOffset.QuadPart = 0;
  ViewSize = 0;
  Snapshot = NULL;

  Status = NtMapViewOfSection(hSection,
                              NtCurrentProcess(),
                              (PVOID*)&Snapshot,
                              0,
                              0,
                              &SOffset,
                              &ViewSize,
                              ViewShare,
                              0,
                              PAGE_READWRITE);
  if(!NT_SUCCESS(Status))
  {
    NtClose(hSection);
    return Status;
  }

  RtlZeroMemory(Snapshot, sizeof(TH32SNAPSHOT));
  DataOffset = 0;

  /*
   * Initialize the section data and fill it with all the data we collected
   */

  /* initialize the heap list */
  if(dwFlags & TH32CS_SNAPHEAPLIST)
  {
    Snapshot->HeapListCount = nHeaps;
    Snapshot->HeapListOffset = DataOffset;
    HeapListEntry = (LPHEAPLIST32)OffsetToPtr(Snapshot, DataOffset);
    for(i = 0; i < nHeaps; i++)
    {
      HeapListEntry->dwSize = sizeof(HEAPLIST32);
      HeapListEntry->th32ProcessID = th32ProcessID;
      HeapListEntry->th32HeapID = (ULONG_PTR)hi->Heaps[i].BaseAddress;
      HeapListEntry->dwFlags = hi->Heaps[i].Flags;

      HeapListEntry++;
    }

    DataOffset += hi->NumberOfHeaps * sizeof(HEAPLIST32);
  }

  /* initialize the module list */
  if(dwFlags & TH32CS_SNAPMODULE)
  {
    Snapshot->ModuleListCount = nModules;
    Snapshot->ModuleListOffset = DataOffset;
    ModuleListEntry = (LPMODULEENTRY32W)OffsetToPtr(Snapshot, DataOffset);
    for(i = 0; i < nModules; i++)
    {
      ModuleListEntry->dwSize = sizeof(MODULEENTRY32W);
      ModuleListEntry->th32ModuleID = 1; /* no longer used, always set to one! */
      ModuleListEntry->th32ProcessID = th32ProcessID;
      ModuleListEntry->GlblcntUsage = mi->Modules[i].LoadCount;
      ModuleListEntry->ProccntUsage = mi->Modules[i].LoadCount;
      ModuleListEntry->modBaseAddr = (BYTE*)mi->Modules[i].ImageBase;
      ModuleListEntry->modBaseSize = mi->Modules[i].ImageSize;
      ModuleListEntry->hModule = (HMODULE)mi->Modules[i].ImageBase;

      MultiByteToWideChar(CP_ACP,
                          0,
                          &mi->Modules[i].FullPathName[mi->Modules[i].OffsetToFileName],
                          -1,
                          ModuleListEntry->szModule,
                          sizeof(ModuleListEntry->szModule) / sizeof(ModuleListEntry->szModule[0]));

      MultiByteToWideChar(CP_ACP,
                          0,
                          mi->Modules[i].FullPathName,
                          -1,
                          ModuleListEntry->szExePath,
                          sizeof(ModuleListEntry->szExePath) / sizeof(ModuleListEntry->szExePath[0]));

      ModuleListEntry++;
    }

    DataOffset += mi->NumberOfModules * sizeof(MODULEENTRY32W);
  }

  /* initialize the process list */
  if(dwFlags & TH32CS_SNAPPROCESS)
  {
    ULONG ProcOffset = 0;

    Snapshot->ProcessListCount = nProcesses;
    Snapshot->ProcessListOffset = DataOffset;
    ProcessListEntry = (LPPROCESSENTRY32W)OffsetToPtr(Snapshot, DataOffset);
    ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)ProcThrdInfo;
    do
    {
      ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)((ULONG_PTR)ProcessInfo + ProcOffset);

      ProcessListEntry->dwSize = sizeof(PROCESSENTRY32W);
      ProcessListEntry->cntUsage = 0; /* no longer used */
      ProcessListEntry->th32ProcessID = (ULONG_PTR)ProcessInfo->UniqueProcessId;
      ProcessListEntry->th32DefaultHeapID = 0; /* no longer used */
      ProcessListEntry->th32ModuleID = 0; /* no longer used */
      ProcessListEntry->cntThreads = ProcessInfo->NumberOfThreads;
      ProcessListEntry->th32ParentProcessID = (ULONG_PTR)ProcessInfo->InheritedFromUniqueProcessId;
      ProcessListEntry->pcPriClassBase = ProcessInfo->BasePriority;
      ProcessListEntry->dwFlags = 0; /* no longer used */
      if(ProcessInfo->ImageName.Buffer != NULL)
      {
        lstrcpynW(ProcessListEntry->szExeFile,
                  ProcessInfo->ImageName.Buffer,
                  min(ProcessInfo->ImageName.Length / sizeof(WCHAR), sizeof(ProcessListEntry->szExeFile) / sizeof(ProcessListEntry->szExeFile[0])));
      }
      else
      {
        lstrcpyW(ProcessListEntry->szExeFile, L"[System Process]");
      }

      ProcessListEntry++;

      ProcOffset = ProcessInfo->NextEntryOffset;
    } while(ProcOffset != 0);

    DataOffset += nProcesses * sizeof(PROCESSENTRY32W);
  }

  /* initialize the thread list */
  if(dwFlags & TH32CS_SNAPTHREAD)
  {
    ULONG ProcOffset = 0;

    Snapshot->ThreadListCount = nThreads;
    Snapshot->ThreadListOffset = DataOffset;
    ThreadListEntry = (LPTHREADENTRY32)OffsetToPtr(Snapshot, DataOffset);
    ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)ProcThrdInfo;
    do
    {
      PSYSTEM_THREAD_INFORMATION ThreadInfo;
      ULONG n;

      ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)((ULONG_PTR)ProcessInfo + ProcOffset);
      ThreadInfo = (PSYSTEM_THREAD_INFORMATION)(ProcessInfo + 1);

      for(n = 0; n < ProcessInfo->NumberOfThreads; n++)
      {
        ThreadListEntry->dwSize = sizeof(THREADENTRY32);
        ThreadListEntry->cntUsage = 0; /* no longer used */
        ThreadListEntry->th32ThreadID = (ULONG_PTR)ThreadInfo->ClientId.UniqueThread;
        ThreadListEntry->th32OwnerProcessID = (ULONG_PTR)ThreadInfo->ClientId.UniqueProcess;
        ThreadListEntry->tpBasePri = ThreadInfo->BasePriority;
        ThreadListEntry->tpDeltaPri = 0; /* no longer used */
        ThreadListEntry->dwFlags = 0; /* no longer used */

        ThreadInfo++;
        ThreadListEntry++;
      }

      ProcOffset = ProcessInfo->NextEntryOffset;
    } while(ProcOffset != 0);
  }

  /*
   * We're done, unmap the view and return the section handle
   */

  Status = NtUnmapViewOfSection(NtCurrentProcess(), (PVOID)Snapshot);

  if(NT_SUCCESS(Status))
  {
    *SectionHandle = hSection;
  }
  else
  {
    NtClose(hSection);
  }

  return Status;
}
Пример #20
0
	virtual void SaveValue(FarDialogItem *Item, int RadioGroupIndex)
	{
		const wchar_t *DataPtr = (const wchar_t *) Info.SendDlgMessage(*DialogHandle, DM_GETCONSTTEXTPTR, ID, 0);
		lstrcpynW(Value, DataPtr, MaxSize);
	}
Пример #21
0
/***********************************************************************
 * Creates and links a new module to a process
 */
struct module* module_new(struct process* pcs, const WCHAR* name,
                          enum module_type type, BOOL virtual,
                          DWORD64 mod_addr, DWORD64 size,
                          unsigned long stamp, unsigned long checksum)
{
    struct module*      module;
    unsigned            i;

    assert(type == DMT_ELF || type == DMT_PE || type == DMT_MACHO);
    if (!(module = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*module))))
	return NULL;

    module->next = pcs->lmodules;
    pcs->lmodules = module;

    TRACE("=> %s %s-%s %s\n",
          get_module_type(type, virtual),
	  wine_dbgstr_longlong(mod_addr), wine_dbgstr_longlong(mod_addr + size),
          debugstr_w(name));

    pool_init(&module->pool, 65536);

    module->process = pcs;
    module->module.SizeOfStruct = sizeof(module->module);
    module->module.BaseOfImage = mod_addr;
    module->module.ImageSize = size;
    module_set_module(module, name);
    module->module.ImageName[0] = '\0';
    lstrcpynW(module->module.LoadedImageName, name, sizeof(module->module.LoadedImageName) / sizeof(WCHAR));
    module->module.SymType = SymNone;
    module->module.NumSyms = 0;
    module->module.TimeDateStamp = stamp;
    module->module.CheckSum = checksum;

    memset(module->module.LoadedPdbName, 0, sizeof(module->module.LoadedPdbName));
    module->module.CVSig = 0;
    memset(module->module.CVData, 0, sizeof(module->module.CVData));
    module->module.PdbSig = 0;
    memset(&module->module.PdbSig70, 0, sizeof(module->module.PdbSig70));
    module->module.PdbAge = 0;
    module->module.PdbUnmatched = FALSE;
    module->module.DbgUnmatched = FALSE;
    module->module.LineNumbers = FALSE;
    module->module.GlobalSymbols = FALSE;
    module->module.TypeInfo = FALSE;
    module->module.SourceIndexed = FALSE;
    module->module.Publics = FALSE;

    module->reloc_delta       = 0;
    module->type              = type;
    module->is_virtual        = virtual;
    for (i = 0; i < DFI_LAST; i++) module->format_info[i] = NULL;
    module->sortlist_valid    = FALSE;
    module->sorttab_size      = 0;
    module->addr_sorttab      = NULL;
    module->num_sorttab       = 0;
    module->num_symbols       = 0;

    vector_init(&module->vsymt, sizeof(struct symt*), 128);
    /* FIXME: this seems a bit too high (on a per module basis)
     * need some statistics about this
     */
    hash_table_init(&module->pool, &module->ht_symbols, 4096);
    hash_table_init(&module->pool, &module->ht_types,   4096);
    vector_init(&module->vtypes, sizeof(struct symt*),  32);

    module->sources_used      = 0;
    module->sources_alloc     = 0;
    module->sources           = 0;
    wine_rb_init(&module->sources_offsets_tree, &source_rb_functions);

    return module;
}
Пример #22
0
static HRESULT TRASH_GetDetails(const TRASH_BUCKET *bucket, LPCSTR filename, WIN32_FIND_DATAW *data)
{
    LPSTR path = NULL;
    XDG_PARSED_FILE *parsed = NULL;
    char *original_file_name = NULL;
    char *deletion_date = NULL;
    int fd = -1;
    struct stat stats;
    HRESULT ret = S_FALSE;
    LPWSTR original_dos_name;
    int suffix_length = lstrlenA(trashinfo_suffix);
    int filename_length = lstrlenA(filename);
    int files_length = lstrlenA(bucket->files_dir);
    int path_length = max(lstrlenA(bucket->info_dir), files_length);
    
    path = SHAlloc(path_length + filename_length + 1);
    if (path == NULL) return E_OUTOFMEMORY;
    wsprintfA(path, "%s%s", bucket->files_dir, filename);
    path[path_length + filename_length - suffix_length] = 0;  /* remove the '.trashinfo' */    
    if (lstat(path, &stats) == -1)
    {
        ERR("Error accessing data file for trashinfo %s (errno=%d)\n", filename, errno);
        goto failed;
    }
    
    wsprintfA(path, "%s%s", bucket->info_dir, filename);
    fd = open(path, O_RDONLY);
    if (fd == -1)
    {
        ERR("Couldn't open trashinfo file %s (errno=%d)\n", path, errno);
        goto failed;
    }
    
    parsed = XDG_ParseDesktopFile(fd);
    if (parsed == NULL)
    {
        ERR("Parse error in trashinfo file %s\n", path);
        goto failed;
    }
    
    original_file_name = XDG_GetStringValue(parsed, trashinfo_group, "Path", XDG_URLENCODE);
    if (original_file_name == NULL)
    {
        ERR("No 'Path' entry in trashinfo file\n");
        goto failed;
    }
    
    ZeroMemory(data, sizeof(*data));
    data->nFileSizeHigh = (DWORD)((LONGLONG)stats.st_size>>32);
    data->nFileSizeLow = stats.st_size & 0xffffffff;
    RtlSecondsSince1970ToTime(stats.st_mtime, (LARGE_INTEGER *)&data->ftLastWriteTime);
    
    original_dos_name = wine_get_dos_file_name(original_file_name);
    if (original_dos_name != NULL)
    {
        lstrcpynW(data->cFileName, original_dos_name, MAX_PATH);
        SHFree(original_dos_name);
    }
    else
    {
        /* show only the file name */
        char *file = strrchr(original_file_name, '/');
        if (file == NULL)
            file = original_file_name;
        MultiByteToWideChar(CP_UNIXCP, 0, file, -1, data->cFileName, MAX_PATH);
    }
    
    deletion_date = XDG_GetStringValue(parsed, trashinfo_group, "DeletionDate", 0);
    if (deletion_date)
    {
        struct tm del_time;
        time_t del_secs;
        
        sscanf(deletion_date, "%d-%d-%dT%d:%d:%d",
            &del_time.tm_year, &del_time.tm_mon, &del_time.tm_mday,
            &del_time.tm_hour, &del_time.tm_min, &del_time.tm_sec);
        del_time.tm_year -= 1900;
        del_time.tm_mon--;
        del_time.tm_isdst = -1;
        del_secs = mktime(&del_time);
        
        RtlSecondsSince1970ToTime(del_secs, (LARGE_INTEGER *)&data->ftLastAccessTime);
    }
    
    ret = S_OK;
failed:
    SHFree(path);
    SHFree(original_file_name);
    SHFree(deletion_date);
    if (fd != -1)
        close(fd);
    XDG_FreeParsedFile(parsed);
    return ret;
}
Пример #23
0
static HRESULT WINAPI IAssemblyNameImpl_GetDisplayName(IAssemblyName *iface,
                                                       LPOLESTR szDisplayName,
                                                       LPDWORD pccDisplayName,
                                                       DWORD dwDisplayFlags)
{
    IAssemblyNameImpl *name = (IAssemblyNameImpl *)iface;
    WCHAR verstr[30];
    DWORD size;
    LPWSTR cultureval = 0;

    static const WCHAR equals[] = {'=',0};

    TRACE("(%p, %p, %p, %d)\n", iface, szDisplayName,
          pccDisplayName, dwDisplayFlags);

    if (dwDisplayFlags == 0)
    {
        if (!name->displayname || !*name->displayname)
            return FUSION_E_INVALID_NAME;

        size = min(*pccDisplayName, lstrlenW(name->displayname) + 1);

        lstrcpynW(szDisplayName, name->displayname, size);
        *pccDisplayName = size;

        return S_OK;
    }

    if (!name->name || !*name->name)
        return FUSION_E_INVALID_NAME;

    /* Verify buffer size is sufficient */
    size = lstrlenW(name->name) + 1;

    if ((dwDisplayFlags & ASM_DISPLAYF_VERSION) && (name->versize > 0))
    {
        static const WCHAR spec[] = {'%','d',0};
        static const WCHAR period[] = {'.',0};
        int i;

        wsprintfW(verstr, spec, name->version[0]);

        for (i = 1; i < name->versize; i++)
        {
            WCHAR value[6];
            wsprintfW(value, spec, name->version[i]);

            lstrcatW(verstr, period);
            lstrcatW(verstr, value);
        }

        size += lstrlenW(separator) + lstrlenW(version) + lstrlenW(equals) + lstrlenW(verstr);
    }

    if ((dwDisplayFlags & ASM_DISPLAYF_CULTURE) && (name->culture))
    {
        static const WCHAR neutral[] = {'n','e','u','t','r','a','l', 0};

        cultureval = (lstrlenW(name->culture) == 2) ? name->culture : (LPWSTR) neutral;
        size += lstrlenW(separator) + lstrlenW(culture) + lstrlenW(equals) + lstrlenW(cultureval);
    }

    if ((dwDisplayFlags & ASM_DISPLAYF_PUBLIC_KEY_TOKEN) && (name->haspubkey))
        size += lstrlenW(separator) + lstrlenW(pubkey) + lstrlenW(equals) + CHARS_PER_PUBKEY;

    if ((dwDisplayFlags & ASM_DISPLAYF_PROCESSORARCHITECTURE) && (name->procarch))
        size += lstrlenW(separator) + lstrlenW(procarch) + lstrlenW(equals) + lstrlenW(name->procarch);

    if (size > *pccDisplayName)
        return S_FALSE;

    /* Construct the string */
    lstrcpyW(szDisplayName, name->name);

    if ((dwDisplayFlags & ASM_DISPLAYF_VERSION) && (name->versize > 0))
    {
        lstrcatW(szDisplayName, separator);

        lstrcatW(szDisplayName, version);
        lstrcatW(szDisplayName, equals);
        lstrcatW(szDisplayName, verstr);
    }

    if ((dwDisplayFlags & ASM_DISPLAYF_CULTURE) && (name->culture))
    {
        lstrcatW(szDisplayName, separator);

        lstrcatW(szDisplayName, culture);
        lstrcatW(szDisplayName, equals);
        lstrcatW(szDisplayName, cultureval);
    }

    if ((dwDisplayFlags & ASM_DISPLAYF_PUBLIC_KEY_TOKEN) && (name->haspubkey))
    {
        WCHAR pkt[CHARS_PER_PUBKEY + 1];
        static const WCHAR spec[] = {'%','0','x','%','0','x','%','0','x',
            '%','0','x','%','0','x','%','0','x','%','0','x','%','0','x',0};

        lstrcatW(szDisplayName, separator);

        lstrcatW(szDisplayName, pubkey);
        lstrcatW(szDisplayName, equals);

        wsprintfW(pkt, spec, name->pubkey[0], name->pubkey[1], name->pubkey[2],
            name->pubkey[3], name->pubkey[4], name->pubkey[5], name->pubkey[6],
            name->pubkey[7]);

        lstrcatW(szDisplayName, pkt);
    }

    if ((dwDisplayFlags & ASM_DISPLAYF_PROCESSORARCHITECTURE) && (name->procarch))
    {
        lstrcatW(szDisplayName, separator);

        lstrcatW(szDisplayName, procarch);
        lstrcatW(szDisplayName, equals);
        lstrcatW(szDisplayName, name->procarch);
    }

    *pccDisplayName = size;
    return S_OK;
}
Пример #24
0
/***********************************************************************
 *	SHELL32_BindToChild [Internal]
 *
 * Common code for IShellFolder_BindToObject.
 * 
 * PARAMS
 *  pidlRoot     [I] The parent shell folder's absolute pidl.
 *  pathRoot     [I] Absolute dos path of the parent shell folder.
 *  pidlComplete [I] PIDL of the child. Relative to pidlRoot.
 *  riid         [I] GUID of the interface, which ppvOut shall be bound to.
 *  ppvOut       [O] A reference to the child's interface (riid).
 *
 * NOTES
 *  pidlComplete has to contain at least one non empty SHITEMID.
 *  This function makes special assumptions on the shell namespace, which
 *  means you probably can't use it for your IShellFolder implementation.
 */
HRESULT SHELL32_BindToChild (LPCITEMIDLIST pidlRoot,
                             LPCWSTR pathRoot, LPCITEMIDLIST pidlComplete, REFIID riid, LPVOID * ppvOut)
{
    GUID const *clsid;
    IShellFolder *pSF;
    HRESULT hr;
    LPITEMIDLIST pidlChild;

    TRACE("(%p %s %p %s %p)\n", pidlRoot, debugstr_w(pathRoot), pidlComplete, debugstr_guid(riid), ppvOut);

    if (!pidlRoot || !ppvOut || _ILIsEmpty(pidlComplete))
        return E_INVALIDARG;

    *ppvOut = NULL;

    pidlChild = ILCloneFirst (pidlComplete);

    if ((clsid = _ILGetGUIDPointer (pidlChild))) {
        /* virtual folder */
        hr = SHELL32_CoCreateInitSF (pidlRoot, pathRoot, pidlChild, clsid, (LPVOID *)&pSF);
    } else if (_ILIsValue(pidlChild)) {
        /* Don't bind to files */
        hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
    } else {
        /* file system folder */
        CLSID clsidFolder = CLSID_ShellFSFolder;
        static const WCHAR wszCLSID[] = {'C','L','S','I','D',0};
        WCHAR wszCLSIDValue[CHARS_IN_GUID], wszFolderPath[MAX_PATH], *pwszPathTail = wszFolderPath;
       
        /* see if folder CLSID should be overridden by desktop.ini file */
        if (pathRoot) {
            lstrcpynW(wszFolderPath, pathRoot, MAX_PATH);
            pwszPathTail = PathAddBackslashW(wszFolderPath);
        }

        _ILSimpleGetTextW(pidlChild,pwszPathTail,MAX_PATH - (int)(pwszPathTail - wszFolderPath));

        if (SHELL32_GetCustomFolderAttributeFromPath (wszFolderPath,
            wszDotShellClassInfo, wszCLSID, wszCLSIDValue, CHARS_IN_GUID))
            CLSIDFromString (wszCLSIDValue, &clsidFolder);

        hr = SHELL32_CoCreateInitSF (pidlRoot, pathRoot, pidlChild,
                                     &clsidFolder, (LPVOID *)&pSF);
    }
    ILFree (pidlChild);

    if (SUCCEEDED (hr)) {
        if (_ILIsPidlSimple (pidlComplete)) {
            /* no sub folders */
            hr = IShellFolder_QueryInterface (pSF, riid, ppvOut);
        } else {
            /* go deeper */
            hr = IShellFolder_BindToObject (pSF, ILGetNext (pidlComplete), NULL, riid, ppvOut);
        }
        IShellFolder_Release (pSF);
    }

    TRACE ("-- returning (%p) 0x%08x\n", *ppvOut, hr);

    return hr;
}
Пример #25
0
INT_PTR CALLBACK DlgProcOptsConnections(HWND hWndDlg,UINT msg,WPARAM wParam,LPARAM lParam)
{
	switch(msg){
	case WM_INITDIALOG:
		{
			WCHAR szBuff[MAX_PATH];

			TranslateDialogDefault(hWndDlg);

			if (DB_Mra_GetStaticStringW(NULL,"Server",szBuff,SIZEOF(szBuff),NULL))
			{
				SET_DLG_ITEM_TEXT(hWndDlg,IDC_SERVER,szBuff);
			}else{
				SET_DLG_ITEM_TEXTA(hWndDlg,IDC_SERVER,MRA_DEFAULT_SERVER);
			}
			SetDlgItemInt(hWndDlg,IDC_SERVERPORT,DB_Mra_GetWord(NULL,"ServerPort",MRA_DEFAULT_SERVER_PORT),FALSE);
			// if set SSL proxy, setting will ignored
			
			//CHECK_DLG_BUTTON(hWndDlg, IDC_KEEPALIVE,DB_Mra_GetByte(NULL,"keepalive",0));
			CHECK_DLG_BUTTON(hWndDlg,IDC_AUTO_ADD_CONTACTS_TO_SERVER,DB_Mra_GetByte(NULL,"AutoAddContactsToServer",MRA_DEFAULT_AUTO_ADD_CONTACTS_TO_SERVER));
			CHECK_DLG_BUTTON(hWndDlg,IDC_AUTO_AUTH_REQ_ON_LOGON,DB_Mra_GetByte(NULL,"AutoAuthRequestOnLogon",MRA_DEFAULT_AUTO_AUTH_REQ_ON_LOGON));
			CHECK_DLG_BUTTON(hWndDlg,IDC_AUTO_AUTH_GRAND_IN_CLIST,DB_Mra_GetByte(NULL,"AutoAuthGrandUsersInCList",MRA_DEFAULT_AUTO_AUTH_GRAND_IN_CLIST));
			CHECK_DLG_BUTTON(hWndDlg,IDC_AUTO_AUTH_GRAND_NEW_USERS,DB_Mra_GetByte(NULL,"AutoAuthGrandNewUsers",MRA_DEFAULT_AUTO_AUTH_GRAND_NEW_USERS));
			CHECK_DLG_BUTTON(hWndDlg,IDC_AUTO_AUTH_GRAND_NEW_USERS_DISABLE_SPAM_CHECK,DB_Mra_GetByte(NULL,"AutoAuthGrandNewUsersDisableSPAMCheck",MRA_DEFAULT_AUTO_AUTH_GRAND_NEW_USERS_DISABLE_SPAM_CHECK));
			EnableWindow(GetDlgItem(hWndDlg,IDC_AUTO_AUTH_GRAND_NEW_USERS_DISABLE_SPAM_CHECK),IS_DLG_BUTTON_CHECKED(hWndDlg,IDC_AUTO_AUTH_GRAND_NEW_USERS));

			CHECK_DLG_BUTTON(hWndDlg,IDC_SLOWSEND,DB_Mra_GetByte(NULL,"SlowSend",MRA_DEFAULT_SLOW_SEND));
			CHECK_DLG_BUTTON(hWndDlg,IDC_INCREMENTAL_NEW_MAIL_NOTIFY,DB_Mra_GetByte(NULL,"IncrementalNewMailNotify",MRA_DEFAULT_INC_NEW_MAIL_NOTIFY));
			CHECK_DLG_BUTTON(hWndDlg,IDC_TRAYICON_NEW_MAIL_NOTIFY,DB_Mra_GetByte(NULL,"TrayIconNewMailNotify",MRA_DEFAULT_TRAYICON_NEW_MAIL_NOTIFY));
			CHECK_DLG_BUTTON(hWndDlg,IDC_TRAYICON_NEW_MAIL_NOTIFY_CLICK_TO_INBOX,DB_Mra_GetByte(NULL,"TrayIconNewMailClkToInbox",MRA_DEFAULT_TRAYICON_NEW_MAIL_CLK_TO_INBOX));
			EnableWindow(GetDlgItem(hWndDlg,IDC_TRAYICON_NEW_MAIL_NOTIFY_CLICK_TO_INBOX),DB_Mra_GetByte(NULL,"TrayIconNewMailNotify",MRA_DEFAULT_TRAYICON_NEW_MAIL_NOTIFY));
			
			CHECK_DLG_BUTTON(hWndDlg,IDC_HIDE_MENU_ITEMS_FOR_NON_MRA,DB_Mra_GetByte(NULL,"HideMenuItemsForNonMRAContacts",MRA_DEFAULT_HIDE_MENU_ITEMS_FOR_NON_MRA));
		
			CHECK_DLG_BUTTON(hWndDlg,IDC_RTF_RECEIVE_ENABLE,DB_Mra_GetByte(NULL,"RTFReceiveEnable",MRA_DEFAULT_RTF_RECEIVE_ENABLE));
			EnableWindow(GetDlgItem(hWndDlg,IDC_RTF_RECEIVE_ENABLE),(BOOL)(masMraSettings.lpfnUncompress!=NULL));
			
			CHECK_DLG_BUTTON(hWndDlg,IDC_RTF_SEND_ENABLE,DB_Mra_GetByte(NULL,"RTFSendEnable",MRA_DEFAULT_RTF_SEND_ENABLE));
			EnableWindow(GetDlgItem(hWndDlg,IDC_RTF_SEND_ENABLE),(BOOL)(masMraSettings.lpfnCompress2!=NULL));
			EnableWindow(GetDlgItem(hWndDlg,IDC_RTF_SEND_SMART),(DB_Mra_GetByte(NULL,"RTFSendEnable",MRA_DEFAULT_RTF_SEND_ENABLE) && masMraSettings.lpfnCompress2));
			EnableWindow(GetDlgItem(hWndDlg,IDC_BUTTON_FONT),(DB_Mra_GetByte(NULL,"RTFSendEnable",MRA_DEFAULT_RTF_SEND_ENABLE) && masMraSettings.lpfnCompress2));
			EnableWindow(GetDlgItem(hWndDlg,IDC_RTF_BGCOLOUR),(DB_Mra_GetByte(NULL,"RTFSendEnable",MRA_DEFAULT_RTF_SEND_ENABLE) && masMraSettings.lpfnCompress2));
			SEND_DLG_ITEM_MESSAGE(hWndDlg,IDC_RTF_BGCOLOUR,CPM_SETCOLOUR,0,DB_Mra_GetDword(NULL,"RTFBackgroundColour",MRA_DEFAULT_RTF_BACKGROUND_COLOUR));
		}
		return(TRUE);
	case WM_COMMAND:
		switch(LOWORD(wParam)){
		case IDC_BUTTON_DEFAULT:
			SET_DLG_ITEM_TEXTA(hWndDlg,IDC_SERVER,MRA_DEFAULT_SERVER);
			SetDlgItemInt(hWndDlg,IDC_SERVERPORT,MRA_DEFAULT_SERVER_PORT,FALSE);
			break;
		case IDC_AUTO_AUTH_GRAND_NEW_USERS:
			EnableWindow(GetDlgItem(hWndDlg,IDC_AUTO_AUTH_GRAND_NEW_USERS_DISABLE_SPAM_CHECK),IS_DLG_BUTTON_CHECKED(hWndDlg,IDC_AUTO_AUTH_GRAND_NEW_USERS));
			break;
		case IDC_TRAYICON_NEW_MAIL_NOTIFY:
			EnableWindow(GetDlgItem(hWndDlg,IDC_TRAYICON_NEW_MAIL_NOTIFY_CLICK_TO_INBOX),IS_DLG_BUTTON_CHECKED(hWndDlg,IDC_TRAYICON_NEW_MAIL_NOTIFY));
			break;
		case IDC_RTF_SEND_ENABLE:
			EnableWindow(GetDlgItem(hWndDlg,IDC_RTF_SEND_SMART),IS_DLG_BUTTON_CHECKED(hWndDlg,IDC_RTF_SEND_ENABLE));
			EnableWindow(GetDlgItem(hWndDlg,IDC_BUTTON_FONT),IS_DLG_BUTTON_CHECKED(hWndDlg,IDC_RTF_SEND_ENABLE));
			EnableWindow(GetDlgItem(hWndDlg,IDC_RTF_BGCOLOUR),IS_DLG_BUTTON_CHECKED(hWndDlg,IDC_RTF_SEND_ENABLE));
			break;
		case IDC_BUTTON_FONT:
			{
				LOGFONT lf={0};
				CHOOSEFONT cf={0};

				cf.lStructSize=sizeof(cf);
				cf.lpLogFont=&lf;
				cf.rgbColors=DB_Mra_GetDword(NULL,"RTFFontColour",MRA_DEFAULT_RTF_FONT_COLOUR);
				cf.Flags=(CF_SCREENFONTS|CF_EFFECTS|CF_FORCEFONTEXIST|CF_INITTOLOGFONTSTRUCT);
				if (DB_Mra_GetContactSettingBlob(NULL,"RTFFont",&lf,sizeof(LOGFONT),NULL)==FALSE)
				{
					HDC hDC=GetDC(NULL);// kegl
					lf.lfCharSet=MRA_DEFAULT_RTF_FONT_CHARSET;
					lf.lfHeight=-MulDiv(MRA_DEFAULT_RTF_FONT_SIZE,GetDeviceCaps(hDC,LOGPIXELSY),72);
					lstrcpynW(lf.lfFaceName,MRA_DEFAULT_RTF_FONT_NAME,LF_FACESIZE);
					ReleaseDC(NULL,hDC);
				}

				if (ChooseFont(&cf))
				{
					/*HDC hDC=GetDC(NULL);
					DWORD dwFontSize;
					dwFontSize=-MulDiv(lf.lfHeight,72,GetDeviceCaps(hDC,LOGPIXELSY));
					dwFontSize+=((dwFontSize+4)/8);//MulDiv(dwFontSize,GetDeviceCaps(hDC,PHYSICALWIDTH),72);
					ReleaseDC(NULL,hDC);*/

					DB_Mra_WriteContactSettingBlob(NULL,"RTFFont",&lf,sizeof(LOGFONT));
					DB_Mra_SetDword(NULL,"RTFFontColour",cf.rgbColors);
				}
			}
			break;
		}

		if ((LOWORD(wParam)==IDC_SERVER || LOWORD(wParam)==IDC_SERVERPORT) && (HIWORD(wParam)!=EN_CHANGE || (HWND)lParam!=GetFocus()) ) return(FALSE);
		SendMessage(GetParent(hWndDlg),PSM_CHANGED,0,0);
		break;
	case WM_NOTIFY:
		switch(((LPNMHDR)lParam)->code){
		case PSN_APPLY:
			{
				WCHAR szBuff[MAX_PATH];

				GET_DLG_ITEM_TEXT(hWndDlg,IDC_SERVER,szBuff,SIZEOF(szBuff));
				DB_Mra_SetStringW(NULL,"Server",szBuff);
				DB_Mra_SetWord(NULL,"ServerPort",(WORD)GetDlgItemInt(hWndDlg,IDC_SERVERPORT,NULL,FALSE));
				DB_Mra_SetByte(NULL,"AutoAddContactsToServer",IS_DLG_BUTTON_CHECKED(hWndDlg,IDC_AUTO_ADD_CONTACTS_TO_SERVER));
				DB_Mra_SetByte(NULL,"AutoAuthRequestOnLogon",IS_DLG_BUTTON_CHECKED(hWndDlg,IDC_AUTO_AUTH_REQ_ON_LOGON));
				DB_Mra_SetByte(NULL,"AutoAuthGrandUsersInCList",IS_DLG_BUTTON_CHECKED(hWndDlg,IDC_AUTO_AUTH_GRAND_IN_CLIST));
				DB_Mra_SetByte(NULL,"AutoAuthGrandNewUsers",IS_DLG_BUTTON_CHECKED(hWndDlg,IDC_AUTO_AUTH_GRAND_NEW_USERS));
				DB_Mra_SetByte(NULL,"AutoAuthGrandNewUsersDisableSPAMCheck",IS_DLG_BUTTON_CHECKED(hWndDlg,IDC_AUTO_AUTH_GRAND_NEW_USERS_DISABLE_SPAM_CHECK));

				DB_Mra_SetByte(NULL,"SlowSend",IS_DLG_BUTTON_CHECKED(hWndDlg,IDC_SLOWSEND));
				DB_Mra_SetByte(NULL,"IncrementalNewMailNotify",IS_DLG_BUTTON_CHECKED(hWndDlg,IDC_INCREMENTAL_NEW_MAIL_NOTIFY));
				DB_Mra_SetByte(NULL,"TrayIconNewMailNotify",IS_DLG_BUTTON_CHECKED(hWndDlg,IDC_TRAYICON_NEW_MAIL_NOTIFY));
				DB_Mra_SetByte(NULL,"TrayIconNewMailClkToInbox",IS_DLG_BUTTON_CHECKED(hWndDlg,IDC_TRAYICON_NEW_MAIL_NOTIFY_CLICK_TO_INBOX));

				DB_Mra_SetByte(NULL,"HideMenuItemsForNonMRAContacts",IS_DLG_BUTTON_CHECKED(hWndDlg,IDC_HIDE_MENU_ITEMS_FOR_NON_MRA));

				DB_Mra_SetByte(NULL,"RTFReceiveEnable",IS_DLG_BUTTON_CHECKED(hWndDlg,IDC_RTF_RECEIVE_ENABLE));
				DB_Mra_SetByte(NULL,"RTFSendEnable",IS_DLG_BUTTON_CHECKED(hWndDlg,IDC_RTF_SEND_ENABLE));
				DBWriteContactSettingDword(NULL,PROTOCOL_NAMEA,"RTFBackgroundColour",SEND_DLG_ITEM_MESSAGE(hWndDlg,IDC_RTF_BGCOLOUR,CPM_GETCOLOUR,0,0));
			}
			return(TRUE);
		}
		break;
	}
return(FALSE);
}
Пример #26
0
/*******************************************************************************
 * GdipCreateFont [GDIPLUS.@]
 *
 * Create a new font based off of a FontFamily
 *
 * PARAMS
 *  *fontFamily     [I] Family to base the font off of
 *  emSize          [I] Size of the font
 *  style           [I] Bitwise OR of FontStyle enumeration
 *  unit            [I] Unit emSize is measured in
 *  **font          [I] the resulting Font object
 *
 * RETURNS
 *  SUCCESS: Ok
 *  FAILURE: InvalidParameter if fontfamily or font is NULL.
 *  FAILURE: FontFamilyNotFound if an invalid FontFamily is given
 *
 * NOTES
 *  UnitDisplay is unsupported.
 *  emSize is stored separately from lfHeight, to hold the fraction.
 */
GpStatus WINGDIPAPI GdipCreateFont(GDIPCONST GpFontFamily *fontFamily,
                        REAL emSize, INT style, Unit unit, GpFont **font)
{
    WCHAR facename[LF_FACESIZE];
    LOGFONTW* lfw;
    const NEWTEXTMETRICW* tmw;
    GpStatus stat;

    if (!fontFamily || !font)
        return InvalidParameter;

    TRACE("%p (%s), %f, %d, %d, %p\n", fontFamily,
            debugstr_w(fontFamily->FamilyName), emSize, style, unit, font);

    stat = GdipGetFamilyName (fontFamily, facename, 0);
    if (stat != Ok) return stat;
    *font = GdipAlloc(sizeof(GpFont));

    tmw = &fontFamily->tmw;
    lfw = &((*font)->lfw);
    ZeroMemory(&(*lfw), sizeof(*lfw));

    lfw->lfWeight = tmw->tmWeight;
    lfw->lfItalic = tmw->tmItalic;
    lfw->lfUnderline = tmw->tmUnderlined;
    lfw->lfStrikeOut = tmw->tmStruckOut;
    lfw->lfCharSet = tmw->tmCharSet;
    lfw->lfPitchAndFamily = tmw->tmPitchAndFamily;
    lstrcpynW(lfw->lfFaceName, facename, LF_FACESIZE);

    switch (unit)
    {
        case UnitWorld:
            /* FIXME: Figure out when World != Pixel */
            lfw->lfHeight = emSize; break;
        case UnitDisplay:
            FIXME("Unknown behavior for UnitDisplay! Please report!\n");
            /* FIXME: Figure out how this works...
             * MSDN says that if "DISPLAY" is a monitor, then pixel should be
             * used. That's not what I got. Tests on Windows revealed no output,
             * and the tests in tests/font crash windows */
            lfw->lfHeight = 0; break;
        case UnitPixel:
            lfw->lfHeight = emSize; break;
        case UnitPoint:
            lfw->lfHeight = point_to_pixel(emSize); break;
        case UnitInch:
            lfw->lfHeight = inch_to_pixel(emSize); break;
        case UnitDocument:
            lfw->lfHeight = document_to_pixel(emSize); break;
        case UnitMillimeter:
            lfw->lfHeight = mm_to_pixel(emSize); break;
    }

    lfw->lfHeight *= -1;

    lfw->lfWeight = style & FontStyleBold ? 700 : 400;
    lfw->lfItalic = style & FontStyleItalic;
    lfw->lfUnderline = style & FontStyleUnderline;
    lfw->lfStrikeOut = style & FontStyleStrikeout;

    (*font)->unit = unit;
    (*font)->emSize = emSize;
    (*font)->height = tmw->ntmSizeEM;
    (*font)->line_spacing = tmw->tmAscent + tmw->tmDescent + tmw->tmExternalLeading;

    TRACE("<-- %p\n", *font);

    return Ok;
}
Пример #27
0
/***********************************************************************
 *                              FD31_TestPath      [internal]
 *      before accepting the file name, test if it includes wild cards
 *      tries to scan the directory and returns TRUE if no error.
 */
static LRESULT FD31_TestPath( PFD31_DATA lfs, LPWSTR path )
{
    HWND hWnd = lfs->hwnd;
    LPWSTR pBeginFileName, pstr2;
    WCHAR tmpstr2[BUFFILE];

    pBeginFileName = strrchrW(path, '\\');
    if (pBeginFileName == NULL)
	pBeginFileName = strrchrW(path, ':');

    if (strchrW(path,'*') != NULL || strchrW(path,'?') != NULL)
    {
        /* edit control contains wildcards */
        if (pBeginFileName != NULL)
        {
	    lstrcpynW(tmpstr2, pBeginFileName + 1, BUFFILE);
	    *(pBeginFileName + 1) = 0;
	}
	else
	{
	    strcpyW(tmpstr2, path);
            if(!(lfs->ofnW->Flags & OFN_NOVALIDATE))
                *path = 0;
        }

        TRACE("path=%s, tmpstr2=%s\n", debugstr_w(path), debugstr_w(tmpstr2));
        SetDlgItemTextW( hWnd, edt1, tmpstr2 );
        FD31_ScanDir(hWnd, path);
        return (lfs->ofnW->Flags & OFN_NOVALIDATE) ? TRUE : FALSE;
    }

    /* no wildcards, we might have a directory or a filename */
    /* try appending a wildcard and reading the directory */

    pstr2 = path + lstrlenW(path);
    if (pBeginFileName == NULL || *(pBeginFileName + 1) != 0)
        strcatW(path, FILE_bslash);

    /* if ScanDir succeeds, we have changed the directory */
    if (FD31_ScanDir(hWnd, path))
        return FALSE; /* and path is not a valid file name */

    /* if not, this must be a filename */

    *pstr2 = 0; /* remove the wildcard added before */

    if (pBeginFileName != NULL)
    {
        /* strip off the pathname */
        *pBeginFileName = 0;
        SetDlgItemTextW( hWnd, edt1, pBeginFileName + 1 );

        lstrcpynW(tmpstr2, pBeginFileName + 1, sizeof(tmpstr2)/sizeof(WCHAR) );
        /* Should we MessageBox() if this fails? */
        if (!FD31_ScanDir(hWnd, path))
        {
            return FALSE;
        }
        strcpyW(path, tmpstr2);
    }
    else
        SetDlgItemTextW( hWnd, edt1, path );
    return TRUE;
}
Пример #28
0
static HRESULT TransformFilter_Init(const IBaseFilterVtbl *pVtbl, const CLSID* pClsid, const TransformFilterFuncTable* pFuncsTable, TransformFilter* pTransformFilter)
{
    HRESULT hr;
    PIN_INFO piInput;
    PIN_INFO piOutput;

    BaseFilter_Init(&pTransformFilter->filter, pVtbl, pClsid, (DWORD_PTR)(__FILE__ ": TransformFilter.csFilter"), &tfBaseFuncTable);

    InitializeCriticalSection(&pTransformFilter->csReceive);
    pTransformFilter->csReceive.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__": TransformFilter.csReceive");

    /* pTransformFilter is already allocated */
    pTransformFilter->pFuncsTable = pFuncsTable;
    ZeroMemory(&pTransformFilter->pmt, sizeof(pTransformFilter->pmt));
    pTransformFilter->npins = 2;

    pTransformFilter->ppPins = CoTaskMemAlloc(2 * sizeof(IPin *));

    /* construct input pin */
    piInput.dir = PINDIR_INPUT;
    piInput.pFilter = &pTransformFilter->filter.IBaseFilter_iface;
    lstrcpynW(piInput.achName, wcsInputPinName, sizeof(piInput.achName) / sizeof(piInput.achName[0]));
    piOutput.dir = PINDIR_OUTPUT;
    piOutput.pFilter = &pTransformFilter->filter.IBaseFilter_iface;
    lstrcpynW(piOutput.achName, wcsOutputPinName, sizeof(piOutput.achName) / sizeof(piOutput.achName[0]));

    hr = BaseInputPin_Construct(&TransformFilter_InputPin_Vtbl, sizeof(BaseInputPin), &piInput,
            &tf_input_BaseInputFuncTable, &pTransformFilter->filter.csFilter, NULL, &pTransformFilter->ppPins[0]);

    if (SUCCEEDED(hr))
    {
        hr = BaseOutputPin_Construct(&TransformFilter_OutputPin_Vtbl, sizeof(BaseOutputPin), &piOutput, &tf_output_BaseOutputFuncTable, &pTransformFilter->filter.csFilter, &pTransformFilter->ppPins[1]);

        if (FAILED(hr))
            ERR("Cannot create output pin (%x)\n", hr);
        else {
            QualityControlImpl_Create( pTransformFilter->ppPins[0], &pTransformFilter->filter.IBaseFilter_iface, &pTransformFilter->qcimpl);
            pTransformFilter->qcimpl->IQualityControl_iface.lpVtbl = &TransformFilter_QualityControl_Vtbl;
        }
    }

    if (SUCCEEDED(hr))
    {
        ISeekingPassThru *passthru;
        pTransformFilter->seekthru_unk = NULL;
        hr = CoCreateInstance(&CLSID_SeekingPassThru, (IUnknown*)pTransformFilter, CLSCTX_INPROC_SERVER, &IID_IUnknown, (void**)&pTransformFilter->seekthru_unk);
        if (SUCCEEDED(hr))
        {
            IUnknown_QueryInterface(pTransformFilter->seekthru_unk, &IID_ISeekingPassThru, (void**)&passthru);
            ISeekingPassThru_Init(passthru, FALSE, pTransformFilter->ppPins[0]);
            ISeekingPassThru_Release(passthru);
        }
    }

    if (FAILED(hr))
    {
        CoTaskMemFree(pTransformFilter->ppPins);
        BaseFilterImpl_Release(&pTransformFilter->filter.IBaseFilter_iface);
    }

    return hr;
}
Пример #29
0
HRESULT MultiFileReader::RefreshTSBufferFile()
{
	if (m_TSBufferFile.IsFileInvalid())
	{
		return S_FALSE;
  }

	ULONG bytesRead = 0;
	ULONG bytesRead2 = 0;
	MultiFileReaderFile *file;

  HRESULT result;
	__int64 currentPosition;
  long filesAdded, filesRemoved;
  long filesAdded2, filesRemoved2;
  long Error=0;
  long Loop=10 ;
  __int64 fileLength = 0;
  	
  do
  {
    if (m_bIsStopping || !m_pInfoFileBuffer1 || !m_pInfoFileBuffer2)
      return E_FAIL ;
      
   	if (Error) //Handle errors from a previous loop iteration
   	{
   	  // if (Loop < 9) //An error on the first loop iteration is quasi-normal, so don't log it
   	  // {
    	//   LogDebug("MultiFileReader has error 0x%x in Loop %d. Try to clear SMB Cache.", Error, 10-Loop);  	  
  	  // }
  	  
  	  // try to clear local / remote SMB file cache. This should happen when we close the filehandle
      m_TSBufferFile.CloseFile();
  	  m_TSBufferFile.OpenFile();
  	  Sleep(5);
    }  

    Error=0;
  	currentPosition = -1;
  	filesAdded = -1;
  	filesRemoved = -1;
  	filesAdded2 = -2;
  	filesRemoved2 = -2;
    Loop-- ;

    //Read the 'header' of the file to work out if anything has changed.
  	int readLength = sizeof(currentPosition) + sizeof(filesAdded) + sizeof(filesRemoved);
    
  	m_TSBufferFile.SetFilePointer(0, FILE_BEGIN);
  	result = m_TSBufferFile.Read(m_pInfoFileBuffer1, readLength, &bytesRead);
		
    if (!SUCCEEDED(result) || bytesRead != readLength) 
    {
		  Error |= 0x02;
      continue;
		}

  	if(Error == 0)
  	{
  		currentPosition = *((__int64*)(m_pInfoFileBuffer1 + 0));
  		filesAdded = *((long*)(m_pInfoFileBuffer1 + sizeof(__int64)));
  		filesRemoved = *((long*)(m_pInfoFileBuffer1 + sizeof(__int64) + sizeof(long)));
  	}

  	m_TSBufferFile.SetFilePointer(0, FILE_BEGIN);
  	result = m_TSBufferFile.Read(m_pInfoFileBuffer2, readLength, &bytesRead);

    if (!SUCCEEDED(result) || bytesRead != readLength) 
    {
		  Error |= 0x04;
      continue;
		}

  	if(Error == 0)
  	{
  		currentPosition = *((__int64*)(m_pInfoFileBuffer2 + 0));
  		filesAdded2 = *((long*)(m_pInfoFileBuffer2 + sizeof(__int64)));
  		filesRemoved2 = *((long*)(m_pInfoFileBuffer2 + sizeof(__int64) + sizeof(long)));
  	}

    if ((filesAdded2 != filesAdded) || (filesRemoved2 != filesRemoved))
    {
		  Error |= 0x08;
      continue;
    } 

    // If no files added or removed, break out of the loop (we don't need to read the rest of the file)
    if ((m_filesAdded == filesAdded) && (m_filesRemoved == filesRemoved)) 
			break ;

    //Now read the full file for processing and comparison.
    //The maximum length is INFO_BUFF_SIZE bytes, but normally
    //'bytesRead' will be much less than that - it should be the actual file length.
	        
  	m_TSBufferFile.SetFilePointer(0, FILE_BEGIN);
  	result=m_TSBufferFile.Read(m_pInfoFileBuffer1, INFO_BUFF_SIZE, &bytesRead);  	
    if (!SUCCEEDED(result) || (bytesRead == 0))
    {
      Error |= 0x20 ;
      continue;
    }
      	  
	  //read it again to a different buffer  
  	m_TSBufferFile.SetFilePointer(0, FILE_BEGIN);
  	result = m_TSBufferFile.Read(m_pInfoFileBuffer2, INFO_BUFF_SIZE, &bytesRead2);
    if (!SUCCEEDED(result) || (bytesRead2 != bytesRead) || (bytesRead2 == 0))
    {
      Error |= 0x40 ;
      continue;
    }
      
    fileLength = (__int64)bytesRead2;

		if (fileLength > INFO_BUFF_SIZE)
      return E_FAIL ;

    // Min file length is Header ( __int64 + long + long ) + filelist ( > 0 ) + Footer ( long + long ) 
    if (fileLength <= (sizeof(__int64) + sizeof(long) + sizeof(long) + sizeof(wchar_t) + sizeof(long) + sizeof(long)))
		  Error |= 0x1000;
    if (fileLength%2) //Must be a multiple of 2 bytes in length
		  Error |= 0x2000;

    //Compare the two buffers (except the 'currentPosition' values), and compare the filesAdded/filesRemoved values 
    //at the beginning and end of the second buffer for integrity checking
  	if (
  	    (Error == 0) 
  	    && (memcmp(m_pInfoFileBuffer1 + sizeof(__int64), m_pInfoFileBuffer2 + sizeof(__int64), (ULONG)(fileLength - sizeof(__int64))) == 0)
  	    && (memcmp(m_pInfoFileBuffer2 + sizeof(__int64), m_pInfoFileBuffer2 + fileLength - (2*sizeof(long)), 2*sizeof(long)) == 0)
  	    )
  	{
  		currentPosition = *((__int64*)(m_pInfoFileBuffer2 + 0)); //use the most recent value
  		filesAdded = *((long*)(m_pInfoFileBuffer2 + sizeof(__int64)));
  		filesRemoved = *((long*)(m_pInfoFileBuffer2 + sizeof(__int64) + sizeof(long)));
   	}
   	else
   	{
		  Error |= 0x80;
      continue;
    }  

    //Rebuild the file list if files have been added or removed
  	if ((m_filesAdded != filesAdded) || (m_filesRemoved != filesRemoved))
  	{
  		long filesToRemove = filesRemoved - m_filesRemoved;
  		long filesToAdd = filesAdded - m_filesAdded;
  		long fileID = filesRemoved;
  		__int64 nextStartPosition = 0;
  
  		// Remove files that aren't present anymore.
  		while ((filesToRemove > 0) && (m_tsFiles.size() > 0))
  		{  			
  			file = m_tsFiles.at(0);  			
  			delete file;
  			m_tsFiles.erase(m_tsFiles.begin()); 
  			m_filesRemoved++;  
  			filesToRemove--;
  		}  
  
  		// Figure out what the start position of the next new file will be
  		if (m_tsFiles.size() > 0)
  		{
  			file = m_tsFiles.back();
  
  			if (filesToAdd > 0)
  			{
  				// If we're adding files the chances are the one at the back has a partial length
  				// so we need update it.
  				result = GetFileLength(file->filename, file->length, true);
  				if (!SUCCEEDED(result)) 
  				{
		        Error |= 0x10;
          }
  			}
  
  			nextStartPosition = file->startPosition + file->length;
  		} 
  
  		//Get the real path of the buffer file
  		LPWSTR wfilename;
  		m_TSBufferFile.GetFileName(&wfilename);
  		LPWSTR path = NULL;
  		LPWSTR name = wcsrchr(wfilename, 92); //Find the last backslash character, so we can extract the path to the containing folder
  		if (name)
  		{
  			name++;
  			long len = name - wfilename;
  			path = new wchar_t[len+1];
  			lstrcpynW(path, wfilename, len+1);
  		}
  
  		// Create a list of files in the .tsbuffer file.
  		std::vector<LPWSTR> filenames;
  
  		LPWSTR pCurr = (LPWSTR)(m_pInfoFileBuffer2 + sizeof(__int64) + sizeof(long) + sizeof(long)); //pointer to start of filename section
  		LPWSTR pEndOfList = (LPWSTR)(m_pInfoFileBuffer2 + fileLength - (2*sizeof(long)));
  		long length = wcslen(pCurr);
  		while ((length > 0) && (pCurr < pEndOfList))
  		{
  			//modify filename path here to include the real path
  			LPWSTR pFilename;
  			LPWSTR temp = wcsrchr(pCurr, 92); //Find the last backslash character, so we can extract just the 'filename' part
  			if (path && temp)
  			{
  				temp++;
  				pFilename = new wchar_t[wcslen(path)+wcslen(temp)+1];
  				wcscpy(pFilename, path);
  				wcscat(pFilename, temp);
  			}
  			else
  			{
  				pFilename = new wchar_t[length+1];
  				wcscpy(pFilename, pCurr);
  			}
  
  			filenames.push_back(pFilename);
  
  			pCurr += (length + 1);
  			length = wcslen(pCurr);
  		}
  
  		if (path)
  			delete[] path;

  	  if ((filesAdded - filesRemoved) != filenames.size())
  	  {
        LogDebug("MultiFileReader: expected file count incorrect") ;
  		  Error |= 0x200;
  	  }  	   
  
  		// Go through existing file list and new filename list
  		std::vector<MultiFileReaderFile *>::iterator itFiles = m_tsFiles.begin();
  		std::vector<LPWSTR>::iterator itFilenames = filenames.begin();
  
  		while ((itFiles < m_tsFiles.end()) && !Error)
  		{
  			file = *itFiles;
  
  			itFiles++;
  			fileID++;
  
  			if (itFilenames < filenames.end())
  			{
  				itFilenames++;
  			}
  			else
  			{
          LogDebug("MultiFileReader has missing files!!") ;
    		  Error |= 0x400;
  			}
  		}
  		  
  		//Add any new files to the m_tsFiles list i.e. itFilenames > itFiles
  		while ((itFilenames < filenames.end()) && !Error)
  		{
  			LPWSTR pFilename = *itFilenames;
  
  			file = new MultiFileReaderFile();
  			file->filename = pFilename;
  			file->startPosition = nextStartPosition;
  
    	  itFilenames++;
  			fileID++;
  			file->filePositionId = fileID;
    
        if (itFilenames == filenames.end()) //Latest file
        {
          //The 'currentPosition' value is the length of the latest file
          file->length = currentPosition;
          result = S_OK;
        }
        else
        {
          //'double check' the length of any older, closed files that have been added
  			  result = GetFileLength(pFilename, file->length, true);
        }
        
  		  if (!SUCCEEDED(result)) 
  		  {
		      Error |= 0x100;
		      delete file;
		    }
        else
        {
          //LogDebug("MultiFileReader: Update file list, filePositionId = %d, length = %d", file->filePositionId, file->length) ;          
    			m_tsFiles.push_back(file);   
    			m_filesAdded++;
    
    			nextStartPosition = file->startPosition + file->length;    
  		  }
  		}
  		
  	  if ((m_tsFiles.size() != filenames.size()) && !Error)
  	  {
        LogDebug("MultiFileReader: files to filenames mismatch") ;
  		  Error |= 0x800;
  	  }
  	      
  		if (!Error && m_bExtraLogging)
  		{
        LogDebug("MultiFileReader m_filesAdded : %d, m_filesRemoved : %d, file->startPosition : %I64d, currentPosition = %I64d, LatestFileID = %d", m_filesAdded, m_filesRemoved, file->startPosition, currentPosition, fileID) ;
  	  }
  	}

  } while ( Error && Loop ) ; // If Error is set, try again...until Loop reaches 0.
 
  if (Error)
  {
    LogDebug("MultiFileReader has failed for TSbuffer integrity after 10 tries. Error: %x:", Error) ;
    if (Error & ~0x7)  //Integrity errors
    {
      return E_FAIL ;
    }
    else  //File 'too short' errors (maybe nothing written to it yet)
    {
      return S_FALSE;
    }
  }


	if (m_tsFiles.size() > 0)
	{
		file = m_tsFiles.front();
		m_startPosition = file->startPosition;

		file = m_tsFiles.back();	
    file->length = currentPosition;
		m_endPosition = file->startPosition + currentPosition;	
	}
	else
	{
		m_startPosition = 0;
		m_endPosition = 0;
	}

	return S_OK;
}
Пример #30
0
/***********************************************************************
 *             GetVersionFromFileExW   (ADVPACK.@)
 *
 * Gets the files version or language information.
 *
 * PARAMS
 *   lpszFilename [I] The file to get the info from.
 *   pdwMSVer     [O] Major version.
 *   pdwLSVer     [O] Minor version.
 *   bVersion     [I] Whether to retrieve version or language info.
 *
 * RETURNS
 *   Always returns S_OK.
 *
 * NOTES
 *   If bVersion is TRUE, version information is retrieved, else
 *   pdwMSVer gets the language ID and pdwLSVer gets the codepage ID.
 */
HRESULT WINAPI GetVersionFromFileExW(LPCWSTR lpszFilename, LPDWORD pdwMSVer,
                                     LPDWORD pdwLSVer, BOOL bVersion )
{
    VS_FIXEDFILEINFO *pFixedVersionInfo;
    LANGANDCODEPAGE *pLangAndCodePage;
    DWORD dwHandle, dwInfoSize;
    WCHAR szWinDir[MAX_PATH];
    WCHAR szFile[MAX_PATH];
    LPVOID pVersionInfo = NULL;
    BOOL bFileCopied = FALSE;
    UINT uValueLen;

    static const WCHAR backslash[] = {'\\',0};
    static const WCHAR translation[] = {
        '\\','V','a','r','F','i','l','e','I','n','f','o',
        '\\','T','r','a','n','s','l','a','t','i','o','n',0
    };

    TRACE("(%s, %p, %p, %d)\n", debugstr_w(lpszFilename),
          pdwMSVer, pdwLSVer, bVersion);

    *pdwLSVer = 0;
    *pdwMSVer = 0;

    lstrcpynW(szFile, lpszFilename, MAX_PATH);

    dwInfoSize = GetFileVersionInfoSizeW(szFile, &dwHandle);
    if (!dwInfoSize)
    {
        /* check that the file exists */
        if (GetFileAttributesW(szFile) == INVALID_FILE_ATTRIBUTES)
            return S_OK;

        /* file exists, but won't be found by GetFileVersionInfoSize,
        * so copy it to the temp dir where it will be found.
        */
        GetWindowsDirectoryW(szWinDir, MAX_PATH);
        GetTempFileNameW(szWinDir, NULL, 0, szFile);
        CopyFileW(lpszFilename, szFile, FALSE);
        bFileCopied = TRUE;

        dwInfoSize = GetFileVersionInfoSizeW(szFile, &dwHandle);
        if (!dwInfoSize)
            goto done;
    }

    pVersionInfo = HeapAlloc(GetProcessHeap(), 0, dwInfoSize);
    if (!pVersionInfo)
        goto done;

    if (!GetFileVersionInfoW(szFile, dwHandle, dwInfoSize, pVersionInfo))
        goto done;

    if (bVersion)
    {
        if (!VerQueryValueW(pVersionInfo, backslash,
            (LPVOID *)&pFixedVersionInfo, &uValueLen))
            goto done;

        if (!uValueLen)
            goto done;

        *pdwMSVer = pFixedVersionInfo->dwFileVersionMS;
        *pdwLSVer = pFixedVersionInfo->dwFileVersionLS;
    }
    else
    {
        if (!VerQueryValueW(pVersionInfo, translation,
             (LPVOID *)&pLangAndCodePage, &uValueLen))
            goto done;

        if (!uValueLen)
            goto done;

        *pdwMSVer = pLangAndCodePage->wLanguage;
        *pdwLSVer = pLangAndCodePage->wCodePage;
    }

done:
    HeapFree(GetProcessHeap(), 0, pVersionInfo);

    if (bFileCopied)
        DeleteFileW(szFile);

    return S_OK;
}