Exemple #1
0
HostFile::HostFile(tchar_t const* path, uint32_t access, uint32_t share, uint32_t flags)
{
	if(!path || !(*path)) throw Win32Exception(ERROR_INVALID_PARAMETER);

	m_handle = CreateFile(path, access, share, NULL, OPEN_EXISTING, flags, NULL);
	if(m_handle == INVALID_HANDLE_VALUE) throw Win32Exception();
}
Exemple #2
0
std::wstring Settings::DoGetVerInfoField(const wchar_t *field, bool fatal)
{
    TCHAR exeFilename[MAX_PATH + 1];

    if ( !GetModuleFileName(NULL, exeFilename, MAX_PATH) )
        throw Win32Exception();

    DWORD unusedHandle;
    DWORD fiSize = GetFileVersionInfoSize(exeFilename, &unusedHandle);
    if ( fiSize == 0 )
        throw Win32Exception("Executable doesn't have the required VERSIONINFO resource");

    DataBuffer fi(fiSize);

    if ( !GetFileVersionInfo(exeFilename, unusedHandle, fiSize, fi.data) )
        throw Win32Exception();

    const std::wstring key =
        TEXT("\\StringFileInfo\\") + GetVerInfoLang(fi.data) + TEXT("\\") + field;
    LPTSTR key_str = (LPTSTR)key.c_str(); // explicit cast to work around VC2005 bug

    TCHAR *value;
    UINT len;
    if ( !VerQueryValue(fi.data, key_str, (LPVOID*)&value, &len) )
    {
        if ( fatal )
            throw Win32Exception("Executable doesn't have required key in StringFileInfo");
        else
            return std::wstring();
    }

    return value;
}
Exemple #3
0
std::tstring Console::ReadLine(void)
{
	std::vector<tchar_t>	accumulator;			// Character accumulator
	DWORD					mode = 0;				// Original console mode
	DWORD					read = 0;				// Characters read from the console
	tchar_t					next;					// Next character read from console

	// Prevent multiple threads from reading the console at the same time
	std::lock_guard<std::recursive_mutex> lock(m_readlock);

	// Ensure LINE_INPUT and ECHO_INPUT are enabled for the input mode
	if(!GetConsoleMode(m_stdin, &mode)) throw Win32Exception();
	if(!SetConsoleMode(m_stdin, mode | ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT)) throw Win32Exception();

	try {

		// Repeatedly read characters from the console until CR has been detected
		if(!ReadConsole(m_stdin, &next, 1, &read, nullptr)) throw Win32Exception();
		while(next != _T('\n')) { 
		
			if(next != _T('\r')) accumulator.push_back(next); 
			if(!ReadConsole(m_stdin, &next, 1, &read, nullptr)) throw Win32Exception();
		}
	}

	// Be sure the restore the original console mode flags on any exception
	catch(...) { SetConsoleMode(m_stdin, mode); throw; }

	// Restore the previously set input mode flags
	SetConsoleMode(m_stdin, mode);

	// Convert the accumulated character data as a tstring instance
	return std::tstring(accumulator.data(), accumulator.size());
}
   /// <summary>Initializes the property grid.</summary>
   /// <returns></returns>
   BOOL PreferencesPage::OnInitDialog()
   {
      try
      {
         // Create base
	      if (!__super::OnInitDialog())
		      throw Win32Exception(HERE, L"Failed to create dialog base");

	      ClientRect wnd(this);

         // Create property grid
	      if (!Grid.Create(WS_VISIBLE | WS_CHILD, wnd, this, IDC_PROPERTY_GRID))
	         throw Win32Exception(HERE, L"Failed to create Properties Grid");

	      // Grid
         Grid.EnableHeaderCtrl(FALSE);
	      Grid.EnableDescriptionArea();
	      Grid.SetVSDotNetLook();
	      Grid.MarkModifiedProperties();

         // Adjust layout
         AdjustLayout();

         // Populate grid
         Populate();
	      return TRUE;
      }
      catch (ExceptionBase& e) {
         Console.Log(HERE, e);
         return FALSE;
      }
   }
