Пример #1
0
static HRESULT CreateMap(const UStringVector &names,
    const UString &id,
    CFileMapping &fileMapping, NSynchronization::CManualResetEvent &event,
    UString &params)
{
  UInt32 extraSize = 2;
  UInt32 dataSize = 0;
  for (int i = 0; i < names.Size(); i++)
    dataSize += (names[i].Length() + 1) * sizeof(wchar_t);
  UInt32 totalSize = extraSize + dataSize;
  
  UString mappingName;
  
  CRandom random;
  random.Init(GetTickCount());
  for (;;)
  {
    int number = random.Generate();
    wchar_t temp[32];
    ConvertUInt64ToString(UInt32(number), temp);
    mappingName = id;
    mappingName += L"Mapping";
    mappingName += temp;
    if (!fileMapping.Create(INVALID_HANDLE_VALUE, NULL,
        PAGE_READWRITE, totalSize, GetSystemString(mappingName)))
      return E_FAIL;
    if (::GetLastError() != ERROR_ALREADY_EXISTS)
      break;
    fileMapping.Close();
  }
  
  UString eventName;
  RINOK(CreateTempEvent(id + L"MappingEndEvent", event, eventName));

  params += mappingName;
  params += L":";
  wchar_t string[10];
  ConvertUInt64ToString(totalSize, string);
  params += string;
  
  params += L":";
  params += eventName;

  LPVOID data = fileMapping.MapViewOfFile(FILE_MAP_WRITE, 0, totalSize);
  if (data == NULL)
    return E_FAIL;
  {
    wchar_t *curData = (wchar_t *)data;
    *curData = 0;
    curData++;
    for (int i = 0; i < names.Size(); i++)
    {
      const UString &s = names[i];
      memcpy(curData, (const wchar_t *)s, s.Length() * sizeof(wchar_t));
      curData += s.Length();
      *curData++ = L'\0';
    }
  }
  return S_OK;
}
Пример #2
0
static const char *ParseMapWithPaths(
    NWildcard::CCensor &censor,
    const UString &s2, bool include,
    NRecursedType::EEnum commonRecursedType,
    bool wildcardMatching)
{
  UString s = s2;
  int pos = s.Find(L':');
  if (pos < 0)
    return k_IncorrectMapCommand;
  int pos2 = s.Find(L':', pos + 1);
  if (pos2 < 0)
    return k_IncorrectMapCommand;

  CEventSetEnd eventSetEnd((const wchar_t *)s + ((unsigned)pos2 + 1));
  s.DeleteFrom(pos2);
  UInt32 size;
  if (!StringToUInt32(s.Ptr(pos + 1), size)
      || size < sizeof(wchar_t)
      || size > ((UInt32)1 << 31)
      || size % sizeof(wchar_t) != 0)
    return "Unsupported Map data size";

  s.DeleteFrom(pos);
  CFileMapping map;
  if (map.Open(FILE_MAP_READ, GetSystemString(s)) != 0)
    return "Can not open mapping";
  LPVOID data = map.Map(FILE_MAP_READ, 0, size);
  if (!data)
    return "MapViewOfFile error";
  CFileUnmapper unmapper(data);

  UString name;
  const wchar_t *p = (const wchar_t *)data;
  if (*p != 0) // data format marker
    return "Unsupported Map data";
  UInt32 numChars = size / sizeof(wchar_t);
  for (UInt32 i = 1; i < numChars; i++)
  {
    wchar_t c = p[i];
    if (c == 0)
    {
      // MessageBoxW(0, name, L"7-Zip", 0);
      AddNameToCensor(censor, name, include, commonRecursedType, wildcardMatching);
      name.Empty();
    }
    else
      name += c;
  }
  if (!name.IsEmpty())
    return "Map data error";

  return NULL;
}
Пример #3
0
template<class T, USHORT default_port> BOOL CHttpAgentT<T, default_port>::SendLocalFile(CONNID dwConnID, LPCSTR lpszFileName, LPCSTR lpszMethod, LPCSTR lpszPath, const THeader lpHeaders[], int iHeaderCount)
{
	CFile file;
	CFileMapping fmap;

	HRESULT hr = ::ReadSmallFile(CA2T(lpszFileName), file, fmap);

	if(FAILED(hr))
	{
		::SetLastError(hr);
		return FALSE;
	}

	return SendRequest(dwConnID, lpszMethod, lpszPath, lpHeaders, iHeaderCount, (BYTE*)fmap, (int)fmap.Size());
}
Пример #4
0
int _tmain(int argc, _TCHAR* argv[])
{
	if (argc < 3) {
		_tprintf(_T("Usage: rf <source file/disk path> <desnitantion folder/file>\nFor disk use \\\\.\\H: as source path"));
		return -1;
	}
	HANDLE hFile = CreateFile(argv[1], GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
	if (hFile != INVALID_HANDLE_VALUE) {
		UINT64 currentDone(0), totalSize(0);
		LARGE_INTEGER fileSize = {0};
		GetFileSizeEx(hFile, &fileSize);
		totalSize = fileSize.QuadPart;
		if (totalSize == 0) { // Disk Path
			ULARGE_INTEGER li = {0};
			GetDiskFreeSpaceEx(argv[1]+4, NULL, &li, NULL);
			totalSize = li.QuadPart;
		}
		Progress progress;
		progress.SetTask(totalSize);
		ConsoleProgress cp;
		Path dstPath(argv[2]);
		auto updateWSTime = ProcessUtil::GetTickCount(); // Update Writing speed time
		lprintf(_T("\nTime Elapsed: "));
		CountTimer timeElapsed;
		lprintf(_T("\t\t\t\tTime Remaining: "));
		CountTimer timeRemaining(true);
		if (dstPath.IsDir()) {
            CRecoverManager recoverManger;
            recoverManger.SetInputFileHandle(hFile);
            recoverManger.SetSavePath(dstPath);
            recoverManger.SetTotal(totalSize);
            recoverManger.Initialize();
            recoverManger.BeginRecover();
			while (recoverManger.ProcessRecover()) {
                currentDone = recoverManger.GetCurrentDone();
				if (progress.UpdateProgress(currentDone))
					cp.ShowPercentage(progress.GetCurrentPercentageDone());
				auto curTime = ProcessUtil::GetTickCount();
				if (curTime - updateWSTime >= 5000) { // 5 secs passed
					timeRemaining.SetTimeDuration((timeElapsed.GetTimeDuration() * totalSize) / currentDone);
					updateWSTime = curTime;
				}
				timeElapsed.PrintTimeDuration();
				timeRemaining.PrintTimeDuration();
			}
            if (progress.UpdateProgress(currentDone))
                cp.ShowPercentage(progress.GetCurrentPercentageDone());
            recoverManger.EndRecover();
            progress.UpdateProgress(totalSize);
            cp.ShowPercentage(progress.GetCurrentPercentageDone());
        }
		else {
			CFileMapping fileDstMap;
			CFileMapping fileSrcMap;
			//fileSrcMap.GetFileMapping(hFile);
			fileSrcMap.SetFileHandle(hFile);
			//HANDLE hDestFile = CreateFile(argv[2], GENERIC_ALL, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL);
			//if (hDestFile != INVALID_HANDLE_VALUE) {
			//	fileDstMap.SetFileHandle(hDestFile);
			if (fileDstMap.GetFileMapping(argv[2], totalSize) != NULL) {
				std::vector<char> buffer;
				buffer.resize(1024*1024);
				size_t size = buffer.size();
				char *buf = &buffer[0];
				while (currentDone < totalSize) {
					DWORD nBytesRead(fileSrcMap.Read(buf, (UINT)size));
					if (nBytesRead > 0) {
						fileDstMap.Write(buf, nBytesRead);
						currentDone += nBytesRead;
						if (progress.UpdateProgress(currentDone))
							cp.ShowPercentage(progress.GetCurrentPercentageDone());
						auto curTime = ProcessUtil::GetTickCount();
						if (curTime - updateWSTime >= 5000) { // 5 secs passed
							double p = progress.GetCurrentPercentageDone();
							if (p < 0.01)
								p = 0.01;
							timeRemaining.SetTimeDuration(__int64((timeElapsed.GetTimeDuration() * (100-p)) / p));
							updateWSTime = curTime;
						}
						timeElapsed.PrintTimeDuration();
						timeRemaining.PrintTimeDuration();
					}
					else break;
				}
				//CloseHandle(hDestFile);
			}
			else _tprintf(_T("Cannot open file: '%s'\nError: %d"), argv[2], GetLastError());
		}
		CloseHandle(hFile);
	}
    else {
        bool bError(true);
        if (GetLastError() == ERROR_ACCESS_DENIED)
            bError = !ProcessUtil::RunApplication(argc, (LPCTSTR*)argv, RAF_ADMIN);
        if (bError)
            _tprintf(_T("Cannot open file: '%s'\nError: %d"), argv[1], GetLastError());
    }
	return 0;
}
static HRESULT CreateMap(const UStringVector &names,
    CFileMapping &fileMapping, NSynchronization::CManualResetEvent &event,
    UString &params)
{
  size_t totalSize = 1;
  {
    FOR_VECTOR (i, names)
      totalSize += (names[i].Len() + 1);
  }
  totalSize *= sizeof(wchar_t);
  
  CRandNameGenerator random;

  UString mappingName;
  for (;;)
  {
    random.GenerateName(mappingName, "7zMap");

    WRes res = fileMapping.Create(PAGE_READWRITE, totalSize, GetSystemString(mappingName));
    if (fileMapping.IsCreated() && res == 0)
      break;
    if (res != ERROR_ALREADY_EXISTS)
      return res;
    fileMapping.Close();
  }
  
  UString eventName;
  for (;;)
  {
    random.GenerateName(eventName, "7zEvent");
    WRes res = event.CreateWithName(false, GetSystemString(eventName));
    if (event.IsCreated() && res == 0)
      break;
    if (res != ERROR_ALREADY_EXISTS)
      return res;
    event.Close();
  }

  params += L'#';
  params += mappingName;
  params += L':';
  char temp[32];
  ConvertUInt64ToString(totalSize, temp);
  params.AddAscii(temp);
  
  params += L':';
  params += eventName;

  LPVOID data = fileMapping.Map(FILE_MAP_WRITE, 0, totalSize);
  if (!data)
    return E_FAIL;
  CFileUnmapper unmapper(data);
  {
    wchar_t *cur = (wchar_t *)data;
    *cur++ = 0; // it means wchar_t strings (UTF-16 in WIN32)
    FOR_VECTOR (i, names)
    {
      const UString &s = names[i];
      unsigned len = s.Len() + 1;
      wmemcpy(cur, (const wchar_t *)s, len);
      cur += len;
    }
  }
  return S_OK;
}
static void ParseMapWithPaths(NWildcard::CCensor &wildcardCensor,
    const UString &switchParam, bool include,
    NRecursedType::EEnum commonRecursedType)
{
  int splitPos = switchParam.Find(L':');
  if (splitPos < 0)
    ThrowUserErrorException();
  UString mappingName = switchParam.Left(splitPos);
  
  UString switchParam2 = switchParam.Mid(splitPos + 1);
  splitPos = switchParam2.Find(L':');
  if (splitPos < 0)
    ThrowUserErrorException();
  
  UString mappingSize = switchParam2.Left(splitPos);
  UString eventName = switchParam2.Mid(splitPos + 1);
  
  UInt64 dataSize64 = ConvertStringToUInt64(mappingSize, NULL);
  UInt32 dataSize = (UInt32)dataSize64;
  {
    CFileMapping fileMapping;
    if (fileMapping.Open(FILE_MAP_READ, GetSystemString(mappingName)) != 0)
      ThrowException("Can not open mapping");
    LPVOID data = fileMapping.Map(FILE_MAP_READ, 0, dataSize);
    if (data == NULL)
      ThrowException("MapViewOfFile error");
    try
    {
      const wchar_t *curData = (const wchar_t *)data;
      if (*curData != 0)
        ThrowException("Incorrect mapping data");
      UInt32 numChars = dataSize / sizeof(wchar_t);
      UString name;
      for (UInt32 i = 1; i < numChars; i++)
      {
        wchar_t c = curData[i];
        if (c == L'\0')
        {
          AddNameToCensor(wildcardCensor, name, include, commonRecursedType);
          name.Empty();
        }
        else
          name += c;
      }
      if (!name.IsEmpty())
        ThrowException("data error");
    }
    catch(...)
    {
      UnmapViewOfFile(data);
      throw;
    }
    UnmapViewOfFile(data);
  }
  
  {
    NSynchronization::CManualResetEvent event;
    if (event.Open(EVENT_MODIFY_STATE, false, GetSystemString(eventName)) == S_OK)
      event.Set();
  }
}
Пример #7
0
bool COverlaySurfaceCache::CaptureFromSharedMemory(HDC hdc,LPCRECT prcDest)
{
	
	if(prcDest ==0 ) return false;

	static CFileMapping shared_flags;
	//1.create filemapping object for sharing memory  
	if(!shared_flags.IsOpen())
	{
		if(!shared_flags.Open(kFlagsShareMemory,sizeof(DWORD),false ))
		{
			DebugOutF(filelog::log_error,"open shared_flags failed,could not open shared memory");
			return false;
		}
	}
	DWORD *pFlags = (DWORD *)shared_flags.GetPointer();
	if(*pFlags == 0) return false;
	TrackDebugOut;
	static LONG tick = GetTickCount();//make sure that message HWND_BROADCAST will be handle once.

	static CFileMapping mem;
	//1.create filemapping object for sharing memory  
	if(!mem.IsOpen())
	{
		if(!mem.Open(kChaptureOverlayShareMemory,sizeof(SURFACE_DATA),true ))
		{
			DebugOutF(filelog::log_error,"CaptureFromSharedMemory failed,could not open shared memory");
			return false;
		}
		//2.Notify processes which using DirectDaw overlay.
		SURFACE_DATA*pDate = static_cast<SURFACE_DATA*>( mem.GetPointer());
		pDate->modified = FALSE;
		SendMessageTimeout(HWND_BROADCAST,CAPTURE_SCREEN,++tick,0,SMTO_ABORTIFHUNG,10000,0);
		if(!pDate->modified)
		{
			DebugOutF(filelog::log_debug,"no overlay alive");
			return false;
		}
	}
	// resize shared memory if necessarily  
	int i = 0;
	for(i=0;i<3;++i)
	{
		SURFACE_DATA*pDate = static_cast<SURFACE_DATA*>( mem.GetPointer());
		if(pDate->size + sizeof(SURFACE_DATA ) > mem.GetSize() )
		{
			if(!mem.Open(kChaptureOverlayShareMemory,pDate->size + sizeof(SURFACE_DATA ),true ))
			{
				DebugOutF(filelog::log_error,"CaptureFromSharedMemory failed,could not open shared memory");
				return false;
			}
			pDate = static_cast<SURFACE_DATA*>( mem.GetPointer());
		}
		//Notify processes which using DirectDaw overlay.
		pDate->modified = FALSE;
		SendMessageTimeout(HWND_BROADCAST,CAPTURE_SCREEN,++tick,0,SMTO_ABORTIFHUNG,10000,0);
		if(!pDate->modified ) 
		{
			DebugOutF(filelog::log_debug,"no overlay alive");
			return false;
		}
		if(pDate->size + sizeof(SURFACE_DATA ) > mem.GetSize() ) continue;
		break;
	}
	/*return false;*/
	if(i == 3) return false;
	CAutoLockEx<CMutexLock> lock(g_mLock);
	//open and get the size of shared memory
	//CFileMapping mem;
// 	if(!mem.Open(kChaptureOverlayShareMemory,sizeof(SURFACE_DATA),false))
// 	{
// 		DebugOutF(filelog::log_error,"CaptureFromSharedMemory failed,could not open shared memory");
// 		return false;
// 	}
// 	SURFACE_DATA* pData = (SURFACE_DATA*)mem.GetPointer();
// 	DWORD size = pData->size;
// 	mem.Destroy();
// 	if(size < sizeof(SURFACE_DATA)) return false;
// 	// then get open again with the size
// 	if(!mem.Open(kChaptureOverlayShareMemory,size,false))
// 	{
// 		DebugOutF(filelog::log_error,"CaptureFromSharedMemory failed,could not open shared memory as size %d",size);
// 		return false;
// 	}

	SURFACE_DATA*pData = (SURFACE_DATA*)mem.GetPointer();
	// the area to be copy
	RECT dest ={0},src={0},intersect={0};
	if(IsRectEmpty(&pData->rcDst)) 
	{
		DebugOutF(filelog::log_debug,"CaptureFromSharedMemory dest rect is empty");
		return true;
	}
	IntersectRect(&intersect,prcDest,&pData->rcDst);
	if(IsRectEmpty(&intersect)) 
	{
		DebugOutF(filelog::log_debug,"CaptureFromSharedMemory dest rect is empty");
		return true;
	}

	HRGN hrgn = 0;
	HBITMAP hBmp = 0;
	HDC hMemDC = 0;

	dest.left = intersect.left - prcDest->left;
	dest.top = intersect.top - prcDest->top;
	int w = intersect.right-intersect.left;
	int h = intersect.bottom-intersect.top;
	dest.right = dest.left +w;
	dest.bottom = dest.top +h;

	src.left = (intersect.left - pData->rcDst.left)*pData->desc.dwWidth/(pData->rcDst.right-pData->rcDst.left);
	src.top = (intersect .top -pData->rcDst.top)*pData->desc.dwHeight/(pData->rcDst.bottom-pData->rcDst.top);
	w = w*pData->desc.dwWidth/(pData->rcDst.right-pData->rcDst.left);
	h = h*pData->desc.dwHeight/(pData->rcDst.bottom-pData->rcDst.top);
	src.right = src.left +w;
	src.bottom = src.top +h;


	bool bOK = true;
	try
	{

		if (pData->desc.ddpfPixelFormat.dwFlags & DDPF_FOURCC)
		{
			DebugOutF(filelog::log_error,"unsupport color space 0x%x",pData->desc.ddpfPixelFormat.dwFourCC);
			throw false;
		}
// 		if(pData->rdh.nCount )
// 		{
// 			hrgn = ExtCreateRegion(0,pData->rdh.nRgnSize,(RGNDATA*)&pData->rdh);
// 			if(prcDest) OffsetRgn(hrgn,-prcDest->left,-prcDest->top);
// 			SelectClipRgn(hdc,hrgn);
// 		}
		{
			BITMAPINFOHEADER infhead ;
			ZeroMemory(&infhead,sizeof(infhead));

			infhead.biSize = sizeof(BITMAPINFOHEADER);

			infhead.biBitCount = (WORD)pData->desc.ddpfPixelFormat.dwRGBBitCount;

			int imagesize =  pData->desc.lPitch* pData->desc.dwHeight;

			infhead.biPlanes	= 1;
			infhead.biHeight	= -LONG(pData->desc.dwHeight);
			infhead.biWidth		= pData->desc.dwWidth;
			infhead.biSizeImage	= imagesize ;
			infhead.biCompression = BI_RGB;
			hMemDC  = CreateCompatibleDC(hdc);

			if(hMemDC == NULL){
				DebugOutF(filelog::log_error,"CreateCompatibleDC failed with %d",GetLastError());
				throw false;
			}


			{
				hBmp = CreateDIBSection(hMemDC,
					(BITMAPINFO *)&infhead,
					DIB_RGB_COLORS, 0,mem.GetHandle(), FIELD_OFFSET(SURFACE_DATA,data) + (pData->rdh.nRgnSize?pData->rdh.nRgnSize-sizeof(RGNDATAHEADER):0));

				if(hBmp == NULL){
					DebugOutF(filelog::log_error,"CreateDIBSection failed with %d",GetLastError() );
					throw false;
				}
			}

			SelectObject(hMemDC,hBmp);

			if (((dest.right-dest.left) == (src.right-src.left)) &&
				((dest.bottom-dest.top) == (src.bottom-src.top))
				)
			{
				if(!BitBlt( hdc,
					dest.left,
					dest.top,
					dest.right-dest.left,
					dest.bottom-dest.top,
					hMemDC,
					src.left,
					src.top,
					SRCCOPY))
				{
					DebugOutF( filelog::log_error,"StretchBlt failed with %d",GetLastError() );
					throw false;
				}
			}
			else
			{
				if(!StretchBlt (hdc,
					dest.left,
					dest.top,
					dest.right-dest.left,
					dest.bottom-dest.top,
					hMemDC,
					src.left,
					src.top,
					src.right-src.left,
					src.bottom-src.top,
					SRCCOPY))
				{
					DebugOutF(filelog::log_error,"StretchBlt failed with %d",GetLastError());
					throw false;
				}
			}

// 			DebugOutF(filelog::log_info,"CaptureFromSharedMemory (w:%d,h:%d,FourCC:0x%x,RGBBitCount:%d,l:%d,t:%d,r:%d,b:%d)ok",
// 				pData->desc.dwWidth,
// 				pData->desc.dwHeight,
// 				pData->desc.ddpfPixelFormat.dwFourCC,
// 				pData->desc.ddpfPixelFormat.dwRGBBitCount,
// 				pData->rcDst.left,
// 				pData->rcDst.top,
// 				pData->rcDst.right,
// 				pData->rcDst.bottom
// 				);
			//return true;


		}

	}
	catch (bool b1)
	{
		bOK = b1;
	}

	if(hMemDC)DeleteDC(hMemDC);
	if(hBmp)DeleteObject(hBmp);
	if(hrgn)DeleteObject(hrgn);
	DebugOutF(filelog::log_debug,"CaptureFromSharedMemory ok");
	return bOK;
}
Пример #8
0
bool COverlaySurfaceCache::CopyToSharedMemory(IDirectDraw7*pDDraw,const OVERLAY_ITEM& item)
{
	CAutoLockEx<CMutexLock> lock(g_mLock);
	
	if( !item.pOverlay ) return false;

	DumpSurface(item.pOverlay,_T("DumpSurface1.temp"));
	CComPtr<IDirectDrawSurface7> pTemp = CopyToOffscreenSurface(pDDraw,item);
	DumpSurface(pTemp,_T("DumpSurface2.temp"));
	if(!pTemp) 
	{
		OutputDebugStringA("CopyToOffscreenSurface failed");
		return false;
	}

	HRESULT hr=S_OK;
	DDSURFACEDESC2 ddsd_dest = {0};
	ddsd_dest.dwSize = sizeof(DDSURFACEDESC2);

	hr = pTemp->Lock(0,&ddsd_dest,DDLOCK_READONLY|DDLOCK_DONOTWAIT,0);
	if (FAILED(hr))
	{
		OutputDebugStringA("IDirectDrawSurface7::Lock failed");
		pTemp->Unlock(0);
		return false;
	}
	try
	{
		DWORD rgnsize = 0;
// 		CComPtr<IDirectDrawClipper> pClipper;
// 		if(SUCCEEDED(item.pOverlay->GetClipper(&pClipper)))
// 		{
// 			pClipper->GetClipList(0,0,&rgnsize);
// 		}

		DWORD size;
		DWORD imagesize ;


		imagesize = CalculatePitch(CalculateLine(ddsd_dest.dwWidth,ddsd_dest.ddpfPixelFormat.dwRGBBitCount)) * ddsd_dest.dwHeight;
		size = FIELD_OFFSET(SURFACE_DATA,data) + (rgnsize?rgnsize-sizeof(RGNDATAHEADER):0) + imagesize;


		CFileMapping mem;
		if(!mem.Open(kChaptureOverlayShareMemory,size,false))
		{
			// open failed ,maybe size is too small
			if(mem.Open(kChaptureOverlayShareMemory,sizeof(SURFACE_DATA),false))
			{
				SURFACE_DATA*pData = (SURFACE_DATA*)mem.GetPointer();
				pData->size = size;
				pData->desc = ddsd_dest;
				pData->modified = TRUE;
			}
			OutputDebugStringA("CFileMappingBitmap::Open failed");
			throw E_FAIL;
		}
		SURFACE_DATA*pData = (SURFACE_DATA*)mem.GetPointer();
		pData->size = size;
		pData->desc = ddsd_dest;
		pData->modified = TRUE;
// 		if(pClipper && rgnsize)
// 		{
// 			if(FAILED(pClipper->GetClipList(0,(LPRGNDATA)&pData->rdh,&rgnsize)))
// 			{
// 				OutputDebugStringA("IDirectDrawSurface7::GetClipList failed");
// 				throw E_FAIL;
// 			}
// 		}

// 		if(item.bEntireDest)
// 		{
// 			DDSURFACEDESC2 des = {0};
// 			des.dwSize = sizeof(DDSURFACEDESC2);
// 			if(FAILED(pPrimary->GetSurfaceDesc(&des)))
// 			{
// 				OutputDebugStringA("IDirectDrawSurface7::GetSurfaceDesc failed");
// 				throw E_FAIL;
// 			}
// 			pData->rcDst.left = pData->rcDst.top = 0;
// 			pData->rcDst.right = des.dwWidth;
// 			pData->rcDst.bottom = des.dwHeight;
// 		}
// 		else
			pData->rcDst = item.rcDst;

		pData->flags= item.flags; 
		pData->fx = item.fx;

		BYTE *pBegin = pData->data + (rgnsize?rgnsize-sizeof(RGNDATAHEADER):0);
		pData->desc.lPitch = CalculatePitch(CalculateLine(ddsd_dest.dwWidth,ddsd_dest.ddpfPixelFormat.dwRGBBitCount));
		//int left ;
		//left = CalculatePitch(CalculateLine(item.rcDst.left,ddsd_dest.ddpfPixelFormat.dwRGBBitCount));

		for (int i= 0;i != ddsd_dest.dwHeight;i++)
		{
			memcpy( pBegin + i *  pData->desc.lPitch ,
				(BYTE*)ddsd_dest.lpSurface + i*ddsd_dest.lPitch ,
				pData->desc.lPitch);
		}

// 		DebugOutF(filelog::log_info,"CopyToSharedMemory (%d,%d,%d,%d) -> (%d,%d,%d,%d) ok",
// 			item.rcSrc.left,
// 			item.rcSrc.top,
// 			item.rcSrc.right,
// 			item.rcSrc.bottom,
// 			item.rcDst.left,
// 			item.rcDst.top,
// 			item.rcDst.right,
// 			item.rcDst.bottom);
	}
	catch(HRESULT hr1)
	{
		hr = hr1;
	}
	pTemp->Unlock(0);
	return SUCCEEDED(hr);
}
Пример #9
0
HRESULT CompressFiles(
    const UString &curDir,
    const UString &archiveName,
    const UString &archiveType,
    const UStringVector &names,
    // const UString &outFolder,
    bool email,
    bool showDialog,
    bool waitFinish)
{
  /*
  UString curDir;
  if (names.Size() > 0)
  {
    NFile::NDirectory::GetOnlyDirPrefix(names[0], curDir);
  }
  */
  UString params;
  params = Get7zGuiPath();
  params += L" a";
  params += kMapSwitch;
  // params += _fileNames[0];
  
  UInt32 extraSize = 2;
  UInt32 dataSize = 0;
  for (int i = 0; i < names.Size(); i++)
    dataSize += (names[i].Length() + 1) * sizeof(wchar_t);
  UInt32 totalSize = extraSize + dataSize;
  
  UString mappingName;
  
  CFileMapping fileMapping;
  CRandom random;
  random.Init(GetTickCount());
  for (;;)
  {
    int number = random.Generate();
    wchar_t temp[32];
    ConvertUInt64ToString(UInt32(number), temp);
    mappingName = L"7zCompressMapping";
    mappingName += temp;
    if (!fileMapping.Create(INVALID_HANDLE_VALUE, NULL,
      PAGE_READWRITE, totalSize, GetSystemString(mappingName)))
    {
      // MyMessageBox(IDS_ERROR, 0x02000605);
      return E_FAIL;
    }
    if (::GetLastError() != ERROR_ALREADY_EXISTS)
      break;
    fileMapping.Close();
  }
  
  NSynchronization::CManualResetEvent event;
  UString eventName;
  RINOK(CreateTempEvent(L"7zCompressMappingEndEvent", event, eventName));

  params += mappingName;
  params += L":";
  wchar_t string[10];
  ConvertUInt64ToString(totalSize, string);
  params += string;
  
  params += L":";
  params += eventName;

  if (!archiveType.IsEmpty())
  {
    params += kArchiveTypeSwitch;
    params += archiveType;
  }

  if (email)
    params += kEmailSwitch;

  if (showDialog)
    params += kShowDialogSwitch;

  AddLagePagesSwitch(params);

  params += kStopSwitchParsing;
  params += L" ";
  
  params += GetQuotedString(archiveName);
  
  LPVOID data = fileMapping.MapViewOfFile(FILE_MAP_WRITE, 0, totalSize);
  if (data == NULL)
  {
    // MyMessageBox(IDS_ERROR, 0x02000605);
    return E_FAIL;
  }
  try
  {
    wchar_t *curData = (wchar_t *)data;
    *curData = 0;
    curData++;
    for (int i = 0; i < names.Size(); i++)
    {
      const UString &unicodeString = names[i];
      memcpy(curData, (const wchar_t *)unicodeString ,
        unicodeString .Length() * sizeof(wchar_t));
      curData += unicodeString.Length();
      *curData++ = L'\0';
    }
    // MessageBox(0, params, 0, 0);
    RINOK(MyCreateProcess(params,
      (curDir.IsEmpty()? 0: (LPCWSTR)curDir),
      waitFinish, &event));
  }
  catch(...)
  {
    UnmapViewOfFile(data);
    throw;
  }
  UnmapViewOfFile(data);
  

  /*
  CThreadCompressMain *compressor = new CThreadCompressMain();;
  compressor->FileNames = _fileNames;
  CThread thread;
  if (!thread.Create(CThreadCompressMain::MyThreadFunction, compressor))
  throw 271824;
  */
  return S_OK;
}
Пример #10
0
LRESULT CTestDlg::OnBnClickedButton3(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	if (m_pService == 0)
	{
		MessageBox(_T("m_pService ==0 "));
		return 0;
	}
	HRESULT hr = S_OK;

	CComPtr<IUnknown>pUnk;
	hr = m_pService->GetActiveConsoleSession(&pUnk);

	if( FAILED(hr) )
	{
		MessageBox(_T("GetActiveConsoleSession failed"));
		return 0;
	}

	CComQIPtr<IWinRobotSession> pSession = pUnk;

	if (!pSession)
	{
		MessageBox(_T("pSession ==0"));
		return 0;
	}
	DWORD start = GetTickCount();
	float count = 1.0;
	for (int i=0;i<count;i++)
	{
		pUnk = 0;
		if(FAILED(hr = pSession->CreateScreenCapture(-1280,0,1280*2,800,&pUnk)))
		{
			TCHAR buf[1024] = {0};
			_stprintf(buf,_T("CreateScreenCapture failed with 0x%x"),hr);
			MessageBox(buf);
			return 0;
		}

		CComQIPtr<IScreenBufferStream> pStream = pUnk;
		CComBSTR name;
		pStream->get_FileMappingName(&name);
		ULONG size = 0;
		pStream->get_Size(&size);
		CFileMapping fm;
		fm.Open(name,size,false);
	}
 	DWORD spend = GetTickCount()-start;
 	TCHAR buff[1034];
 	_stprintf(buff,_T("%f"),count*1000.0/spend);
 //	MessageBox(buff);
	//return 0;
	CComQIPtr<ISequentialStream> pStream = pUnk;

	_ASSERT(pStream);
	bool bRtn = true;
	HANDLE hf = INVALID_HANDLE_VALUE;
	try
	{
		hf = CreateFile(_T("c:\\test.bmp"), 
			GENERIC_READ | GENERIC_WRITE, 
			(DWORD) 0, 
			NULL, 
			CREATE_ALWAYS, 
			FILE_ATTRIBUTE_NORMAL, 
			(HANDLE) NULL); 

		if (hf == INVALID_HANDLE_VALUE) 
		{ 
			throw false;
		}
		char buf[1024];
		ULONG cbBuffer  = 0 ;
		
		while (pStream->Read(buf,sizeof(buf),&cbBuffer) == S_OK )
		{
			DWORD cbWrite = 0;
			if (!WriteFile(hf, buf, cbBuffer, &cbWrite,  NULL)) 
			{
				throw false;
			}
		}
	}
	catch(bool b1)
	{
		bRtn = b1;
	}
	CloseHandle(hf);
	//_ASSERT(bRtn);
	return 0;
}