Exemple #5
0
void Console::putTreatControlCAsInput(bool value) const
{
	DWORD mode = 0;
	if(!GetConsoleMode(m_stdin, &mode)) throw Win32Exception();

	// Set or clear ENABLED_PROCESSED_INPUT from the bitmask returned
	if(!SetConsoleMode(m_stdin, (value) ? mode | ENABLE_PROCESSED_INPUT : 
		mode & ~ENABLE_PROCESSED_INPUT)) throw Win32Exception();
}
Exemple #6
0
   /// <summary>Create temporary file path</summary>
   /// <param name="prefix">three letter filename prefix</param>
   /// <exception cref="Logic::Win32Exception">API function failed</exception>
   TempPath::TempPath(const wchar* prefix)
   {
      Path folder;

      // Get temp folder
      if (!GetTempPath(MAX_PATH, (wchar*)folder))
         throw Win32Exception(HERE, L"Unable to get temp folder");
            
      // Generate filename
      if (!GetTempFileName(folder.c_str(), prefix, NULL, Buffer.get()))
         throw Win32Exception(HERE, L"Unable to generate temporary filename");
   }
Exemple #7
0
	void Window::SetClientArea(INT clientX, INT clientY)
	{
		RECT windowRect;
		::SetRect(&windowRect, 0, 0, clientX, clientY);

		BOOL bIsMenu = (::GetMenu(hwnd) != NULL);
		if (!::AdjustWindowRectEx(&windowRect, style, bIsMenu, exStyle))
			throw Win32Exception(::GetLastError());

		if (!::SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top, SWP_NOMOVE))
			throw Win32Exception(::GetLastError());
	}
Exemple #8
0
TransactedFileSink::TransactedFileSink(const KernelTransaction &tx, const wchar_t *path){
	this->handle.reset(new HANDLE(nullptr), [](HANDLE *h){ CloseHandle(*h); delete h; });
	static const DWORD open_modes[] = {
		OPEN_EXISTING,
		CREATE_ALWAYS,
	};
	static USHORT TXFS_MINIVERSION_DEFAULT_VIEW = 0xFFFE;
	for (auto m : open_modes){
		*this->handle = CreateFileTransactedW(
			path,
			GENERIC_WRITE,
			0,
			nullptr,
			m,
			0,
			nullptr,
			tx.get_handle(),
			&TXFS_MINIVERSION_DEFAULT_VIEW,
			nullptr
		);
		if (*this->handle != INVALID_HANDLE_VALUE)
			break;
	}
	if (*this->handle == INVALID_HANDLE_VALUE){
		auto error = GetLastError();
		throw Win32Exception(error);
	}
	SetFilePointer(*this->handle, 0, 0, FILE_END);
}
Exemple #9
0
KernelTransaction::KernelTransaction(){
	this->tx = CreateTransaction(nullptr, 0, 0, 0, 0, 0, nullptr);
	if (this->tx == INVALID_HANDLE_VALUE){
		auto error = GetLastError();
		throw Win32Exception(error);
	}
}
Exemple #10
0
	void Window::SetExtendedStyle(DWORD newExStyle)
	{
		if (!::SetWindowLongPtr(hwnd, GWL_EXSTYLE, newExStyle))
			throw Win32Exception(::GetLastError());

		exStyle = newExStyle;
	}
Exemple #11
0
	void Window::SetWindowStyle(DWORD newStyle)
	{
		if (!::SetWindowLongPtr(hwnd, GWL_STYLE, newStyle))
			throw Win32Exception(::GetLastError());

		style = newStyle;
	}
Exemple #12
0
	Window::Window(EngineState* state,
		HINSTANCE hinstance,
		LPCWSTR name,
		DWORD style,
		DWORD exStyle,
		LPCWSTR iconResource,
		LPCWSTR smallIconResource,
		LPCWSTR menuResource,
		LPCWSTR accelResource) : style(style),
		exStyle(exStyle),
		appName(name),
		hinstance(hinstance),
		hwnd(NULL)
	{
		if (hinstance == NULL)
			this->hinstance = GetModuleHandle(NULL);

		INITCOMMONCONTROLSEX cce;
		cce.dwSize = sizeof(INITCOMMONCONTROLSEX);
		cce.dwICC = ICC_BAR_CLASSES | ICC_COOL_CLASSES | ICC_STANDARD_CLASSES | ICC_STANDARD_CLASSES;
		::InitCommonControlsEx(&cce);

		MakeWindow(iconResource, smallIconResource, menuResource);
		SetClientArea(state->m_BackBufferDesc.Width, state->m_BackBufferDesc.Height);

		if (accelResource)
		{
			accelTable = ::LoadAccelerators(hinstance, accelResource);
			if (!accelTable)
				throw Win32Exception(::GetLastError());
		}
	}
Exemple #13
0
size_t File::readData(void* buff, size_t size) {
	DWORD nbytes;
	if (!ReadFile(impl->handle, buff, size, &nbytes, nullptr))
		throw Win32Exception("ReadFile failed");

	return nbytes;
}
Exemple #14
0
void Host::ProtectMemory(const void* address, size_t length, DWORD protection)
{
	// Determine the starting and ending points for the operation
	uintptr_t begin = uintptr_t(address);
	uintptr_t end = begin + length;

	// Prevent changes to the process memory layout while this is operating
	section_lock_t::scoped_lock_read reader(m_sectionlock);

	while(begin < end) {

		// Locate the section object that matches the current base address
		const auto& found = std::find_if(m_sections.begin(), m_sections.end(), [&](const std::unique_ptr<MemorySection>& section) -> bool {
			return ((begin >= uintptr_t(section->BaseAddress)) && (begin < (uintptr_t(section->BaseAddress) + section->Length)));
		});

		// No matching section object exists, throw ERROR_INVALID_ADDRESS
		if(found == m_sections.end()) throw Win32Exception(ERROR_INVALID_ADDRESS);

		// Cast out the std::unique_ptr<MemorySection>& for clarity below
		const auto& section = *found;

		// Determine the length of the allocation to request from this section and request it
		size_t protectlen = min(section->Length - (begin - uintptr_t(section->BaseAddress)), end - begin);
		section->Protect(reinterpret_cast<void*>(begin), protectlen, protection);

		begin += protectlen;
	}
}
	SocketProvider::SocketProvider()
	{
		WSAData wsaData;

		if (0 != WSAStartup(MAKEWORD(2, 2), &wsaData)) {
			throw Win32Exception("WSAStartup");
		}

		static GUID guidTransmitFile = WSAID_TRANSMITFILE;
		static GUID guidAcceptEx = WSAID_ACCEPTEX;
		static GUID guidGetAcceptExSockaddrs = WSAID_GETACCEPTEXSOCKADDRS;
		static GUID guidTransmitPackets = WSAID_TRANSMITPACKETS;
		static GUID guidConnectEx = WSAID_CONNECTEX;
		static GUID guidDisconnectEx = WSAID_DISCONNECTEX;
		static GUID guidWSARecvMsg = WSAID_WSARECVMSG;

		SocketPtr socket;
		GetExtensionFunctionPtr(socket, &guidTransmitFile, &TransmitFile);
		GetExtensionFunctionPtr(socket, &guidAcceptEx, &AcceptEx);
		GetExtensionFunctionPtr(socket, &guidGetAcceptExSockaddrs, &GetAcceptExSockaddrs);
		GetExtensionFunctionPtr(socket, &guidTransmitPackets, &TransmitPackets);
		GetExtensionFunctionPtr(socket, &guidConnectEx, &ConnectEx);
		GetExtensionFunctionPtr(socket, &guidDisconnectEx, &DisconnectEx);
		GetExtensionFunctionPtr(socket, &guidWSARecvMsg, &WSARecvMsg);
	}
      /// <summary>Custom draws a single sub-item</summary>
      /// <param name="dc">Device context</param>
      /// <param name="item">Item data.</param>
      void  ListViewCustomDraw::onDrawSubItem(CDC* dc, ItemData& item)
      {
         // Get item data
         LVItem data(item.Index, item.SubItem, 512, LVIF_IMAGE | LVIF_TEXT);
         ListView.GetItem(&data);

         // Draw Icon:
         CImageList* imgList = ListView.GetImageList(LVSIL_SMALL);
         if (item.SubItem == 0 && imgList)
         {
            CRect icon;

            // Get icon rectangle
            ListView.GetSubItemRect(item.Index, 0, LVIR_ICON, icon);
            
            // Draw transparent
            if (!imgList->Draw(dc, data.iImage, icon.TopLeft(), ILD_TRANSPARENT))
               throw Win32Exception(HERE, VString(L"Unable to draw icon for item %d", item.Index));

            // Create gap betwen icon/label
            item.Rect.left += 3;
         }

         // Draw Text:
         dc->DrawText(data.pszText, item.Rect, DT_VCENTER|DT_LEFT|DT_END_ELLIPSIS|DT_SINGLELINE);
      }
Exemple #17
0
std::string Settings::GetCustomResource(const char *name, const char *type)
{
    const HINSTANCE module = 0; // main executable
    HRSRC hRes = FindResourceA(module, name, type);
    if ( hRes )
    {
        HGLOBAL hData = LoadResource(module, hRes);
        if ( hData )
        {
            const char *data = (const char*)::LockResource(hData);
            size_t size = ::SizeofResource(module, hRes);

            if ( data && size )
            {
                if ( data[size-1] == '\0' ) // null-terminated string
                    size--;
                return std::string(data, size);
            }
        }
    }

    std::string err;
    err += "Failed to get resource \"";
    err += name;
    err += "\" (type \"";
    err += type;
    err += "\")";
    throw Win32Exception(err.c_str());
}
Exemple #18
0
bool Console::getTreatControlCAsInput(void) const
{
	DWORD mode = 0;
	if(!GetConsoleMode(m_stdin, &mode)) throw Win32Exception();

	return ((mode & ENABLE_PROCESSED_INPUT) == ENABLE_PROCESSED_INPUT);
}
   /// <summary>Initialises control and populates</summary>
   /// <param name="lpCreateStruct">The create structure.</param>
   /// <returns></returns>
   int SuggestionList::OnCreate(LPCREATESTRUCT lpCreateStruct)
   {
      try
      {
         if (__super::OnCreate(lpCreateStruct) == -1)
            throw Win32Exception(HERE, L"Unable to create base ListView");
      
         // Display items using a single column. Custom Draw handles the column illusion
         InsertColumn(0, L"text");
         SetColumnWidth(0, lpCreateStruct->cx);
         SetExtendedStyle(LVS_EX_FULLROWSELECT);

         // Populate
         PopulateContent();

         // Ensure we have content
         if (Content.size() == 0)
            throw AlgorithmException(HERE, L"Unable to create list of zero suggestions");

         // Display contents
         SetItemCountEx(Content.size());
         SetItemState(0, LVIS_SELECTED, LVIS_SELECTED);

         // Shrink to fit
         ShrinkToFit();
         OnVisibleItemsChanged();
         return 0;
      }
      catch (ExceptionBase& e)
      {
         Console.Log(HERE, e);
         return -1;
      }
   }
Exemple #20
0
QC_BASE_NAMESPACE_BEGIN

//==============================================================================
// ThreadLocal::ThreadLocal
//
/**
   Default constructor.  Uses the operating-system's threading library to 
   allocate a new thread-local variable.

   The value of the variable is automatically initialized to zero for every
   thread.
*/
//==============================================================================
ThreadLocal::ThreadLocal()
{
#if defined(QC_WIN32_THREADS)

	m_key = ::TlsAlloc();
	if(m_key == (DWORD)-1)
	{
		throw Win32Exception(::GetLastError());
	}

#elif defined(QC_POSIX_THREADS)

	int status = ::pthread_key_create(&m_key, 0);
	if(status != 0)
	{
		throw OSException(status, QC_T("pthread_key_create"));
	}

#endif
}
      /// <summary>Draw multiple lines of rich text</summary>
      /// <param name="dc">dc.</param>
      /// <param name="rect">drawing rectangle</param>
      /// <param name="str">string.</param>
      /// <param name="flags">drawing flags.</param>
      /// <exception cref="Logic::Win32Exception">Drawing error</exception>
      /// <returns>Width of widest line</returns>
      int  RichTextRenderer::DrawLines(CDC* dc, CRect& rect, const RichString& str, RenderFlags flags)
      {
         LOGFONT  fontData;
         CFont*   oldFont;
         LineRect line(rect, dc->GetTextExtent(L"ABC").cy);
         long     rightMargin = rect.left;

         // Get original font properties
         oldFont = dc->GetCurrentFont();
         if (!oldFont->GetLogFont(&fontData))
            throw Win32Exception(HERE, L"Unable to get logical font");
         
         // Draw paragraphs
         for (auto para = str.Paragraphs.begin(); para != str.Paragraphs.end(); )
         {
            auto words(GetWords(*para));

            // Draw words
            for (auto w = words.begin(); w != words.end(); )
            {
               CRect remaining(line);

               // Measure words on line
               auto first = w;
               int line_remaining = MeasureLine(dc, w, words.end(), line, flags);

               // Alignment: Offset all word rectangles
               for (auto word = first; word != w; ++word)
               {
                  switch (para->Align)
                  {
                  case Alignment::Right:   word->Offset(line_remaining, 0);    break;
                  case Alignment::Centre:
                  case Alignment::Justify: word->Offset(line_remaining/2, 0);  break;
                  }

                  // Set rightmost margin
                  rightMargin = max(rightMargin, word->Rect.right);
               }

               // Render words
               if (flags != RenderFlags::Calculate)
                  RenderLine(dc, first, w, flags);

               // NewLine
               if (w != words.end())
                  line.Advance();
            }

            // Start each paragraph on a separate line
            if (++para != str.Paragraphs.end())
               line.Advance();
         }

         // Set drawing extent
         rect.bottom = (!str.FirstParagraph.empty() ? line.bottom : line.top);

         // Return width of widest line of text
         return rightMargin - rect.left;
      }
Exemple #22
0
std::unique_ptr<Host> Host::Create(const tchar_t* path, const tchar_t* arguments, HANDLE handles[], size_t numhandles)
{
	PROCESS_INFORMATION				procinfo;			// Process information

	// If a null argument string was provided, change it to an empty string
	if(arguments == nullptr) arguments = _T("");

	// Generate the command line for the child process, using the specifed path as argument zero
	tchar_t commandline[MAX_PATH];
	_sntprintf_s(commandline, MAX_PATH, MAX_PATH, _T("\"%s\"%s%s"), path, (arguments[0]) ? _T(" ") : _T(""), arguments);

	// Determine the size of the attributes buffer required to hold the inheritable handles property
	SIZE_T required = 0;
	InitializeProcThreadAttributeList(nullptr, 1, 0, &required);
	if(GetLastError() != ERROR_INSUFFICIENT_BUFFER) throw Win32Exception();

	// Allocate a buffer large enough to hold the attribute data and initialize it
	HeapBuffer<uint8_t> buffer(required);
	PPROC_THREAD_ATTRIBUTE_LIST attributes = reinterpret_cast<PPROC_THREAD_ATTRIBUTE_LIST>(&buffer);
	if(!InitializeProcThreadAttributeList(attributes, 1, 0, &required)) throw Win32Exception();

	try {

		// UpdateProcThreadAttribute will fail if there are no handles in the specified array
		if((handles != nullptr) && (numhandles > 0)) {
			
			// Add the array of handles as inheritable handles for the client process
			if(!UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handles, numhandles * sizeof(HANDLE), 
				nullptr, nullptr)) throw Win32Exception();
		}

		// Attempt to launch the process using the CREATE_SUSPENDED and EXTENDED_STARTUP_INFO_PRESENT flag
		zero_init<STARTUPINFOEX> startinfo;
		startinfo.StartupInfo.cb = sizeof(STARTUPINFOEX);
		startinfo.lpAttributeList = attributes;
		if(!CreateProcess(path, commandline, nullptr, nullptr, TRUE, CREATE_SUSPENDED | EXTENDED_STARTUPINFO_PRESENT, nullptr, 
			nullptr, &startinfo.StartupInfo, &procinfo)) throw Win32Exception();

		DeleteProcThreadAttributeList(attributes);			// Clean up the PROC_THREAD_ATTRIBUTE_LIST
	}

	catch(...) { DeleteProcThreadAttributeList(attributes); throw; }

	// Process was successfully created and initialized, pass it off to a Host instance
	return std::make_unique<Host>(procinfo);
}
Exemple #23
0
	void Window::GetWindowPos(INT& posX, INT& posY) const
	{
		RECT windowRect;
		if (!::GetWindowRect(hwnd, &windowRect))
			throw Win32Exception(::GetLastError());
		posX = windowRect.left;
		posY = windowRect.top;
	}
Exemple #24
0
Console::ScreenBufferInfo::ScreenBufferInfo(const Console& parent)
{
	// Try in order: STDOUT, STDERR and STDIN
	if(GetConsoleScreenBufferInfo(parent.m_stdout, this)) return;
	else if(GetConsoleScreenBufferInfo(parent.m_stderr, this)) return;
	else if(GetConsoleScreenBufferInfo(parent.m_stdin, this)) return;
	else throw Win32Exception();
}
Exemple #25
0
// Subclasses a dialog item inside a dialog, usually used in combination with Dialog resources.
void Widget::attach( unsigned id ) {
	if ( !itsParent )
		throw DWTException("Can't attach a Widget without a parent...");
	HWND hWnd = ::GetDlgItem( itsParent->handle(), id );
	if ( !hWnd )
		throw Win32Exception("GetDlgItem failed.");
	setHandle(hWnd);
}
Exemple #26
0
	size_t Socket::EndAsyncOperation(const AsyncResultPtr &asyncResult)
	{
		DWORD size;
		if (0 == GetOverlappedResult((HANDLE)hSocket, asyncResult.operator ->(), &size, TRUE)) {
			throw Win32Exception("GetOverlappedResult");
		}
		return size;
	}
Exemple #27
0
	void Window::GetClientArea(INT& clientX, INT& clientY) const
	{
		RECT clientRect;
		if (!::GetClientRect(hwnd, &clientRect))
			throw Win32Exception(::GetLastError());

		clientX = clientRect.right;
		clientY = clientRect.bottom;
	}
Exemple #28
0
void Console::SetCursorPosition(int16_t left, int16_t top) const
{
	// Check the specified left and top coordinates against the console screen buffer
	COORD buffer = ScreenBufferInfo(*this).dwSize;
	if((left >= buffer.X) || (top >= buffer.Y)) throw Exception(E_INVALIDARG);

	// Attempt to set the attached console's cursor position
	if(!SetConsoleCursorPosition(m_stdout, { left, top })) throw Win32Exception();
}
Exemple #29
0
void Console::SetBufferSize(int16_t width, int16_t height) const
{
	// Check the boundaries of the specified width and height values against the console window
	SMALL_RECT window = ScreenBufferInfo(*this).srWindow;
	if((width < window.Right + 1) || (height < window.Bottom + 1)) throw Exception(E_INVALIDARG);

	// Attempt to set the attached console's screen buffer size
	if(!SetConsoleScreenBufferSize(m_stdout, { width, height })) throw Win32Exception();
}
Exemple #30
0
 /// <summary>Create path of file in the application format</summary>
 /// <param name="filename">filename</param>
 /// <exception cref="Logic::Win32Exception">API function failed</exception>
 AppPath::AppPath(const wstring& filename)
 {
    // Get app path
    if (!GetModuleFileName(NULL, Buffer.get(), MAX_PATH))
       throw Win32Exception(HERE, L"Unable to get application path");
          
    // Rename 
    Assign(RenameFileName(filename).c_str());
 }