This commit is contained in:
Igor Pavlov
2003-12-11 00:00:00 +00:00
committed by Kornel Lesiński
commit 8c1b5c7b7e
982 changed files with 118799 additions and 0 deletions

37
Windows/COM.cpp Executable file
View File

@@ -0,0 +1,37 @@
// Windows/COM.cpp
#include "StdAfx.h"
#include "Windows/COM.h"
#include "Common/StringConvert.h"
namespace NWindows {
namespace NCOM {
// CoInitialize (NULL); must be called!
UString GUIDToStringW(REFGUID guid)
{
UString string;
const int kStringSize = 48;
StringFromGUID2(guid, string.GetBuffer(kStringSize), kStringSize);
string.ReleaseBuffer();
return string;
}
AString GUIDToStringA(REFGUID guid)
{
return UnicodeStringToMultiByte(GUIDToStringW(guid));
}
HRESULT StringToGUIDW(const wchar_t *string, GUID &classID)
{
return CLSIDFromString((wchar_t *)string, &classID);
}
HRESULT StringToGUIDA(const char *string, GUID &classID)
{
return StringToGUIDW(MultiByteToUnicodeString(string), classID);
}
}}

59
Windows/COM.h Executable file
View File

@@ -0,0 +1,59 @@
// Windows/COM.h
#pragma once
#ifndef __WINDOWS_COM_H
#define __WINDOWS_COM_H
#include "Common/String.h"
namespace NWindows {
namespace NCOM {
class CComInitializer
{
public:
CComInitializer() { CoInitialize(NULL);};
~CComInitializer() { CoUninitialize(); };
};
class CStgMedium
{
STGMEDIUM _object;
public:
bool _mustBeReleased;
CStgMedium(): _mustBeReleased(false) {}
~CStgMedium() { Free(); }
void Free()
{
if(_mustBeReleased)
ReleaseStgMedium(&_object);
_mustBeReleased = false;
}
const STGMEDIUM* operator->() const { return &_object;}
STGMEDIUM* operator->() { return &_object;}
STGMEDIUM* operator&() { return &_object; }
};
//////////////////////////////////
// GUID <--> String Conversions
UString GUIDToStringW(REFGUID guid);
AString GUIDToStringA(REFGUID guid);
#ifdef UNICODE
#define GUIDToString GUIDToStringW
#else
#define GUIDToString GUIDToStringA
#endif // !UNICODE
HRESULT StringToGUIDW(const wchar_t *string, GUID &classID);
HRESULT StringToGUIDA(const char *string, GUID &classID);
#ifdef UNICODE
#define StringToGUID StringToGUIDW
#else
#define StringToGUID StringToGUIDA
#endif // !UNICODE
}}
#endif

10
Windows/Console.cpp Executable file
View File

@@ -0,0 +1,10 @@
// Windows/Console.cpp
#include "StdAfx.h"
#include "Windows/Console.h"
namespace NWindows{
namespace NConsole{
}}

54
Windows/Console.h Executable file
View File

@@ -0,0 +1,54 @@
// Windows/Console.h
#ifndef __WINDOWS_CONSOLE_H
#define __WINDOWS_CONSOLE_H
#pragma once
#include "Windows/Defs.h"
namespace NWindows{
namespace NConsole{
class CBase
{
protected:
HANDLE m_Object;
public:
void Attach(HANDLE aHandle) { m_Object = aHandle; };
bool GetMode(DWORD &aMode)
{ return BOOLToBool(::GetConsoleMode(m_Object, &aMode)); }
bool SetMode(DWORD aMode)
{ return BOOLToBool(::SetConsoleMode(m_Object, aMode)); }
};
class CIn: public CBase
{
public:
bool PeekEvents(PINPUT_RECORD anEvents, DWORD aNumEvents, DWORD &aNumEventsRead)
{ return BOOLToBool(::PeekConsoleInput(m_Object, anEvents, aNumEvents, &aNumEventsRead)); }
bool PeekEvent(INPUT_RECORD &anEvent, DWORD &aNumEventsRead)
{ return PeekEvents(&anEvent, 1, aNumEventsRead); }
bool ReadEvents(PINPUT_RECORD anEvents, DWORD aNumEvents, DWORD &aNumEventsRead)
{ return BOOLToBool(::ReadConsoleInput(m_Object, anEvents, aNumEvents, &aNumEventsRead)); }
bool ReadEvent(INPUT_RECORD &anEvent, DWORD &aNumEventsRead)
{ return ReadEvents(&anEvent, 1, aNumEventsRead); }
bool GetNumberOfEvents(DWORD &aNumberOfEvents)
{ return BOOLToBool(::GetNumberOfConsoleInputEvents(m_Object, &aNumberOfEvents)); }
bool WriteEvents(const INPUT_RECORD *anEvents, DWORD aNumEvents, DWORD &aNumEventsWritten)
{ return BOOLToBool(::WriteConsoleInput(m_Object, anEvents, aNumEvents, &aNumEventsWritten)); }
bool WriteEvent(const INPUT_RECORD &anEvent, DWORD &aNumEventsWritten)
{ return WriteEvents(&anEvent, 1, aNumEventsWritten); }
bool Read(LPVOID aBuffer, DWORD aNumberOfCharsToRead, DWORD &aNumberOfCharsRead)
{ return BOOLToBool(::ReadConsole(m_Object, aBuffer, aNumberOfCharsToRead, &aNumberOfCharsRead, NULL)); }
bool Flush()
{ return BOOLToBool(::FlushConsoleInputBuffer(m_Object)); }
};
}}
#endif

23
Windows/Control/ComboBox.cpp Executable file
View File

@@ -0,0 +1,23 @@
// Windows/Control/ComboBox.cpp
#include "StdAfx.h"
#include "Windows/Control/ComboBox.h"
#include "Windows/Defs.h"
namespace NWindows {
namespace NControl {
int CComboBox::GetLBText(int index, CSysString &string)
{
string.Empty();
int aLength = GetLBTextLen(index);
if (aLength == CB_ERR)
return aLength;
aLength = GetLBText(index, string.GetBuffer(aLength));
string.ReleaseBuffer();
return aLength;
}
}}

55
Windows/Control/ComboBox.h Executable file
View File

@@ -0,0 +1,55 @@
// Windows/Control/ComboBox.h
#pragma once
#ifndef __WINDOWS_CONTROL_COMBOBOX_H
#define __WINDOWS_CONTROL_COMBOBOX_H
#include "Windows/Window.h"
#include "Windows/Defs.h"
namespace NWindows {
namespace NControl {
class CComboBox: public CWindow
{
public:
void ResetContent()
{ SendMessage(CB_RESETCONTENT, 0, 0); }
int AddString(LPCTSTR string)
{ return SendMessage(CB_ADDSTRING, 0, (LPARAM)string); }
int SetCurSel(int index)
{ return SendMessage(CB_SETCURSEL, index, 0); }
int GetCurSel()
{ return SendMessage(CB_GETCURSEL, 0, 0); }
int GetCount()
{ return SendMessage(CB_GETCOUNT, 0, 0); }
int GetLBTextLen(int index)
{ return SendMessage(CB_GETLBTEXTLEN, index, 0); }
int GetLBText(int index, LPTSTR string)
{ return SendMessage(CB_GETLBTEXT, index, (LPARAM)string); }
int GetLBText(int index, CSysString &string);
int SetItemData(int index, LPARAM lParam)
{ return SendMessage(CB_SETITEMDATA, index, lParam); }
int GetItemData(int index)
{ return SendMessage(CB_GETITEMDATA, index, 0); }
};
class CComboBoxEx: public CWindow
{
public:
int DeleteItem(int index)
{ return SendMessage(CBEM_DELETEITEM, index, 0); }
int InsertItem(COMBOBOXEXITEM *item)
{ return SendMessage(CBEM_INSERTITEM, 0, (LPARAM)item); }
DWORD SetExtendedStyle(DWORD exMask, DWORD exStyle)
{ return SendMessage(CBEM_SETEXTENDEDSTYLE, exMask, exStyle); }
HWND GetEditControl()
{ return (HWND)SendMessage(CBEM_GETEDITCONTROL, 0, 0); }
};
}}
#endif

106
Windows/Control/Dialog.cpp Executable file
View File

@@ -0,0 +1,106 @@
// Windows/Control/Dialog.cpp
#include "StdAfx.h"
#include "Windows/Control/Dialog.h"
extern HINSTANCE g_hInstance;
namespace NWindows {
namespace NControl {
BOOL APIENTRY DialogProcedure(HWND dialogHWND, UINT message,
WPARAM wParam, LPARAM lParam)
{
CWindow aDialogTmp(dialogHWND);
if (message == WM_INITDIALOG)
aDialogTmp.SetUserDataLongPtr(lParam);
CDialog *aDialog = (CDialog *)(aDialogTmp.GetUserDataLongPtr());
if (aDialog == NULL)
return FALSE;
if (message == WM_INITDIALOG)
aDialog->Attach(dialogHWND);
return BoolToBOOL(aDialog->OnMessage(message, wParam, lParam));
}
bool CDialog::OnMessage(UINT message, UINT wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
return OnInit();
case WM_COMMAND:
return OnCommand(wParam, lParam);
case WM_NOTIFY:
return OnNotify(wParam, (LPNMHDR) lParam);
case WM_HELP:
{
OnHelp((LPHELPINFO)lParam);
return true;
}
case WM_TIMER:
{
return OnTimer(wParam, lParam);
}
default:
return false;
}
}
bool CDialog::OnCommand(WPARAM wParam, LPARAM lParam)
{
return OnCommand(HIWORD(wParam), LOWORD(wParam), lParam);
}
bool CDialog::OnCommand(int code, int itemID, LPARAM lParam)
{
if (code == BN_CLICKED)
return OnButtonClicked(itemID, (HWND)lParam);
return false;
}
bool CDialog::OnButtonClicked(int buttonID, HWND buttonHWND)
{
switch(buttonID)
{
case IDOK:
OnOK();
break;
case IDCANCEL:
OnCancel();
break;
case IDHELP:
OnHelp();
break;
default:
return false;
}
return true;
}
bool CModelessDialog::Create(LPCTSTR templateName, HWND parentWindow)
{
HWND aHWND = CreateDialogParam(g_hInstance,
templateName, parentWindow, DialogProcedure, LPARAM(this));
if (aHWND == 0)
return false;
Attach(aHWND);
return true;
}
INT_PTR CModalDialog::Create(LPCTSTR templateName, HWND parentWindow)
{
return DialogBoxParam(g_hInstance,
templateName, parentWindow, DialogProcedure, LPARAM(this));
}
/*
INT_PTR CModalDialog::Create(LPCWSTR templateName, HWND parentWindow)
{
return DialogBoxParamW(g_hInstance,
templateName, parentWindow, DialogProcedure, LPARAM(this));
}
*/
}}

137
Windows/Control/Dialog.h Executable file
View File

@@ -0,0 +1,137 @@
// Windows/Control/Dialog.h
#pragma once
#ifndef __WINDOWS_CONTROL_DIALOG_H
#define __WINDOWS_CONTROL_DIALOG_H
#include "Windows/Window.h"
#include "Windows/Defs.h"
namespace NWindows {
namespace NControl {
BOOL APIENTRY DialogProcedure(HWND dialogHWND, UINT message, UINT wParam, LPARAM lParam);
class CDialog: public CWindow
{
public:
CDialog(HWND wndow = NULL): CWindow(wndow){};
virtual ~CDialog() {};
HWND GetItem(int itemID) const
{ return GetDlgItem(_window, itemID); }
bool EnableItem(int itemID, bool enable) const
{ return BOOLToBool(::EnableWindow(GetItem(itemID), BoolToBOOL(enable))); }
bool SetItemText(int itemID, LPCTSTR s)
{ return BOOLToBool(SetDlgItemText(_window, itemID, s)); }
#ifndef _UNICODE
bool SetItemText(int itemID, LPCWSTR s)
{
CWindow window(GetItem(itemID));
return window.SetText(s);
}
#endif
UINT GetItemText(int itemID, LPTSTR string, int maxCount)
{ return GetDlgItemText(_window, itemID, string, maxCount); }
#ifndef _UNICODE
/*
bool GetItemText(int itemID, LPWSTR string, int maxCount)
{
CWindow window(GetItem(itemID));
return window.GetText(string, maxCount);
}
*/
#endif
bool SetItemInt(int itemID, UINT value, bool isSigned)
{ return BOOLToBool(SetDlgItemInt(_window, itemID, value, BoolToBOOL(isSigned))); }
bool GetItemInt(int itemID, bool isSigned, UINT &value)
{
BOOL result;
value = GetDlgItemInt(_window, itemID, &result, BoolToBOOL(isSigned));
return BOOLToBool(result);
}
HWND GetNextGroupItem(HWND control, bool previous)
{ return GetNextDlgGroupItem(_window, control, BoolToBOOL(previous)); }
HWND GetNextTabItem(HWND control, bool previous)
{ return GetNextDlgTabItem(_window, control, BoolToBOOL(previous)); }
bool MapRect(LPRECT rect)
{ return BOOLToBool(MapDialogRect(_window, rect)); }
bool IsMessage(LPMSG message)
{ return BOOLToBool(IsDialogMessage(_window, message)); }
LRESULT SendItemMessage(int itemID, UINT message, WPARAM wParam, LPARAM lParam)
{ return SendDlgItemMessage(_window, itemID, message, wParam, lParam); }
bool CheckButton(int buttonID, UINT checkState)
{ return BOOLToBool(CheckDlgButton(_window, buttonID, checkState)); }
bool CheckButton(int buttonID, bool checkState)
{ return CheckButton(buttonID, UINT(checkState ? BST_CHECKED : BST_UNCHECKED)); }
UINT IsButtonChecked(int buttonID) const
{ return IsDlgButtonChecked(_window, buttonID); }
bool IsButtonCheckedBool(int buttonID) const
{ return (IsButtonChecked(buttonID) == BST_CHECKED); }
bool CheckRadioButton(int firstButtonID, int lastButtonID, int checkButtonID)
{ return BOOLToBool(::CheckRadioButton(_window, firstButtonID, lastButtonID, checkButtonID)); }
virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam);
virtual bool OnInit() { return true; }
virtual bool OnCommand(WPARAM wParam, LPARAM lParam);
virtual bool OnCommand(int code, int itemID, LPARAM lParam);
virtual void OnHelp(LPHELPINFO helpInfo) { OnHelp(); };
virtual void OnHelp() {};
virtual bool OnButtonClicked(int buttonID, HWND buttonHWND);
virtual void OnOK() {};
virtual void OnCancel() {};
virtual bool OnNotify(UINT controlID, LPNMHDR lParam) { return false; }
virtual bool OnTimer(WPARAM timerID, LPARAM callback) { return false; }
LONG_PTR SetMsgResult(LONG_PTR newLongPtr )
{ return SetLongPtr(DWLP_MSGRESULT, newLongPtr); }
LONG_PTR GetMsgResult() const
{ return GetLongPtr(DWLP_MSGRESULT); }
};
class CModelessDialog: public CDialog
{
public:
bool Create(LPCTSTR templateName, HWND parentWindow);
virtual void OnOK() { Destroy(); }
virtual void OnCancel() { Destroy(); }
};
class CModalDialog: public CDialog
{
public:
INT_PTR Create(LPCTSTR templateName, HWND parentWindow);
// INT_PTR Create(LPCWSTR templateName, HWND parentWindow);
bool End(INT_PTR result)
{ return BOOLToBool(::EndDialog(_window, result)); }
virtual void OnOK() { End(IDOK); }
virtual void OnCancel() { End(IDCANCEL); }
};
class CDialogChildControl: public NWindows::CWindow
{
public:
int m_ID;
void Init(const NWindows::NControl::CDialog &parentDialog, int id)
{
m_ID = id;
Attach(parentDialog.GetItem(id));
}
};
}}
#endif

23
Windows/Control/Edit.h Executable file
View File

@@ -0,0 +1,23 @@
// Windows/Control/Edit.h
#pragma once
#ifndef __WINDOWS_CONTROL_EDIT_H
#define __WINDOWS_CONTROL_EDIT_H
#include "Windows/Window.h"
#include "Windows/Defs.h"
namespace NWindows {
namespace NControl {
class CEdit: public CWindow
{
public:
void SetPasswordChar(WPARAM c)
{ SendMessage(EM_SETPASSWORDCHAR, c); }
};
}}
#endif

11
Windows/Control/ImageList.cpp Executable file
View File

@@ -0,0 +1,11 @@
// Windows/Control/ImageList.cpp
#include "StdAfx.h"
#include "Windows/Control/ImageList.h"
namespace NWindows {
namespace NControl {
}}

88
Windows/Control/ImageList.h Executable file
View File

@@ -0,0 +1,88 @@
// Windows/Control/ImageList.h
#pragma once
#ifndef __WINDOWS_CONTROL_IMAGELIST_H
#define __WINDOWS_CONTROL_IMAGELIST_H
#include "Windows/Defs.h"
namespace NWindows {
namespace NControl {
class CImageList
{
HIMAGELIST m_Object;
public:
operator HIMAGELIST() const {return m_Object; }
CImageList(): m_Object(NULL) {}
bool Attach(HIMAGELIST imageList)
{
if(imageList == NULL)
return false;
m_Object = imageList;
return true;
}
HIMAGELIST Detach()
{
HIMAGELIST imageList = m_Object;
m_Object = NULL;
return imageList;
}
bool Create(int width, int height, UINT flags, int initialNumber, int grow)
{
HIMAGELIST a = ImageList_Create(width, height, flags,
initialNumber, grow);
if(a == NULL)
return false;
return Attach(a);
}
bool Destroy() // DeleteImageList() in MFC
{
if (m_Object == NULL)
return false;
return BOOLToBool(ImageList_Destroy(Detach()));
}
~CImageList()
{ Destroy(); }
int GetImageCount() const
{ return ImageList_GetImageCount(m_Object); }
bool GetImageInfo(int index, IMAGEINFO* imageInfo) const
{ return BOOLToBool(ImageList_GetImageInfo(m_Object, index, imageInfo)); }
int Add(HBITMAP hbmImage, HBITMAP hbmMask = 0)
{ return ImageList_Add(m_Object, hbmImage, hbmMask); }
int AddMasked(HBITMAP hbmImage, COLORREF mask)
{ return ImageList_AddMasked(m_Object, hbmImage, mask); }
int AddIcon(HICON icon)
{ return ImageList_AddIcon(m_Object, icon); }
int Replace(int index, HICON icon)
{ return ImageList_ReplaceIcon(m_Object, index, icon); }
// If index is -1, the function removes all images.
bool Remove(int index)
{ return BOOLToBool(ImageList_Remove(m_Object, index)); }
bool RemoveAll()
{ return BOOLToBool(ImageList_RemoveAll(m_Object)); }
HICON ExtractIcon(int index)
{ return ImageList_ExtractIcon(NULL, m_Object, index); }
HICON GetIcon(int index, UINT flags)
{ return ImageList_GetIcon(m_Object, index, flags); }
bool GetIconSize(int &width, int &height) const
{ return BOOLToBool(ImageList_GetIconSize(m_Object, &width, &height)); }
bool SetIconSize(int width, int height)
{ return BOOLToBool(ImageList_SetIconSize(m_Object, width, height)); }
};
}}
#endif

58
Windows/Control/ListView.cpp Executable file
View File

@@ -0,0 +1,58 @@
// Windows/Control/ListView.cpp
#include "StdAfx.h"
#include "Windows/Control/ListView.h"
namespace NWindows {
namespace NControl {
bool CListView::CreateEx(DWORD exStyle, DWORD style,
int x, int y, int width, int height,
HWND parentWindow, HMENU idOrHMenu,
HINSTANCE instance, LPVOID createParam)
{
return CWindow::CreateEx(exStyle, WC_LISTVIEW, TEXT(""), style, x, y, width,
height, parentWindow, idOrHMenu, instance, createParam);
}
bool CListView::GetItemParam(int itemIndex, LPARAM &param) const
{
LVITEM item;
item.iItem = itemIndex;
item.iSubItem = 0;
item.mask = LVIF_PARAM;
bool aResult = GetItem(&item);
param = item.lParam;
return aResult;
}
/*
int CListView::InsertItem(UINT mask, int item, LPCTSTR itemText,
UINT nState, UINT nStateMask, int nImage, LPARAM lParam)
{
LVITEM item;
item.mask = nMask;
item.iItem = nItem;
item.iSubItem = 0;
item.pszText = (LPTSTR)itemText;
item.state = nState;
item.stateMask = nStateMask;
item.iImage = nImage;
item.lParam = lParam;
return InsertItem(&item);
}
int CListView::InsertItem(int nItem, LPCTSTR itemText)
{
return InsertItem(LVIF_TEXT, nItem, itemText, 0, 0, 0, 0);
}
int CListView::InsertItem(int nItem, LPCTSTR itemText, int nImage)
{
return InsertItem(LVIF_TEXT | LVIF_IMAGE, nItem, itemText, 0, 0, nImage, 0);
}
*/
}}

121
Windows/Control/ListView.h Executable file
View File

@@ -0,0 +1,121 @@
// Windows/Control/ListView.h
#pragma once
#ifndef __WINDOWS_CONTROL_LISTVIEW_H
#define __WINDOWS_CONTROL_LISTVIEW_H
#include "Windows/Window.h"
#include "Windows/Defs.h"
namespace NWindows {
namespace NControl {
class CListView: public NWindows::CWindow
{
public:
bool CreateEx(DWORD exStyle, DWORD style,
int x, int y, int width, int height,
HWND parentWindow, HMENU idOrHMenu,
HINSTANCE instance, LPVOID createParam);
bool DeleteAllItems()
{ return BOOLToBool(ListView_DeleteAllItems(_window)); }
int InsertColumn(int columnIndex, const LVCOLUMN *columnInfo)
{ return ListView_InsertColumn(_window, columnIndex, columnInfo); }
bool DeleteColumn(int columnIndex)
{ return BOOLToBool(ListView_DeleteColumn(_window, columnIndex)); }
int InsertItem(const LVITEM* item)
{ return ListView_InsertItem(_window, item); }
bool SetItem(const LVITEM* item)
{ return BOOLToBool(ListView_SetItem(_window, item)); }
bool DeleteItem(int itemIndex)
{ return BOOLToBool(ListView_DeleteItem(_window, itemIndex)); }
UINT GetSelectedCount() const
{ return ListView_GetSelectedCount(_window); }
int GetItemCount() const
{ return ListView_GetItemCount(_window); }
INT GetSelectionMark()
{ return ListView_GetSelectionMark(_window); }
void SetItemCount(int numItems)
{ ListView_SetItemCount(_window, numItems); }
void SetItemCountEx(int numItems, DWORD flags)
{ ListView_SetItemCountEx(_window, numItems, flags); }
int GetNextItem(int startIndex, UINT flags) const
{ return ListView_GetNextItem(_window, startIndex, flags); }
int GetNextSelectedItem(int startIndex) const
{ return GetNextItem(startIndex, LVNI_SELECTED); }
int GetFocusedItem() const
{ return GetNextItem(-1, LVNI_FOCUSED); }
bool GetItem(LVITEM* item) const
{ return BOOLToBool(ListView_GetItem(_window, item)); }
bool GetItemParam(int itemIndex, LPARAM &param) const;
void GetItemText(int itemIndex, int aSubItemIndex, LPTSTR aText, int aTextSizeMax) const
{ ListView_GetItemText(_window, itemIndex, aSubItemIndex, aText, aTextSizeMax); }
bool SortItems(PFNLVCOMPARE compareFunction, LPARAM dataParam)
{ return BOOLToBool(ListView_SortItems(_window, compareFunction, dataParam)); }
void SetItemState(int index, UINT state, UINT mask)
{ ListView_SetItemState(_window, index, state, mask); }
UINT GetItemState(int index, UINT mask)
{ return ListView_GetItemState(_window, index, mask); }
bool GetColumn(int columnIndex, LVCOLUMN* columnInfo) const
{ return BOOLToBool(ListView_GetColumn(_window, columnIndex, columnInfo)); }
HIMAGELIST SetImageList(HIMAGELIST imageList, int imageListType)
{ return ListView_SetImageList(_window, imageList, imageListType); }
// version 4.70: NT5 | (NT4 + ie3) | w98 | (w95 + ie3)
DWORD GetExtendedListViewStyle()
{ return ListView_GetExtendedListViewStyle(_window); }
void SetExtendedListViewStyle(DWORD exStyle)
{ ListView_SetExtendedListViewStyle(_window, exStyle); }
void SetExtendedListViewStyle(DWORD exMask, DWORD exStyle)
{ ListView_SetExtendedListViewStyleEx(_window, exMask, exStyle); }
#ifndef _WIN32_WCE
void SetCheckState(UINT index, bool checkState)
{ ListView_SetCheckState(_window, index, BoolToBOOL(checkState)); }
#endif
bool GetCheckState(UINT index)
{ return BOOLToBool(ListView_GetCheckState(_window, index)); }
bool EnsureVisible(int index, bool partialOK)
{ return BOOLToBool(ListView_EnsureVisible(_window, index, BoolToBOOL(partialOK))); }
bool GetItemRect(int index, RECT *rect, int code)
{ return BOOLToBool(ListView_GetItemRect(_window, index, rect, code)); }
HWND GetEditControl()
{ return ListView_GetEditControl(_window) ; }
HWND EditLabel(int itemIndex)
{ return ListView_EditLabel(_window, itemIndex) ; }
bool RedrawItems(int firstIndex, int lastIndex)
{ return BOOLToBool(ListView_RedrawItems(_window, firstIndex, lastIndex)); }
bool RedrawAllItems()
{
if (GetItemCount() > 0)
return RedrawItems(0, GetItemCount() - 1);
return true;
}
bool RedrawItem(int index)
{ return RedrawItems(index, index); }
int HitTest(LPLVHITTESTINFO info)
{ return ListView_HitTest(_window, info); }
COLORREF GetBkColor()
{ return ListView_GetBkColor(_window); }
};
}}
#endif

43
Windows/Control/ProgressBar.h Executable file
View File

@@ -0,0 +1,43 @@
// Windows/Control/ProgressBar.h
#pragma once
#ifndef __WINDOWS_CONTROL_PROGRESSBAR_H
#define __WINDOWS_CONTROL_PROGRESSBAR_H
#include "Windows/Window.h"
#include "Windows/Defs.h"
namespace NWindows {
namespace NControl {
class CProgressBar: public CWindow
{
public:
LRESULT SetPos(int pos)
{ return SendMessage(PBM_SETPOS, pos, 0); }
LRESULT DeltaPos(int increment)
{ return SendMessage(PBM_DELTAPOS, increment, 0); }
UINT GetPos()
{ return SendMessage(PBM_GETPOS, 0, 0); }
LRESULT SetRange(unsigned short minValue, unsigned short maxValue)
{ return SendMessage(PBM_SETRANGE, 0, MAKELPARAM(minValue, maxValue)); }
DWORD SetRange32(int minValue, int maxValue)
{ return SendMessage(PBM_SETRANGE32, minValue, maxValue); }
int SetStep(int aStep)
{ return SendMessage(PBM_SETSTEP, aStep, 0); }
int StepIt()
{ return SendMessage(PBM_STEPIT, 0, 0); }
int GetRange(bool minValue, PPBRANGE range)
{ return SendMessage(PBM_GETRANGE, BoolToBOOL(minValue), (LPARAM)range); }
COLORREF SetBarColor(COLORREF color)
{ return SendMessage(PBM_SETBARCOLOR, 0, color); }
COLORREF SetBackgroundColor(COLORREF color)
{ return SendMessage(PBM_SETBKCOLOR, 0, color); }
};
}}
#endif

View File

@@ -0,0 +1,59 @@
// Windows/Control/PropertyPage.cpp
#include "StdAfx.h"
#include "Windows/Control/PropertyPage.h"
namespace NWindows {
namespace NControl {
BOOL APIENTRY ProperyPageProcedure(HWND dialogHWND, UINT message,
UINT wParam, LONG lParam)
{
CDialog tempDialog(dialogHWND);
if (message == WM_INITDIALOG)
tempDialog.SetUserDataLongPtr(((PROPSHEETPAGE *)lParam)->lParam);
CDialog *dialog = (CDialog *)(tempDialog.GetUserDataLongPtr());
if (message == WM_INITDIALOG)
dialog->Attach(dialogHWND);
switch (message)
{
case WM_INITDIALOG:
return dialog->OnInit();
case WM_COMMAND:
return dialog->OnCommand(wParam, lParam);
case WM_NOTIFY:
return dialog->OnNotify(wParam, (LPNMHDR) lParam);
}
if (dialog == NULL)
return false;
return dialog->OnMessage(message, wParam, lParam);
}
bool CPropertyPage::OnNotify(UINT controlID, LPNMHDR lParam)
{
switch(lParam->code)
{
case PSN_APPLY:
SetMsgResult(OnApply(LPPSHNOTIFY(lParam)));
break;
case PSN_KILLACTIVE:
SetMsgResult(BoolToBOOL(OnKillActive(LPPSHNOTIFY(lParam))));
break;
case PSN_SETACTIVE:
SetMsgResult(OnSetActive(LPPSHNOTIFY(lParam)));
break;
case PSN_RESET:
OnReset(LPPSHNOTIFY(lParam));
break;
case PSN_HELP:
OnNotifyHelp(LPPSHNOTIFY(lParam));
break;
default:
return false;
}
return true;
}
}}

41
Windows/Control/PropertyPage.h Executable file
View File

@@ -0,0 +1,41 @@
// Windows/Control/PropertyPage.h
#pragma once
#ifndef __WINDOWS_CONTROL_PROPERTYPAGE_H
#define __WINDOWS_CONTROL_PROPERTYPAGE_H
#include "Windows/Control/Dialog.h"
#include "Windows/Defs.h"
namespace NWindows {
namespace NControl {
BOOL APIENTRY ProperyPageProcedure(HWND dialogHWND, UINT message, UINT wParam, LONG lParam);
class CPropertyPage: public CDialog
{
public:
CPropertyPage(HWND window = NULL): CDialog(window){};
void Changed() { PropSheet_Changed(GetParent(), HWND(*this)); }
void UnChanged() { PropSheet_UnChanged(GetParent(), HWND(*this)); }
virtual bool OnNotify(UINT controlID, LPNMHDR lParam);
virtual bool OnKillActive() { return false; } // false = OK
virtual bool OnKillActive(const PSHNOTIFY *aPSHNOTIFY) { return OnKillActive(); }
virtual LONG OnSetActive() { return false; } // false = OK
virtual LONG OnSetActive(const PSHNOTIFY *aPSHNOTIFY) { return OnKillActive(); }
virtual LONG OnApply() { return PSNRET_NOERROR; }
virtual LONG OnApply(const PSHNOTIFY *aPSHNOTIFY) { return OnApply(); }
virtual void OnNotifyHelp() { }
virtual void OnNotifyHelp(const PSHNOTIFY *aPSHNOTIFY) { OnNotifyHelp(); }
virtual void OnReset() { }
virtual void OnReset(const PSHNOTIFY *aPSHNOTIFY) { OnReset(); }
};
}}
#endif

37
Windows/Control/ReBar.h Executable file
View File

@@ -0,0 +1,37 @@
// Windows/Control/ReBar.h
#pragma once
#ifndef __WINDOWS_CONTROL_REBAR_H
#define __WINDOWS_CONTROL_REBAR_H
#include "Windows/Window.h"
#include "Windows/Defs.h"
namespace NWindows {
namespace NControl {
class CReBar: public NWindows::CWindow
{
public:
bool SetBarInfo(LPREBARINFO barInfo)
{ return BOOLToBool(SendMessage(RB_SETBARINFO, 0, (LPARAM)barInfo)); }
bool InsertBand(int index, LPREBARBANDINFO bandInfo)
{ return BOOLToBool(SendMessage(RB_INSERTBAND, index, (LPARAM)bandInfo)); }
bool SetBandInfo(int index, LPREBARBANDINFO bandInfo)
{ return BOOLToBool(SendMessage(RB_SETBANDINFO, index, (LPARAM)bandInfo)); }
void MaximizeBand(int index, bool ideal)
{ SendMessage(RB_MAXIMIZEBAND, index, BoolToBOOL(ideal)); }
bool SizeToRect(LPRECT rect)
{ return BOOLToBool(SendMessage(RB_SIZETORECT, 0, (LPARAM)rect)); }
UINT GetHeight()
{ return SendMessage(RB_GETBARHEIGHT); }
UINT GetBandCount()
{ return SendMessage(RB_GETBANDCOUNT); }
bool DeleteBand(UINT index)
{ return BOOLToBool(SendMessage(RB_DELETEBAND, index)); }
};
}}
#endif

29
Windows/Control/Static.h Executable file
View File

@@ -0,0 +1,29 @@
// Windows/Control/Static.h
#pragma once
#ifndef __WINDOWS_CONTROL_STATIC_H
#define __WINDOWS_CONTROL_STATIC_H
#include "Windows/Window.h"
#include "Windows/Defs.h"
namespace NWindows {
namespace NControl {
class CStatic: public CWindow
{
public:
HICON SetIcon(HICON icon)
{ return (HICON)SendMessage(STM_SETICON, (WPARAM)icon, 0); }
HICON GetIcon()
{ return (HICON)SendMessage(STM_GETICON, 0, 0); }
HANDLE SetImage(WPARAM imageType, HANDLE handle)
{ return (HANDLE)SendMessage(STM_SETIMAGE, imageType, (LPARAM)handle); }
HANDLE GetImage(WPARAM imageType)
{ return (HANDLE)SendMessage(STM_GETIMAGE, imageType, 0); }
};
}}
#endif

33
Windows/Control/StatusBar.h Executable file
View File

@@ -0,0 +1,33 @@
// Windows/Control/StatusBar.h
#pragma once
#ifndef __WINDOWS_CONTROL_STATUSBAR_H
#define __WINDOWS_CONTROL_STATUSBAR_H
#include "Windows/Window.h"
#include "Windows/Defs.h"
namespace NWindows {
namespace NControl {
class CStatusBar: public NWindows::CWindow
{
public:
bool Create(LONG style, LPCTSTR text, HWND hwndParent, UINT id)
{ return (_window = ::CreateStatusWindow(style, text, hwndParent, id)) != 0; }
bool SetParts(int numParts, const int *edgePostions)
{ return BOOLToBool(SendMessage(SB_SETPARTS, numParts, (LPARAM)edgePostions)); }
bool SetText(LPCTSTR text)
{ return CWindow::SetText(text); }
bool SetText(int index, LPCTSTR text, UINT type)
{ return BOOLToBool(SendMessage(SB_SETTEXT, index | type, (LPARAM)text)); }
bool SetText(int index, LPCTSTR text)
{ return SetText(index, text, 0); }
void Simple(bool simple)
{ SendMessage(SB_SIMPLE, BoolToBOOL(simple), 0); }
};
}}
#endif

32
Windows/Control/ToolBar.h Executable file
View File

@@ -0,0 +1,32 @@
// Windows/Control/ToolBar.h
#pragma once
#ifndef __WINDOWS_CONTROL_TOOLBAR_H
#define __WINDOWS_CONTROL_TOOLBAR_H
#include "Windows/Window.h"
#include "Windows/Defs.h"
namespace NWindows {
namespace NControl {
class CToolBar: public NWindows::CWindow
{
public:
bool GetMaxSize(LPSIZE size)
{ return BOOLToBool(SendMessage(TB_GETMAXSIZE, 0, (LPARAM)size)); }
bool EnableButton(UINT buttonID, bool enable)
{ return BOOLToBool(SendMessage(TB_ENABLEBUTTON, buttonID,
MAKELONG(BoolToBOOL(enable), 0))); }
void ButtonStructSize()
{ SendMessage(TB_BUTTONSTRUCTSIZE, sizeof(TBBUTTON)); }
HIMAGELIST SetImageList(UINT listIndex, HIMAGELIST imageList)
{ return HIMAGELIST(SendMessage(TB_SETIMAGELIST, listIndex, (LPARAM)imageList)); }
bool AddButton(UINT numButtons, LPTBBUTTON buttons)
{ return BOOLToBool(SendMessage(TB_ADDBUTTONS, numButtons, (LPARAM)buttons)); }
};
}}
#endif

30
Windows/Control/Trackbar.h Executable file
View File

@@ -0,0 +1,30 @@
// Windows/Control/Trackbar.h
#pragma once
#ifndef __WINDOWS_CONTROL_TRACKBAR_H
#define __WINDOWS_CONTROL_TRACKBAR_H
#include "Windows/Window.h"
#include "Windows/Defs.h"
namespace NWindows {
namespace NControl {
class CTrackbar: public CWindow
{
public:
void SetRange(int minimum, int maximum, bool redraw = true)
{ SendMessage(TBM_SETRANGE, BoolToBOOL(redraw), MAKELONG(minimum, maximum)); }
void SetPos(int pos, bool redraw = true)
{ SendMessage(TBM_SETPOS, BoolToBOOL(redraw), pos); }
void SetTicFreq(int freq)
{ SendMessage(TBM_SETTICFREQ, freq); }
int GetPos()
{ return SendMessage(TBM_GETPOS); }
};
}}
#endif

125
Windows/Control/Window2.cpp Executable file
View File

@@ -0,0 +1,125 @@
// Windows/Control/Window2.cpp
#include "StdAfx.h"
#include "Windows/Control/Window2.h"
// extern HINSTANCE g_hInstance;
namespace NWindows {
namespace NControl {
static LRESULT CALLBACK WindowProcedure(HWND aHWND, UINT message,
WPARAM wParam, LPARAM lParam)
{
CWindow tempWindow(aHWND);
if (message == WM_NCCREATE)
tempWindow.SetUserDataLongPtr(
LONG_PTR(((LPCREATESTRUCT)lParam)->lpCreateParams));
CWindow2 *window = (CWindow2*)(tempWindow.GetUserDataLongPtr());
if (window == NULL)
return FALSE;
if (message == WM_NCCREATE)
window->Attach(aHWND);
if (window == 0)
return DefWindowProc(aHWND, message, wParam, lParam);
return window->OnMessage(message, wParam, lParam);
}
bool CWindow2::CreateEx(DWORD exStyle, LPCTSTR className,
LPCTSTR windowName, DWORD style,
int x, int y, int width, int height,
HWND parentWindow, HMENU idOrHMenu,
HINSTANCE instance)
{
WNDCLASS windowClass;
if(!::GetClassInfo(instance, className, &windowClass))
{
// windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.style = 0;
windowClass.lpfnWndProc = WindowProcedure;
windowClass.cbClsExtra = NULL;
windowClass.cbWndExtra = NULL;
windowClass.hInstance = instance;
windowClass.hIcon = NULL;
windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
windowClass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
windowClass.lpszMenuName = NULL;
windowClass.lpszClassName = className;
if (::RegisterClass(&windowClass) == 0)
return false;
}
return CWindow::CreateEx(exStyle, className, windowName,
style, x, y, width, height, parentWindow,
idOrHMenu, instance, this);
}
LRESULT CWindow2::OnMessage(UINT message, UINT wParam, LPARAM lParam)
{
LRESULT result;
switch (message)
{
case WM_CREATE:
if (!OnCreate((CREATESTRUCT *)lParam))
return -1;
break;
case WM_COMMAND:
if (OnCommand(wParam, lParam, result))
return result;
break;
case WM_NOTIFY:
if (OnNotify(wParam, (LPNMHDR) lParam, result))
return result;
break;
case WM_DESTROY:
OnDestroy();
break;
case WM_CLOSE:
OnClose();
return 0;
case WM_SIZE:
if (OnSize(wParam, LOWORD(lParam), HIWORD(lParam)))
return 0;
}
return DefProc(message, wParam, lParam);
}
bool CWindow2::OnCommand(WPARAM wParam, LPARAM lParam, LRESULT &result)
{
return OnCommand(HIWORD(wParam), LOWORD(wParam), lParam, result);
}
bool CWindow2::OnCommand(int code, int itemID, LPARAM lParam, LRESULT &result)
{
return false;
// return DefProc(message, wParam, lParam);
/*
if (code == BN_CLICKED)
return OnButtonClicked(itemID, (HWND)lParam);
*/
}
/*
bool CDialog::OnButtonClicked(int buttonID, HWND buttonHWND)
{
switch(aButtonID)
{
case IDOK:
OnOK();
break;
case IDCANCEL:
OnCancel();
break;
case IDHELP:
OnHelp();
break;
default:
return false;
}
return true;
}
*/
}}

54
Windows/Control/Window2.h Executable file
View File

@@ -0,0 +1,54 @@
// Windows/Control/Window2.h
#pragma once
#ifndef __WINDOWS_CONTROL_WINDOW2_H
#define __WINDOWS_CONTROL_WINDOW2_H
#include "Windows/Window.h"
#include "Windows/Defs.h"
namespace NWindows {
namespace NControl {
class CWindow2: public CWindow
{
public:
CWindow2(HWND newWindow = NULL): CWindow(newWindow){};
virtual ~CWindow2() {};
LRESULT DefProc(UINT message, WPARAM wParam, LPARAM lParam)
{ return ::DefWindowProc(_window, message, wParam, lParam); }
bool CreateEx(DWORD exStyle, LPCTSTR className,
LPCTSTR windowName, DWORD style,
int x, int y, int width, int height,
HWND parentWindow, HMENU idOrHMenu,
HINSTANCE instance);
virtual LRESULT OnMessage(UINT message, WPARAM wParam, LPARAM lParam);
virtual bool OnCreate(CREATESTRUCT *createStruct) { return true; }
// virtual LRESULT OnCommand(WPARAM wParam, LPARAM lParam);
virtual bool OnCommand(WPARAM wParam, LPARAM lParam, LRESULT &result);
virtual bool OnCommand(int code, int itemID, LPARAM lParam, LRESULT &result);
virtual bool OnSize(WPARAM wParam, int xSize, int ySize) { return false; }
virtual bool OnNotify(UINT controlID, LPNMHDR lParam, LRESULT &result) { return false; }
virtual void OnDestroy() { PostQuitMessage(0); }
virtual void OnClose() { Destroy(); }
/*
virtual LRESULT OnHelp(LPHELPINFO helpInfo) { OnHelp(); };
virtual LRESULT OnHelp() {};
virtual bool OnButtonClicked(int buttonID, HWND buttonHWND);
virtual void OnOK() {};
virtual void OnCancel() {};
*/
LONG_PTR SetMsgResult(LONG_PTR newLongPtr )
{ return SetLongPtr(DWLP_MSGRESULT, newLongPtr); }
LONG_PTR GetMsgResult() const
{ return GetLongPtr(DWLP_MSGRESULT); }
};
}}
#endif

113
Windows/DLL.cpp Executable file
View File

@@ -0,0 +1,113 @@
// Windows/DLL.cpp
#include "StdAfx.h"
#include "DLL.h"
#include "Defs.h"
#ifndef _UNICODE
#include "../Common/StringConvert.h"
#endif
namespace NWindows {
namespace NDLL {
CLibrary::~CLibrary()
{
Free();
}
bool CLibrary::Free()
{
if (_module == 0)
return true;
// MessageBox(0, TEXT(""), TEXT("Free"), 0);
// Sleep(5000);
if (!::FreeLibrary(_module))
return false;
_module = 0;
return true;
}
bool CLibrary::LoadOperations(HMODULE newModule)
{
if (newModule == NULL)
return false;
if(!Free())
return false;
_module = newModule;
return true;
}
bool CLibrary::LoadEx(LPCTSTR fileName, DWORD flags)
{
// MessageBox(0, fileName, TEXT("LoadEx"), 0);
return LoadOperations(::LoadLibraryEx(fileName, NULL, flags));
}
bool CLibrary::Load(LPCTSTR fileName)
{
// MessageBox(0, fileName, TEXT("Load"), 0);
// Sleep(5000);
// OutputDebugString(fileName);
// OutputDebugString(TEXT("\n"));
return LoadOperations(::LoadLibrary(fileName));
}
#ifndef _UNICODE
static inline UINT GetCurrentCodePage()
{ return ::AreFileApisANSI() ? CP_ACP : CP_OEMCP; }
bool CLibrary::LoadEx(LPCWSTR fileName, DWORD flags)
{
HMODULE module = ::LoadLibraryExW(fileName, NULL, flags);
if (module != 0)
return LoadOperations(module);
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return false;
return LoadEx(UnicodeStringToMultiByte(fileName, GetCurrentCodePage()), flags);
}
bool CLibrary::Load(LPCWSTR fileName)
{
HMODULE module = ::LoadLibraryW(fileName);
if (module != 0)
return LoadOperations(module);
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return false;
return Load(UnicodeStringToMultiByte(fileName, GetCurrentCodePage()));
}
#endif
bool MyGetModuleFileName(HMODULE hModule, CSysString &result)
{
result.Empty();
TCHAR fullPath[MAX_PATH + 2];
DWORD size = ::GetModuleFileName(hModule, fullPath, MAX_PATH + 1);
if (size <= MAX_PATH && size != 0)
{
result = fullPath;
return true;
}
return false;
}
#ifndef _UNICODE
bool MyGetModuleFileName(HMODULE hModule, UString &result)
{
result.Empty();
wchar_t fullPath[MAX_PATH + 2];
DWORD size = ::GetModuleFileNameW(hModule, fullPath, MAX_PATH + 1);
if (size <= MAX_PATH && size != 0)
{
result = fullPath;
return true;
}
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return false;
CSysString resultSys;
if (!MyGetModuleFileName(hModule, resultSys))
return false;
result = MultiByteToUnicodeString(resultSys, GetCurrentCodePage());
return true;
}
#endif
}}

56
Windows/DLL.h Executable file
View File

@@ -0,0 +1,56 @@
// Windows/DLL.h
#ifndef __WINDOWS_DLL_H
#define __WINDOWS_DLL_H
#pragma once
#include "../Common/String.h"
namespace NWindows {
namespace NDLL {
class CLibrary
{
bool LoadOperations(HMODULE newModule);
protected:
HMODULE _module;
public:
operator HMODULE() const { return _module; }
HMODULE* operator&() { return &_module; }
CLibrary():_module(NULL) {};
~CLibrary();
void Attach(HMODULE m)
{
Free();
_module = m;
}
HMODULE Detach()
{
HMODULE m = _module;
_module = NULL;
return m;
}
// operator HMODULE() const { return _module; };
// bool IsLoaded() const { return (_module != NULL); };
bool Free();
bool LoadEx(LPCTSTR fileName, DWORD flags = LOAD_LIBRARY_AS_DATAFILE);
bool Load(LPCTSTR fileName);
#ifndef _UNICODE
bool LoadEx(LPCWSTR fileName, DWORD flags = LOAD_LIBRARY_AS_DATAFILE);
bool Load(LPCWSTR fileName);
#endif
FARPROC GetProcAddress(LPCSTR procName) const
{ return ::GetProcAddress(_module, procName); }
};
bool MyGetModuleFileName(HMODULE hModule, CSysString &result);
#ifndef _UNICODE
bool MyGetModuleFileName(HMODULE hModule, UString &result);
#endif
}}
#endif

23
Windows/Defs.h Executable file
View File

@@ -0,0 +1,23 @@
// Windows/Defs.h
#pragma once
#ifndef __WINDOWS_DEFS_H
#define __WINDOWS_DEFS_H
inline bool BOOLToBool(BOOL value)
{ return (value != FALSE); }
inline BOOL BoolToBOOL(bool value)
{ return (value ? TRUE: FALSE); }
inline VARIANT_BOOL BoolToVARIANT_BOOL(bool value)
{ return (value ? VARIANT_TRUE: VARIANT_FALSE); }
inline bool VARIANT_BOOLToBool(VARIANT_BOOL value)
{ return (value != VARIANT_FALSE); }
// #define RETURN_IF_NOT_S_OK(x) { HRESULT __result_ = (x); if(__result_ != S_OK) return __result_; }
// #define RINOK(x) { HRESULT __result_ = (x); if(__result_ != S_OK) return __result_; }
#endif

59
Windows/Error.cpp Executable file
View File

@@ -0,0 +1,59 @@
// Windows/Error.h
#include "StdAfx.h"
#include "Windows/Error.h"
#ifndef _UNICODE
#include "Common/StringConvert.h"
#endif
namespace NWindows {
namespace NError {
bool MyFormatMessage(DWORD messageID, CSysString &message)
{
LPVOID msgBuf;
if(::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
messageID,
0, // Default language
(LPTSTR) &msgBuf,
0,
NULL) == 0)
return false;
message = (LPCTSTR)msgBuf;
::LocalFree(msgBuf);
return true;
}
#ifndef _UNICODE
bool MyFormatMessage(DWORD messageID, UString &message)
{
LPVOID msgBuf;
if(::FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
messageID,
0, // Default language
(LPWSTR) &msgBuf,
0,
NULL) == 0)
{
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return false;
CSysString messageSys;
bool result = MyFormatMessage(messageID, messageSys);
message = GetUnicodeString(messageSys);
return result;
}
message = (LPCWSTR)msgBuf;
::LocalFree(msgBuf);
return true;
}
#endif
}}

35
Windows/Error.h Executable file
View File

@@ -0,0 +1,35 @@
// Windows/Error.h
#pragma once
#ifndef __WINDOWS_ERROR_H
#define __WINDOWS_ERROR_H
#include "Common/String.h"
namespace NWindows {
namespace NError {
bool MyFormatMessage(DWORD messageID, CSysString &message);
inline CSysString MyFormatMessage(DWORD messageID)
{
CSysString message;
MyFormatMessage(messageID, message);
return message;
}
#ifdef _UNICODE
inline UString MyFormatMessageW(DWORD messageID)
{ return MyFormatMessage(messageID); }
#else
bool MyFormatMessage(DWORD messageID, UString &message);
inline UString MyFormatMessageW(DWORD messageID)
{
UString message;
MyFormatMessage(messageID, message);
return message;
}
#endif
}}
#endif

713
Windows/FileDir.cpp Executable file
View File

@@ -0,0 +1,713 @@
// Windows/FileDir.cpp
#include "StdAfx.h"
#include "FileDir.h"
#include "FileName.h"
#include "FileFind.h"
#include "Defs.h"
#ifndef _UNICODE
#include "../Common/StringConvert.h"
#endif
namespace NWindows {
namespace NFile {
namespace NDirectory {
#ifndef _UNICODE
static inline UINT GetCurrentCodePage()
{ return ::AreFileApisANSI() ? CP_ACP : CP_OEMCP; }
#endif
bool MyGetWindowsDirectory(CSysString &path)
{
DWORD needLength = ::GetWindowsDirectory(path.GetBuffer(MAX_PATH + 1), MAX_PATH + 1);
path.ReleaseBuffer();
return (needLength > 0 && needLength <= MAX_PATH);
}
bool MyGetSystemDirectory(CSysString &path)
{
DWORD needLength = ::GetSystemDirectory(path.GetBuffer(MAX_PATH + 1), MAX_PATH + 1);
path.ReleaseBuffer();
return (needLength > 0 && needLength <= MAX_PATH);
}
#ifndef _UNICODE
bool MyGetWindowsDirectory(UString &path)
{
DWORD needLength = ::GetWindowsDirectoryW(path.GetBuffer(MAX_PATH + 1), MAX_PATH + 1);
path.ReleaseBuffer();
if (needLength != 0)
return (needLength <= MAX_PATH);
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return false;
CSysString sysPath;
if (!MyGetWindowsDirectory(sysPath))
return false;
path = MultiByteToUnicodeString(sysPath, GetCurrentCodePage());
return true;
}
bool MyGetSystemDirectory(UString &path)
{
DWORD needLength = ::GetSystemDirectoryW(path.GetBuffer(MAX_PATH + 1), MAX_PATH + 1);
path.ReleaseBuffer();
if (needLength != 0)
return (needLength <= MAX_PATH);
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return false;
CSysString sysPath;
if (!MyGetSystemDirectory(sysPath))
return false;
path = MultiByteToUnicodeString(sysPath, GetCurrentCodePage());
return true;
}
#endif
#ifndef _UNICODE
bool MySetFileAttributes(LPCWSTR fileName, DWORD fileAttributes)
{
if (::SetFileAttributesW(fileName, fileAttributes))
return true;
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return false;
return MySetFileAttributes(UnicodeStringToMultiByte(fileName,
GetCurrentCodePage()), fileAttributes);
}
bool MyRemoveDirectory(LPCWSTR pathName)
{
if (::RemoveDirectoryW(pathName))
return true;
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return false;
return MyRemoveDirectory(UnicodeStringToMultiByte(pathName,
GetCurrentCodePage()));
}
bool MyMoveFile(LPCWSTR existFileName, LPCWSTR newFileName)
{
if (::MoveFileW(existFileName, newFileName))
return true;
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return false;
UINT codePage = GetCurrentCodePage();
return MyMoveFile(UnicodeStringToMultiByte(existFileName, codePage),
UnicodeStringToMultiByte(newFileName, codePage));
}
#endif
bool MyCreateDirectory(LPCTSTR pathName)
{
return BOOLToBool(::CreateDirectory(pathName, NULL));
}
#ifndef _UNICODE
bool MyCreateDirectory(LPCWSTR pathName)
{
if (::CreateDirectoryW(pathName, NULL))
return true;
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return false;
return MyCreateDirectory(UnicodeStringToMultiByte(pathName,
GetCurrentCodePage()));
}
#endif
/*
bool CreateComplexDirectory(LPCTSTR pathName)
{
NName::CParsedPath path;
path.ParsePath(pathName);
CSysString fullPath = path.Prefix;
DWORD errorCode = ERROR_SUCCESS;
for(int i = 0; i < path.PathParts.Size(); i++)
{
const CSysString &string = path.PathParts[i];
if(string.IsEmpty())
{
if(i != path.PathParts.Size() - 1)
return false;
return true;
}
fullPath += path.PathParts[i];
if(!MyCreateDirectory(fullPath))
{
DWORD errorCode = GetLastError();
if(errorCode != ERROR_ALREADY_EXISTS)
return false;
}
fullPath += NName::kDirDelimiter;
}
return true;
}
*/
bool CreateComplexDirectory(LPCTSTR _aPathName)
{
CSysString pathName = _aPathName;
int pos = pathName.ReverseFind(TEXT('\\'));
if (pos > 0 && pos == pathName.Length() - 1)
{
if (pathName.Length() == 3 && pathName[1] == ':')
return true; // Disk folder;
pathName.Delete(pos);
}
CSysString pathName2 = pathName;
pos = pathName.Length();
while(true)
{
if(MyCreateDirectory(pathName))
break;
if(::GetLastError() == ERROR_ALREADY_EXISTS)
{
NFind::CFileInfo fileInfo;
if (!NFind::FindFile(pathName, fileInfo)) // For network folders
return true;
if (!fileInfo.IsDirectory())
return false;
break;
}
pos = pathName.ReverseFind(TEXT('\\'));
if (pos < 0 || pos == 0)
return false;
if (pathName[pos - 1] == ':')
return false;
pathName = pathName.Left(pos);
}
pathName = pathName2;
while(pos < pathName.Length())
{
pos = pathName.Find(TEXT('\\'), pos + 1);
if (pos < 0)
pos = pathName.Length();
if(!MyCreateDirectory(pathName.Left(pos)))
return false;
}
return true;
}
#ifndef _UNICODE
bool CreateComplexDirectory(LPCWSTR _aPathName)
{
UString pathName = _aPathName;
int pos = pathName.ReverseFind(L'\\');
if (pos > 0 && pos == pathName.Length() - 1)
{
if (pathName.Length() == 3 && pathName[1] == L':')
return true; // Disk folder;
pathName.Delete(pos);
}
UString pathName2 = pathName;
pos = pathName.Length();
while(true)
{
if(MyCreateDirectory(pathName))
break;
if(::GetLastError() == ERROR_ALREADY_EXISTS)
{
NFind::CFileInfoW fileInfo;
if (!NFind::FindFile(pathName, fileInfo)) // For network folders
return true;
if (!fileInfo.IsDirectory())
return false;
break;
}
pos = pathName.ReverseFind(L'\\');
if (pos < 0 || pos == 0)
return false;
if (pathName[pos - 1] == L':')
return false;
pathName = pathName.Left(pos);
}
pathName = pathName2;
while(pos < pathName.Length())
{
pos = pathName.Find(L'\\', pos + 1);
if (pos < 0)
pos = pathName.Length();
if(!MyCreateDirectory(pathName.Left(pos)))
return false;
}
return true;
}
#endif
bool DeleteFileAlways(LPCTSTR name)
{
if(!::SetFileAttributes(name, 0))
return false;
return BOOLToBool(::DeleteFile(name));
}
#ifndef _UNICODE
bool DeleteFileAlways(LPCWSTR name)
{
if(!MySetFileAttributes(name, 0))
return false;
if (::DeleteFileW(name))
return true;
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return false;
return DeleteFileAlways(UnicodeStringToMultiByte(name,
GetCurrentCodePage()));
}
#endif
static bool RemoveDirectorySubItems2(const CSysString pathPrefix,
const NFind::CFileInfo &fileInfo)
{
if(fileInfo.IsDirectory())
return RemoveDirectoryWithSubItems(pathPrefix + fileInfo.Name);
else
return DeleteFileAlways(pathPrefix + fileInfo.Name);
}
bool RemoveDirectoryWithSubItems(const CSysString &path)
{
NFind::CFileInfo fileInfo;
CSysString pathPrefix = path + NName::kDirDelimiter;
{
NFind::CEnumerator enumerator(pathPrefix + TCHAR(NName::kAnyStringWildcard));
while(enumerator.Next(fileInfo))
if(!RemoveDirectorySubItems2(pathPrefix, fileInfo))
return false;
}
if(!BOOLToBool(::SetFileAttributes(path, 0)))
return false;
return BOOLToBool(::RemoveDirectory(path));
}
#ifndef _UNICODE
static bool RemoveDirectorySubItems2(const UString pathPrefix,
const NFind::CFileInfoW &fileInfo)
{
if(fileInfo.IsDirectory())
return RemoveDirectoryWithSubItems(pathPrefix + fileInfo.Name);
else
return DeleteFileAlways(pathPrefix + fileInfo.Name);
}
bool RemoveDirectoryWithSubItems(const UString &path)
{
NFind::CFileInfoW fileInfo;
UString pathPrefix = path + UString(NName::kDirDelimiter);
{
NFind::CEnumeratorW enumerator(pathPrefix + UString(NName::kAnyStringWildcard));
while(enumerator.Next(fileInfo))
if(!RemoveDirectorySubItems2(pathPrefix, fileInfo))
return false;
}
if(!MySetFileAttributes(path, 0))
return false;
return MyRemoveDirectory(path);
}
#endif
#ifndef _WIN32_WCE
bool MyGetShortPathName(LPCTSTR longPath, CSysString &shortPath)
{
DWORD needLength = ::GetShortPathName(longPath,
shortPath.GetBuffer(MAX_PATH + 1), MAX_PATH + 1);
shortPath.ReleaseBuffer();
if (needLength == 0 || needLength >= MAX_PATH)
return false;
return true;
}
bool MyGetFullPathName(LPCTSTR fileName, CSysString &resultPath,
int &fileNamePartStartIndex)
{
LPTSTR fileNamePointer = 0;
LPTSTR buffer = resultPath.GetBuffer(MAX_PATH);
DWORD needLength = ::GetFullPathName(fileName, MAX_PATH + 1,
buffer, &fileNamePointer);
resultPath.ReleaseBuffer();
if (needLength == 0 || needLength >= MAX_PATH)
return false;
if (fileNamePointer == 0)
fileNamePartStartIndex = lstrlen(fileName);
else
fileNamePartStartIndex = fileNamePointer - buffer;
return true;
}
#ifndef _UNICODE
bool MyGetFullPathName(LPCWSTR fileName, UString &resultPath,
int &fileNamePartStartIndex)
{
resultPath.Empty();
LPWSTR fileNamePointer = 0;
LPWSTR buffer = resultPath.GetBuffer(MAX_PATH);
DWORD needLength = ::GetFullPathNameW(fileName, MAX_PATH + 1,
buffer, &fileNamePointer);
resultPath.ReleaseBuffer();
if (needLength == 0)
{
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return false;
const UINT currentPage = GetCurrentCodePage();
CSysString sysPath;
if (!MyGetFullPathName(UnicodeStringToMultiByte(fileName,
currentPage), sysPath, fileNamePartStartIndex))
return false;
UString resultPath1 = MultiByteToUnicodeString(
sysPath.Left(fileNamePartStartIndex), currentPage);
UString resultPath2 = MultiByteToUnicodeString(
sysPath.Mid(fileNamePartStartIndex), currentPage);
fileNamePartStartIndex = resultPath1.Length();
resultPath = resultPath1 + resultPath2;
return true;
}
else if (needLength >= MAX_PATH)
return false;
if (fileNamePointer == 0)
fileNamePartStartIndex = MyStringLen(fileName);
else
fileNamePartStartIndex = fileNamePointer - buffer;
return true;
}
#endif
bool MyGetFullPathName(LPCTSTR fileName, CSysString &path)
{
int index;
return MyGetFullPathName(fileName, path, index);
}
#ifndef _UNICODE
bool MyGetFullPathName(LPCWSTR fileName, UString &path)
{
int index;
return MyGetFullPathName(fileName, path, index);
}
#endif
bool GetOnlyName(LPCTSTR fileName, CSysString &resultName)
{
int index;
if (!MyGetFullPathName(fileName, resultName, index))
return false;
resultName = resultName.Mid(index);
return true;
}
#ifndef _UNICODE
bool GetOnlyName(LPCWSTR fileName, UString &resultName)
{
int index;
if (!MyGetFullPathName(fileName, resultName, index))
return false;
resultName = resultName.Mid(index);
return true;
}
#endif
bool GetOnlyDirPrefix(LPCTSTR fileName, CSysString &resultName)
{
int index;
if (!MyGetFullPathName(fileName, resultName, index))
return false;
resultName = resultName.Left(index);
return true;
}
#ifndef _UNICODE
bool GetOnlyDirPrefix(LPCWSTR fileName, UString &resultName)
{
int index;
if (!MyGetFullPathName(fileName, resultName, index))
return false;
resultName = resultName.Left(index);
return true;
}
#endif
bool MyGetCurrentDirectory(CSysString &path)
{
DWORD needLength = ::GetCurrentDirectory(MAX_PATH + 1,
path.GetBuffer(MAX_PATH + 1));
path.ReleaseBuffer();
return (needLength > 0 && needLength <= MAX_PATH);
}
#ifndef _UNICODE
bool MySetCurrentDirectory(LPCWSTR path)
{
if (::SetCurrentDirectoryW(path))
return true;
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return false;
return MySetCurrentDirectory(UnicodeStringToMultiByte(path,
GetCurrentCodePage()));
}
bool MyGetCurrentDirectory(UString &path)
{
DWORD needLength = ::GetCurrentDirectoryW(MAX_PATH + 1,
path.GetBuffer(MAX_PATH + 1));
path.ReleaseBuffer();
if (needLength != 0)
return (needLength <= MAX_PATH);
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return false;
CSysString sysPath;
if (!MyGetCurrentDirectory(sysPath))
return false;
path = MultiByteToUnicodeString(sysPath, GetCurrentCodePage());
return true;
}
#endif
#endif
bool MySearchPath(LPCTSTR path, LPCTSTR fileName, LPCTSTR extension,
CSysString &resultPath, UINT32 &filePart)
{
LPTSTR filePartPointer;
DWORD value = ::SearchPath(path, fileName, extension,
MAX_PATH, resultPath.GetBuffer(MAX_PATH), &filePartPointer);
filePart = filePartPointer - (LPCTSTR)resultPath;
resultPath.ReleaseBuffer();
if (value == 0 || value > MAX_PATH)
return false;
return true;
}
#ifndef _UNICODE
bool MySearchPath(LPCWSTR path, LPCWSTR fileName, LPCWSTR extension,
UString &resultPath, UINT32 &filePart)
{
LPWSTR filePartPointer = 0;
DWORD value = ::SearchPathW(path, fileName, extension,
MAX_PATH, resultPath.GetBuffer(MAX_PATH), &filePartPointer);
resultPath.ReleaseBuffer();
if (value != 0)
return (value <= MAX_PATH);
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return false;
const UINT currentPage = GetCurrentCodePage();
CSysString sysPath;
if (!MySearchPath(
path != 0 ? (LPCTSTR)UnicodeStringToMultiByte(path, currentPage): 0,
fileName != 0 ? (LPCTSTR)UnicodeStringToMultiByte(fileName, currentPage): 0,
extension != 0 ? (LPCTSTR)UnicodeStringToMultiByte(extension, currentPage): 0,
sysPath, filePart))
return false;
UString resultPath1 = MultiByteToUnicodeString(
sysPath.Left(filePart), currentPage);
UString resultPath2 = MultiByteToUnicodeString(
sysPath.Mid(filePart), currentPage);
filePart = resultPath1.Length();
resultPath = resultPath1 + resultPath2;
return true;
}
#endif
bool MyGetTempPath(CSysString &path)
{
DWORD needLength = ::GetTempPath(MAX_PATH + 1,
path.GetBuffer(MAX_PATH));
path.ReleaseBuffer();
return (needLength > 0 && needLength <= MAX_PATH);
}
#ifndef _UNICODE
bool MyGetTempPath(UString &path)
{
path.Empty();
DWORD needLength = ::GetTempPathW(MAX_PATH + 1,
path.GetBuffer(MAX_PATH));
path.ReleaseBuffer();
if (needLength == 0)
{
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return false;
CSysString sysPath;
if (!MyGetTempPath(sysPath))
return false;
path = MultiByteToUnicodeString(sysPath, GetCurrentCodePage());
return true;
}
return (needLength > 0 && needLength <= MAX_PATH);
}
#endif
UINT MyGetTempFileName(LPCTSTR dirPath, LPCTSTR prefix, CSysString &path)
{
UINT number = ::GetTempFileName(dirPath, prefix, 0,
path.GetBuffer(MAX_PATH));
path.ReleaseBuffer();
return number;
}
#ifndef _UNICODE
UINT MyGetTempFileName(LPCWSTR dirPath, LPCWSTR prefix, UString &path)
{
UINT number = ::GetTempFileNameW(dirPath, prefix, 0,
path.GetBuffer(MAX_PATH));
path.ReleaseBuffer();
if (number == 0)
{
if (::GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
const UINT currentPage = GetCurrentCodePage();
CSysString sysPath;
number = MyGetTempFileName(
dirPath ? (LPCTSTR)UnicodeStringToMultiByte(dirPath, currentPage): 0,
prefix ? (LPCTSTR)UnicodeStringToMultiByte(prefix, currentPage): 0,
sysPath);
path = MultiByteToUnicodeString(sysPath, currentPage);
}
}
return number;
}
#endif
UINT CTempFile::Create(LPCTSTR dirPath, LPCTSTR prefix, CSysString &resultPath)
{
Remove();
UINT number = MyGetTempFileName(dirPath, prefix, resultPath);
if(number != 0)
{
_fileName = resultPath;
_mustBeDeleted = true;
}
return number;
}
bool CTempFile::Create(LPCTSTR prefix, CSysString &resultPath)
{
CSysString tempPath;
if(!MyGetTempPath(tempPath))
return false;
if (Create(tempPath, prefix, resultPath) != 0)
return true;
if(!MyGetWindowsDirectory(tempPath))
return false;
return (Create(tempPath, prefix, resultPath) != 0);
}
bool CTempFile::Remove()
{
if (!_mustBeDeleted)
return true;
_mustBeDeleted = !DeleteFileAlways(_fileName);
return !_mustBeDeleted;
}
#ifndef _UNICODE
UINT CTempFileW::Create(LPCWSTR dirPath, LPCWSTR prefix, UString &resultPath)
{
Remove();
UINT number = MyGetTempFileName(dirPath, prefix, resultPath);
if(number != 0)
{
_fileName = resultPath;
_mustBeDeleted = true;
}
return number;
}
bool CTempFileW::Create(LPCWSTR prefix, UString &resultPath)
{
UString tempPath;
if(!MyGetTempPath(tempPath))
return false;
if (Create(tempPath, prefix, resultPath) != 0)
return true;
if(!MyGetWindowsDirectory(tempPath))
return false;
return (Create(tempPath, prefix, resultPath) != 0);
}
bool CTempFileW::Remove()
{
if (!_mustBeDeleted)
return true;
_mustBeDeleted = !DeleteFileAlways(_fileName);
return !_mustBeDeleted;
}
#endif
bool CreateTempDirectory(LPCTSTR prefix, CSysString &dirName)
{
/*
CSysString prefix = tempPath + prefixChars;
CRandom random;
random.Init();
*/
while(true)
{
CTempFile tempFile;
if (!tempFile.Create(prefix, dirName))
return false;
if (!::DeleteFile(dirName))
return false;
/*
UINT32 randomNumber = random.Generate();
TCHAR randomNumberString[32];
_stprintf(randomNumberString, _T("%04X"), randomNumber);
dirName = prefix + randomNumberString;
*/
if(NFind::DoesFileExist(dirName))
continue;
if (MyCreateDirectory(dirName))
return true;
if (::GetLastError() != ERROR_ALREADY_EXISTS)
return false;
}
}
bool CTempDirectory::Create(LPCTSTR prefix)
{
Remove();
return (_mustBeDeleted = CreateTempDirectory(prefix, _tempDir));
}
#ifndef _UNICODE
bool CreateTempDirectory(LPCWSTR prefix, UString &dirName)
{
/*
CSysString prefix = tempPath + prefixChars;
CRandom random;
random.Init();
*/
while(true)
{
CTempFileW tempFile;
if (!tempFile.Create(prefix, dirName))
return false;
if (!DeleteFileAlways(dirName))
return false;
/*
UINT32 randomNumber = random.Generate();
TCHAR randomNumberString[32];
_stprintf(randomNumberString, _T("%04X"), randomNumber);
dirName = prefix + randomNumberString;
*/
if(NFind::DoesFileExist(dirName))
continue;
if (MyCreateDirectory(dirName))
return true;
if (::GetLastError() != ERROR_ALREADY_EXISTS)
return false;
}
}
bool CTempDirectoryW::Create(LPCWSTR prefix)
{
Remove();
return (_mustBeDeleted = CreateTempDirectory(prefix, _tempDir));
}
#endif
}}}

189
Windows/FileDir.h Executable file
View File

@@ -0,0 +1,189 @@
// Windows/FileDir.h
#pragma once
#ifndef __WINDOWS_FILEDIR_H
#define __WINDOWS_FILEDIR_H
#include "../Common/String.h"
#include "Defs.h"
namespace NWindows {
namespace NFile {
namespace NDirectory {
bool MyGetWindowsDirectory(CSysString &path);
bool MyGetSystemDirectory(CSysString &path);
#ifndef _UNICODE
bool MyGetWindowsDirectory(UString &path);
bool MyGetSystemDirectory(UString &path);
#endif
inline bool MySetFileAttributes(LPCTSTR fileName, DWORD fileAttributes)
{ return BOOLToBool(::SetFileAttributes(fileName, fileAttributes)); }
#ifndef _UNICODE
bool MySetFileAttributes(LPCWSTR fileName, DWORD fileAttributes);
#endif
inline bool MyMoveFile(LPCTSTR existFileName, LPCTSTR newFileName)
{ return BOOLToBool(::MoveFile(existFileName, newFileName)); }
#ifndef _UNICODE
bool MyMoveFile(LPCWSTR existFileName, LPCWSTR newFileName);
#endif
inline bool MyRemoveDirectory(LPCTSTR pathName)
{ return BOOLToBool(::RemoveDirectory(pathName)); }
#ifndef _UNICODE
bool MyRemoveDirectory(LPCWSTR pathName);
#endif
bool MyCreateDirectory(LPCTSTR pathName);
bool CreateComplexDirectory(LPCTSTR pathName);
#ifndef _UNICODE
bool MyCreateDirectory(LPCWSTR pathName);
bool CreateComplexDirectory(LPCWSTR pathName);
#endif
bool DeleteFileAlways(LPCTSTR name);
#ifndef _UNICODE
bool DeleteFileAlways(LPCWSTR name);
#endif
bool RemoveDirectoryWithSubItems(const CSysString &path);
#ifndef _UNICODE
bool RemoveDirectoryWithSubItems(const UString &path);
#endif
#ifndef _WIN32_WCE
bool MyGetShortPathName(LPCTSTR longPath, CSysString &shortPath);
bool MyGetFullPathName(LPCTSTR fileName, CSysString &resultPath,
int &fileNamePartStartIndex);
bool MyGetFullPathName(LPCTSTR fileName, CSysString &resultPath);
bool GetOnlyName(LPCTSTR fileName, CSysString &resultName);
bool GetOnlyDirPrefix(LPCTSTR fileName, CSysString &resultName);
#ifndef _UNICODE
bool MyGetFullPathName(LPCWSTR fileName, UString &resultPath,
int &fileNamePartStartIndex);
bool MyGetFullPathName(LPCWSTR fileName, UString &resultPath);
bool GetOnlyName(LPCWSTR fileName, UString &resultName);
bool GetOnlyDirPrefix(LPCWSTR fileName, UString &resultName);
#endif
inline bool MySetCurrentDirectory(LPCTSTR path)
{ return BOOLToBool(::SetCurrentDirectory(path)); }
bool MyGetCurrentDirectory(CSysString &resultPath);
#ifndef _UNICODE
bool MySetCurrentDirectory(LPCWSTR path);
bool MyGetCurrentDirectory(UString &resultPath);
#endif
#endif
bool MySearchPath(LPCTSTR path, LPCTSTR fileName, LPCTSTR extension,
CSysString &resultPath, UINT32 &filePart);
#ifndef _UNICODE
bool MySearchPath(LPCWSTR path, LPCWSTR fileName, LPCWSTR extension,
UString &resultPath, UINT32 &filePart);
#endif
inline bool MySearchPath(LPCTSTR path, LPCTSTR fileName, LPCTSTR extension,
CSysString &resultPath)
{
UINT32 value;
return MySearchPath(path, fileName, extension, resultPath, value);
}
#ifndef _UNICODE
inline bool MySearchPath(LPCWSTR path, LPCWSTR fileName, LPCWSTR extension,
UString &resultPath)
{
UINT32 value;
return MySearchPath(path, fileName, extension, resultPath, value);
}
#endif
bool MyGetTempPath(CSysString &resultPath);
#ifndef _UNICODE
bool MyGetTempPath(UString &resultPath);
#endif
UINT MyGetTempFileName(LPCTSTR dirPath, LPCTSTR prefix, CSysString &resultPath);
#ifndef _UNICODE
UINT MyGetTempFileName(LPCWSTR dirPath, LPCWSTR prefix, UString &resultPath);
#endif
class CTempFile
{
bool _mustBeDeleted;
CSysString _fileName;
public:
CTempFile(): _mustBeDeleted(false) {}
~CTempFile() { Remove(); }
void DisableDeleting() { _mustBeDeleted = false; }
UINT Create(LPCTSTR dirPath, LPCTSTR prefix, CSysString &resultPath);
bool Create(LPCTSTR prefix, CSysString &resultPath);
bool Remove();
};
#ifdef _UNICODE
typedef CTempFile CTempFileW;
#else
class CTempFileW
{
bool _mustBeDeleted;
UString _fileName;
public:
CTempFileW(): _mustBeDeleted(false) {}
~CTempFileW() { Remove(); }
void DisableDeleting() { _mustBeDeleted = false; }
UINT Create(LPCWSTR dirPath, LPCWSTR prefix, UString &resultPath);
bool Create(LPCWSTR prefix, UString &resultPath);
bool Remove();
};
#endif
bool CreateTempDirectory(LPCTSTR prefixChars, CSysString &dirName);
class CTempDirectory
{
bool _mustBeDeleted;
CSysString _tempDir;
public:
const CSysString &GetPath() const { return _tempDir; }
CTempDirectory(): _mustBeDeleted(false) {}
~CTempDirectory() { Remove(); }
bool Create(LPCTSTR prefix) ;
bool Remove()
{
if (!_mustBeDeleted)
return true;
_mustBeDeleted = !RemoveDirectoryWithSubItems(_tempDir);
return (!_mustBeDeleted);
}
};
#ifdef _UNICODE
typedef CTempDirectory CTempDirectoryW;
#else
class CTempDirectoryW
{
bool _mustBeDeleted;
UString _tempDir;
public:
const UString &GetPath() const { return _tempDir; }
CTempDirectoryW(): _mustBeDeleted(false) {}
~CTempDirectoryW() { Remove(); }
bool Create(LPCWSTR prefix) ;
bool Remove()
{
if (!_mustBeDeleted)
return true;
_mustBeDeleted = !RemoveDirectoryWithSubItems(_tempDir);
return (!_mustBeDeleted);
}
};
#endif
}}}
#endif

312
Windows/FileFind.cpp Executable file
View File

@@ -0,0 +1,312 @@
// Windows/FileFind.cpp
#include "StdAfx.h"
#include "FileFind.h"
#ifndef _UNICODE
#include "../Common/StringConvert.h"
#endif
namespace NWindows {
namespace NFile {
namespace NFind {
static const TCHAR kDot = TEXT('.');
bool CFileInfo::IsDots() const
{
if (!IsDirectory() || Name.IsEmpty())
return false;
if (Name[0] != kDot)
return false;
return Name.Length() == 1 || (Name[1] == kDot && Name.Length() == 2);
}
#ifndef _UNICODE
bool CFileInfoW::IsDots() const
{
if (!IsDirectory() || Name.IsEmpty())
return false;
if (Name[0] != kDot)
return false;
return Name.Length() == 1 || (Name[1] == kDot && Name.Length() == 2);
}
#endif
static void ConvertWIN32_FIND_DATA_To_FileInfo(
const WIN32_FIND_DATA &findData,
CFileInfo &fileInfo)
{
fileInfo.Attributes = findData.dwFileAttributes;
fileInfo.CreationTime = findData.ftCreationTime;
fileInfo.LastAccessTime = findData.ftLastAccessTime;
fileInfo.LastWriteTime = findData.ftLastWriteTime;
fileInfo.Size = (((UINT64)findData.nFileSizeHigh) << 32) +
findData.nFileSizeLow;
fileInfo.Name = findData.cFileName;
#ifndef _WIN32_WCE
fileInfo.ReparseTag = findData.dwReserved0;
#else
fileInfo.ObjectID = findData.dwOID;
#endif
}
#ifndef _UNICODE
static inline UINT GetCurrentCodePage()
{ return ::AreFileApisANSI() ? CP_ACP : CP_OEMCP; }
static void ConvertWIN32_FIND_DATA_To_FileInfo(
const WIN32_FIND_DATAW &findData,
CFileInfoW &fileInfo)
{
fileInfo.Attributes = findData.dwFileAttributes;
fileInfo.CreationTime = findData.ftCreationTime;
fileInfo.LastAccessTime = findData.ftLastAccessTime;
fileInfo.LastWriteTime = findData.ftLastWriteTime;
fileInfo.Size = (((UINT64)findData.nFileSizeHigh) << 32) +
findData.nFileSizeLow;
fileInfo.Name = findData.cFileName;
#ifndef _WIN32_WCE
fileInfo.ReparseTag = findData.dwReserved0;
#else
fileInfo.ObjectID = findData.dwOID;
#endif
}
static void ConvertWIN32_FIND_DATA_To_FileInfo(
const WIN32_FIND_DATA &findData,
CFileInfoW &fileInfo)
{
fileInfo.Attributes = findData.dwFileAttributes;
fileInfo.CreationTime = findData.ftCreationTime;
fileInfo.LastAccessTime = findData.ftLastAccessTime;
fileInfo.LastWriteTime = findData.ftLastWriteTime;
fileInfo.Size = (((UINT64)findData.nFileSizeHigh) << 32) +
findData.nFileSizeLow;
fileInfo.Name = GetUnicodeString(findData.cFileName, GetCurrentCodePage());
#ifndef _WIN32_WCE
fileInfo.ReparseTag = findData.dwReserved0;
#else
fileInfo.ObjectID = findData.dwOID;
#endif
}
#endif
////////////////////////////////
// CFindFile
bool CFindFile::Close()
{
if(!_handleAllocated)
return true;
bool result = BOOLToBool(::FindClose(_handle));
_handleAllocated = !result;
return result;
}
bool CFindFile::FindFirst(LPCTSTR wildcard, CFileInfo &fileInfo)
{
Close();
WIN32_FIND_DATA findData;
_handle = ::FindFirstFile(wildcard, &findData);
_handleAllocated = (_handle != INVALID_HANDLE_VALUE);
if (_handleAllocated)
ConvertWIN32_FIND_DATA_To_FileInfo(findData, fileInfo);
return _handleAllocated;
}
#ifndef _UNICODE
bool CFindFile::FindFirst(LPCWSTR wildcard, CFileInfoW &fileInfo)
{
Close();
WIN32_FIND_DATAW findDataW;
::SetLastError(0);
_handle = ::FindFirstFileW(wildcard, &findDataW);
if ((_handle == INVALID_HANDLE_VALUE || _handle == 0) &&
::GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
WIN32_FIND_DATA findData;
_handle = ::FindFirstFile(UnicodeStringToMultiByte(wildcard,
GetCurrentCodePage()), &findData);
_handleAllocated = (_handle != INVALID_HANDLE_VALUE);
if (_handleAllocated)
ConvertWIN32_FIND_DATA_To_FileInfo(findData, fileInfo);
}
else
{
_handleAllocated = (_handle != INVALID_HANDLE_VALUE);
if (_handleAllocated)
ConvertWIN32_FIND_DATA_To_FileInfo(findDataW, fileInfo);
}
return _handleAllocated;
}
#endif
bool CFindFile::FindNext(CFileInfo &fileInfo)
{
WIN32_FIND_DATA findData;
bool result = BOOLToBool(::FindNextFile(_handle, &findData));
if (result)
ConvertWIN32_FIND_DATA_To_FileInfo(findData, fileInfo);
return result;
}
#ifndef _UNICODE
bool CFindFile::FindNext(CFileInfoW &fileInfo)
{
WIN32_FIND_DATAW findDataW;
if (::FindNextFileW(_handle, &findDataW))
{
ConvertWIN32_FIND_DATA_To_FileInfo(findDataW, fileInfo);
return true;
}
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return false;
WIN32_FIND_DATA findData;
if (!::FindNextFile(_handle, &findData))
return false;
ConvertWIN32_FIND_DATA_To_FileInfo(findData, fileInfo);
return true;
}
#endif
bool FindFile(LPCTSTR wildcard, CFileInfo &fileInfo)
{
CFindFile finder;
return finder.FindFirst(wildcard, fileInfo);
}
#ifndef _UNICODE
bool FindFile(LPCWSTR wildcard, CFileInfoW &fileInfo)
{
CFindFile finder;
return finder.FindFirst(wildcard, fileInfo);
}
#endif
bool DoesFileExist(LPCTSTR name)
{
CFileInfo fileInfo;
return FindFile(name, fileInfo);
}
#ifndef _UNICODE
bool DoesFileExist(LPCWSTR name)
{
CFileInfoW fileInfo;
return FindFile(name, fileInfo);
}
#endif
/////////////////////////////////////
// CEnumerator
bool CEnumerator::NextAny(CFileInfo &fileInfo)
{
if(_findFile.IsHandleAllocated())
return _findFile.FindNext(fileInfo);
else
return _findFile.FindFirst(_wildcard, fileInfo);
}
bool CEnumerator::Next(CFileInfo &fileInfo)
{
while(true)
{
if(!NextAny(fileInfo))
return false;
if(!fileInfo.IsDots())
return true;
}
}
#ifndef _UNICODE
bool CEnumeratorW::NextAny(CFileInfoW &fileInfo)
{
if(_findFile.IsHandleAllocated())
return _findFile.FindNext(fileInfo);
else
return _findFile.FindFirst(_wildcard, fileInfo);
}
bool CEnumeratorW::Next(CFileInfoW &fileInfo)
{
while(true)
{
if(!NextAny(fileInfo))
return false;
if(!fileInfo.IsDots())
return true;
}
}
#endif
////////////////////////////////
// CFindChangeNotification
bool CFindChangeNotification::Close()
{
if(_handle == INVALID_HANDLE_VALUE || _handle == 0)
return true;
bool result = BOOLToBool(::FindCloseChangeNotification(_handle));
if (result)
_handle = INVALID_HANDLE_VALUE;
return result;
}
HANDLE CFindChangeNotification::FindFirst(LPCTSTR pathName, bool watchSubtree,
DWORD notifyFilter)
{
_handle = ::FindFirstChangeNotification(pathName,
BoolToBOOL(watchSubtree), notifyFilter);
return _handle;
}
#ifndef _UNICODE
HANDLE CFindChangeNotification::FindFirst(LPCWSTR pathName, bool watchSubtree,
DWORD notifyFilter)
{
::SetLastError(0);
_handle = ::FindFirstChangeNotificationW(pathName,
BoolToBOOL(watchSubtree), notifyFilter);
if ((_handle == 0 || _handle == INVALID_HANDLE_VALUE) &&
::GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
return FindFirst(UnicodeStringToMultiByte(pathName,
GetCurrentCodePage()), watchSubtree, notifyFilter);
return _handle;
}
#endif
#ifndef _WIN32_WCE
bool MyGetLogicalDriveStrings(CSysStringVector &driveStrings)
{
driveStrings.Clear();
UINT32 size = GetLogicalDriveStrings(0, NULL);
if(size == 0)
return false;
CSysString buffer;
UINT32 newSize = GetLogicalDriveStrings(size, buffer.GetBuffer(size));
if(newSize == 0)
return false;
if(newSize > size)
return false;
CSysString string;
for(UINT32 i = 0; i < newSize; i++)
{
TCHAR c = buffer[i];
if(c == TEXT('\0'))
{
driveStrings.Add(string);
string.Empty();
}
else
string += c;
}
if(!string.IsEmpty())
return false;
return true;
}
#endif
}}}

174
Windows/FileFind.h Executable file
View File

@@ -0,0 +1,174 @@
// Windows/FileFind.h
#pragma once
#ifndef __WINDOWS_FILEFIND_H
#define __WINDOWS_FILEFIND_H
#include "../Common/String.h"
#include "FileName.h"
#include "Defs.h"
namespace NWindows {
namespace NFile {
namespace NFind {
namespace NAttributes
{
inline bool IsReadOnly(DWORD attributes) { return (attributes & FILE_ATTRIBUTE_READONLY) != 0; }
inline bool IsHidden(DWORD attributes) { return (attributes & FILE_ATTRIBUTE_HIDDEN) != 0; }
inline bool IsSystem(DWORD attributes) { return (attributes & FILE_ATTRIBUTE_SYSTEM) != 0; }
inline bool IsDirectory(DWORD attributes) { return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0; }
inline bool IsArchived(DWORD attributes) { return (attributes & FILE_ATTRIBUTE_ARCHIVE) != 0; }
inline bool IsCompressed(DWORD attributes) { return (attributes & FILE_ATTRIBUTE_COMPRESSED) != 0; }
inline bool IsEncrypted(DWORD attributes) { return (attributes & FILE_ATTRIBUTE_ENCRYPTED) != 0; }
}
class CFileInfoBase
{
bool MatchesMask(UINT32 mask) const { return ((Attributes & mask) != 0); }
public:
DWORD Attributes;
FILETIME CreationTime;
FILETIME LastAccessTime;
FILETIME LastWriteTime;
UINT64 Size;
#ifndef _WIN32_WCE
UINT32 ReparseTag;
#else
DWORD ObjectID;
#endif
bool IsArchived() const { return MatchesMask(FILE_ATTRIBUTE_ARCHIVE); }
bool IsCompressed() const { return MatchesMask(FILE_ATTRIBUTE_COMPRESSED); }
bool IsDirectory() const { return MatchesMask(FILE_ATTRIBUTE_DIRECTORY); }
bool IsEncrypted() const { return MatchesMask(FILE_ATTRIBUTE_ENCRYPTED); }
bool IsHidden() const { return MatchesMask(FILE_ATTRIBUTE_HIDDEN); }
bool IsNormal() const { return MatchesMask(FILE_ATTRIBUTE_NORMAL); }
bool IsOffline() const { return MatchesMask(FILE_ATTRIBUTE_OFFLINE); }
bool IsReadOnly() const { return MatchesMask(FILE_ATTRIBUTE_READONLY); }
bool HasReparsePoint() const { return MatchesMask(FILE_ATTRIBUTE_REPARSE_POINT); }
bool IsSparse() const { return MatchesMask(FILE_ATTRIBUTE_SPARSE_FILE); }
bool IsSystem() const { return MatchesMask(FILE_ATTRIBUTE_SYSTEM); }
bool IsTemporary() const { return MatchesMask(FILE_ATTRIBUTE_TEMPORARY); }
};
class CFileInfo: public CFileInfoBase
{
public:
CSysString Name;
bool IsDots() const;
};
#ifdef _UNICODE
typedef CFileInfo CFileInfoW;
#else
class CFileInfoW: public CFileInfoBase
{
public:
UString Name;
bool IsDots() const;
};
#endif
class CFindFile
{
friend class CEnumerator;
HANDLE _handle;
bool _handleAllocated;
public:
bool IsHandleAllocated() const { return _handleAllocated; }
CFindFile(): _handleAllocated(false) {}
~CFindFile() { Close(); }
bool FindFirst(LPCTSTR wildcard, CFileInfo &fileInfo);
bool FindNext(CFileInfo &fileInfo);
#ifndef _UNICODE
bool FindFirst(LPCWSTR wildcard, CFileInfoW &fileInfo);
bool FindNext(CFileInfoW &fileInfo);
#endif
bool Close();
};
bool FindFile(LPCTSTR wildcard, CFileInfo &fileInfo);
bool DoesFileExist(LPCTSTR name);
#ifndef _UNICODE
bool FindFile(LPCWSTR wildcard, CFileInfoW &fileInfo);
bool DoesFileExist(LPCWSTR name);
#endif
class CEnumerator
{
CFindFile _findFile;
CSysString _wildcard;
bool NextAny(CFileInfo &fileInfo);
public:
CEnumerator(): _wildcard(NName::kAnyStringWildcard) {}
CEnumerator(const CSysString &wildcard): _wildcard(wildcard) {}
bool Next(CFileInfo &fileInfo);
};
#ifdef _UNICODE
typedef CEnumerator CEnumeratorW;
#else
class CEnumeratorW
{
CFindFile _findFile;
UString _wildcard;
bool NextAny(CFileInfoW &fileInfo);
public:
CEnumeratorW(): _wildcard(NName::kAnyStringWildcard) {}
CEnumeratorW(const UString &wildcard): _wildcard(wildcard) {}
bool Next(CFileInfoW &fileInfo);
};
#endif
class CFindChangeNotification
{
HANDLE _handle;
public:
operator HANDLE () { return _handle; }
CFindChangeNotification(): _handle(INVALID_HANDLE_VALUE) {}
~CFindChangeNotification() { Close(); }
bool Close();
HANDLE FindFirst(LPCTSTR pathName, bool watchSubtree, DWORD notifyFilter);
#ifndef _UNICODE
HANDLE FindFirst(LPCWSTR pathName, bool watchSubtree, DWORD notifyFilter);
#endif
bool FindNext()
{ return BOOLToBool(::FindNextChangeNotification(_handle)); }
};
#ifndef _WIN32_WCE
bool MyGetLogicalDriveStrings(CSysStringVector &driveStrings);
#endif
inline bool MyGetCompressedFileSize(LPCTSTR fileName, UINT64 &size)
{
DWORD highPart;
DWORD lowPart = ::GetCompressedFileSize(fileName, &highPart);
if (lowPart == INVALID_FILE_SIZE)
if (::GetLastError() != NO_ERROR)
return false;
size = (UINT64(highPart) << 32) | lowPart;
return true;
}
inline bool MyGetCompressedFileSizeW(LPCWSTR fileName, UINT64 &size)
{
DWORD highPart;
DWORD lowPart = ::GetCompressedFileSizeW(fileName, &highPart);
if (lowPart == INVALID_FILE_SIZE)
if (::GetLastError() != NO_ERROR)
return false;
size = (UINT64(highPart) << 32) | lowPart;
return true;
}
}}}
#endif

219
Windows/FileIO.cpp Executable file
View File

@@ -0,0 +1,219 @@
// Windows/FileIO.cpp
#include "StdAfx.h"
#include "FileIO.h"
#include "Defs.h"
#ifndef _UNICODE
#include "../Common/StringConvert.h"
#endif
namespace NWindows {
namespace NFile {
namespace NIO {
CFileBase::~CFileBase()
{
Close();
}
bool CFileBase::Create(LPCTSTR fileName, DWORD desiredAccess,
DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes)
{
Close();
_handle = ::CreateFile(fileName, desiredAccess, shareMode,
(LPSECURITY_ATTRIBUTES)NULL, creationDisposition,
flagsAndAttributes, (HANDLE) NULL);
_fileIsOpen = _handle != INVALID_HANDLE_VALUE;
return _fileIsOpen;
}
#ifndef _UNICODE
bool CFileBase::Create(LPCWSTR fileName, DWORD desiredAccess,
DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes)
{
Close();
// MessageBoxW(0, fileName, 0, 0);
// ::SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
_handle = ::CreateFileW(fileName, desiredAccess, shareMode,
(LPSECURITY_ATTRIBUTES)NULL, creationDisposition,
flagsAndAttributes, (HANDLE) NULL);
if ((_handle == INVALID_HANDLE_VALUE || _handle == 0) &&
::GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
return Create(UnicodeStringToMultiByte(fileName, ::AreFileApisANSI() ? CP_ACP : CP_OEMCP),
desiredAccess, shareMode, creationDisposition, flagsAndAttributes);
return (_fileIsOpen = _handle != INVALID_HANDLE_VALUE);
}
#endif
bool CFileBase::Close()
{
if(!_fileIsOpen)
return true;
bool result = BOOLToBool(::CloseHandle(_handle));
_fileIsOpen = !result;
return result;
}
bool CFileBase::GetPosition(UINT64 &position) const
{
return Seek(0, FILE_CURRENT, position);
}
bool CFileBase::GetLength(UINT64 &length) const
{
DWORD sizeHigh;
DWORD sizeLow = ::GetFileSize(_handle, &sizeHigh);
if(sizeLow == 0xFFFFFFFF)
if(::GetLastError() != NO_ERROR )
return false;
length = (((UINT64)sizeHigh) << 32) + sizeLow;
return true;
}
bool CFileBase::Seek(INT64 distanceToMove, DWORD moveMethod, UINT64 &newPosition) const
{
LARGE_INTEGER *pointer = (LARGE_INTEGER *)&distanceToMove;
pointer->LowPart = ::SetFilePointer(_handle, pointer->LowPart,
&pointer->HighPart, moveMethod);
if (pointer->LowPart == 0xFFFFFFFF)
if(::GetLastError() != NO_ERROR)
return false;
newPosition = *((UINT64 *)pointer);
return true;
}
bool CFileBase::Seek(UINT64 position, UINT64 &newPosition)
{
return Seek(position, FILE_BEGIN, newPosition);
}
bool CFileBase::SeekToBegin()
{
UINT64 newPosition;
return Seek(0, newPosition);
}
bool CFileBase::SeekToEnd(UINT64 &newPosition)
{
return Seek(0, FILE_END, newPosition);
}
bool CFileBase::GetFileInformation(CByHandleFileInfo &fileInfo) const
{
BY_HANDLE_FILE_INFORMATION winFileInfo;
if(!::GetFileInformationByHandle(_handle, &winFileInfo))
return false;
fileInfo.Attributes = winFileInfo.dwFileAttributes;
fileInfo.CreationTime = winFileInfo.ftCreationTime;
fileInfo.LastAccessTime = winFileInfo.ftLastAccessTime;
fileInfo.LastWriteTime = winFileInfo.ftLastWriteTime;
fileInfo.VolumeSerialNumber = winFileInfo.dwFileAttributes;
fileInfo.Size = (((UINT64)winFileInfo.nFileSizeHigh) << 32) +
winFileInfo.nFileSizeLow;
fileInfo.NumberOfLinks = winFileInfo.nNumberOfLinks;
fileInfo.FileIndex = (((UINT64)winFileInfo.nFileIndexHigh) << 32) +
winFileInfo.nFileIndexLow;
return true;
}
/////////////////////////
// CInFile
bool CInFile::Open(LPCTSTR fileName, DWORD shareMode,
DWORD creationDisposition, DWORD flagsAndAttributes)
{
return Create(fileName, GENERIC_READ, shareMode,
creationDisposition, flagsAndAttributes);
}
bool CInFile::Open(LPCTSTR fileName)
{
return Open(fileName, FILE_SHARE_READ, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
}
#ifndef _UNICODE
bool CInFile::Open(LPCWSTR fileName, DWORD shareMode,
DWORD creationDisposition, DWORD flagsAndAttributes)
{
return Create(fileName, GENERIC_READ, shareMode,
creationDisposition, flagsAndAttributes);
}
bool CInFile::Open(LPCWSTR fileName)
{
return Open(fileName, FILE_SHARE_READ, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
}
#endif
bool CInFile::Read(void *data, UINT32 size, UINT32 &processedSize)
{
return BOOLToBool(::ReadFile(_handle, data, size,
(DWORD *)&processedSize, NULL));
}
/////////////////////////
// COutFile
bool COutFile::Open(LPCTSTR fileName, DWORD shareMode,
DWORD creationDisposition, DWORD flagsAndAttributes)
{
return Create(fileName, GENERIC_WRITE, shareMode,
creationDisposition, flagsAndAttributes);
}
bool COutFile::Open(LPCTSTR fileName)
{
return Open(fileName, FILE_SHARE_READ, m_CreationDisposition, FILE_ATTRIBUTE_NORMAL);
}
#ifndef _UNICODE
bool COutFile::Open(LPCWSTR fileName, DWORD shareMode,
DWORD creationDisposition, DWORD flagsAndAttributes)
{
return Create(fileName, GENERIC_WRITE, shareMode,
creationDisposition, flagsAndAttributes);
}
bool COutFile::Open(LPCWSTR fileName)
{
return Open(fileName, FILE_SHARE_READ, m_CreationDisposition, FILE_ATTRIBUTE_NORMAL);
}
#endif
bool COutFile::SetTime(const FILETIME *creationTime,
const FILETIME *lastAccessTime, const FILETIME *lastWriteTime)
{
return BOOLToBool(::SetFileTime(_handle, creationTime,
lastAccessTime, lastWriteTime));
}
bool COutFile::SetLastWriteTime(const FILETIME *lastWriteTime)
{
return SetTime(NULL, NULL, lastWriteTime);
}
bool COutFile::Write(const void *data, UINT32 size, UINT32 &processedSize)
{
return BOOLToBool(::WriteFile(_handle, data, size,
(DWORD *)&processedSize, NULL));
}
bool COutFile::SetEndOfFile()
{
return BOOLToBool(::SetEndOfFile(_handle));
}
bool COutFile::SetLength(UINT64 length)
{
UINT64 newPosition;
if(!Seek(length, newPosition))
return false;
if(newPosition != length)
return false;
return SetEndOfFile();
}
}}}

98
Windows/FileIO.h Executable file
View File

@@ -0,0 +1,98 @@
// Windows/FileIO.h
#pragma once
#ifndef __WINDOWS_FILEIO_H
#define __WINDOWS_FILEIO_H
namespace NWindows {
namespace NFile {
namespace NIO {
struct CByHandleFileInfo
{
DWORD Attributes;
FILETIME CreationTime;
FILETIME LastAccessTime;
FILETIME LastWriteTime;
DWORD VolumeSerialNumber;
UINT64 Size;
DWORD NumberOfLinks;
UINT64 FileIndex;
};
class CFileBase
{
protected:
bool _fileIsOpen;
HANDLE _handle;
bool Create(LPCTSTR fileName, DWORD desiredAccess,
DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes);
#ifndef _UNICODE
bool Create(LPCWSTR fileName, DWORD desiredAccess,
DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes);
#endif
public:
CFileBase():
_fileIsOpen(false){};
virtual ~CFileBase();
virtual bool Close();
bool GetPosition(UINT64 &position) const;
bool GetLength(UINT64 &length) const;
bool Seek(INT64 distanceToMove, DWORD moveMethod, UINT64 &newPosition) const;
bool Seek(UINT64 position, UINT64 &newPosition);
bool SeekToBegin();
bool SeekToEnd(UINT64 &newPosition);
bool GetFileInformation(CByHandleFileInfo &fileInfo) const;
};
class CInFile: public CFileBase
{
public:
bool Open(LPCTSTR fileName, DWORD shareMode,
DWORD creationDisposition, DWORD flagsAndAttributes);
bool Open(LPCTSTR fileName);
#ifndef _UNICODE
bool Open(LPCWSTR fileName, DWORD shareMode,
DWORD creationDisposition, DWORD flagsAndAttributes);
bool Open(LPCWSTR fileName);
#endif
bool Read(void *data, UINT32 size, UINT32 &processedSize);
};
class COutFile: public CFileBase
{
DWORD m_CreationDisposition;
public:
COutFile(): m_CreationDisposition(CREATE_NEW){};
bool Open(LPCTSTR fileName, DWORD shareMode,
DWORD creationDisposition, DWORD flagsAndAttributes);
bool Open(LPCTSTR fileName);
#ifndef _UNICODE
bool Open(LPCWSTR fileName, DWORD shareMode,
DWORD creationDisposition, DWORD flagsAndAttributes);
bool Open(LPCWSTR fileName);
#endif
void SetOpenCreationDisposition(DWORD creationDisposition)
{ m_CreationDisposition = creationDisposition; }
void SetOpenCreationDispositionCreateAlways()
{ m_CreationDisposition = CREATE_ALWAYS; }
bool SetTime(const FILETIME *creationTime,
const FILETIME *lastAccessTime, const FILETIME *lastWriteTime);
bool SetLastWriteTime(const FILETIME *lastWriteTime);
bool Write(const void *data, UINT32 size, UINT32 &processedSize);
bool SetEndOfFile();
bool SetLength(UINT64 length);
};
}}}
#endif

14
Windows/FileMapping.cpp Executable file
View File

@@ -0,0 +1,14 @@
// Windows/FileIO.cpp
#include "StdAfx.h"
#include "Windows/FileMapping.h"
namespace NWindows {
namespace NFile {
namespace NMapping {
}}}

52
Windows/FileMapping.h Executable file
View File

@@ -0,0 +1,52 @@
// Windows/FileMapping.h
#pragma once
#ifndef __WINDOWS_FILEMAPPING_H
#define __WINDOWS_FILEMAPPING_H
#include "Windows/Handle.h"
#include "Windows/Defs.h"
namespace NWindows {
// namespace NFile {
// namespace NMapping {
class CFileMapping: public CHandle
{
public:
bool Create(HANDLE file, LPSECURITY_ATTRIBUTES attributes,
DWORD protect, UINT64 maximumSize, LPCTSTR name)
{
_handle = ::CreateFileMapping(file, attributes,
protect, DWORD(maximumSize >> 32), DWORD(maximumSize), name);
return (_handle != NULL);
}
bool Open(DWORD desiredAccess, bool inheritHandle, LPCTSTR name)
{
_handle = ::OpenFileMapping(desiredAccess, BoolToBOOL(inheritHandle), name);
return (_handle != NULL);
}
LPVOID MapViewOfFile(DWORD desiredAccess, UINT64 fileOffset,
SIZE_T numberOfBytesToMap)
{
return ::MapViewOfFile(_handle, desiredAccess,
DWORD(fileOffset >> 32), DWORD(fileOffset), numberOfBytesToMap);
}
LPVOID MapViewOfFileEx(DWORD desiredAccess, UINT64 fileOffset,
SIZE_T numberOfBytesToMap, LPVOID baseAddress)
{
return ::MapViewOfFileEx(_handle, desiredAccess,
DWORD(fileOffset >> 32), DWORD(fileOffset),
numberOfBytesToMap, baseAddress);
}
};
}
#endif

111
Windows/FileName.cpp Executable file
View File

@@ -0,0 +1,111 @@
// Windows/FileName.cpp
#include "StdAfx.h"
#include "Windows/FileName.h"
#include "Common/WildCard.h"
namespace NWindows {
namespace NFile {
namespace NName {
static const wchar_t kDiskDelimiter = L':';
/*
static bool IsCharAPrefixDelimiter(wchar_t c)
{ return (c == kDirDelimiter || c == kDiskDelimiter); }
*/
void NormalizeDirPathPrefix(CSysString &dirPath)
{
if (dirPath.IsEmpty())
return;
if (dirPath.ReverseFind(kDirDelimiter) != dirPath.Length() - 1)
dirPath += kDirDelimiter;
}
#ifndef _UNICODE
void NormalizeDirPathPrefix(UString &dirPath)
{
if (dirPath.IsEmpty())
return;
if (dirPath.ReverseFind(wchar_t(kDirDelimiter)) != dirPath.Length() - 1)
dirPath += wchar_t(kDirDelimiter);
}
#endif
namespace NPathType
{
EEnum GetPathType(const UString &path)
{
if (path.Length() <= 2)
return kLocal;
if (path[0] == kDirDelimiter && path[1] == kDirDelimiter)
return kUNC;
return kLocal;
}
}
void CParsedPath::ParsePath(const UString &path)
{
int curPos = 0;
switch (NPathType::GetPathType(path))
{
case NPathType::kLocal:
{
int posDiskDelimiter = path.Find(kDiskDelimiter);
if(posDiskDelimiter >= 0)
{
curPos = posDiskDelimiter + 1;
if (path.Length() > curPos)
if(path[curPos] == kDirDelimiter)
curPos++;
}
break;
}
case NPathType::kUNC:
{
int curPos = path.Find(kDirDelimiter, 2);
if(curPos < 0)
curPos = path.Length();
else
curPos++;
}
}
Prefix = path.Left(curPos);
SplitPathToParts(path.Mid(curPos), PathParts);
}
UString CParsedPath::MergePath() const
{
UString result = Prefix;
for(int i = 0; i < PathParts.Size(); i++)
{
if (i != 0)
result += kDirDelimiter;
result += PathParts[i];
}
return result;
}
const wchar_t kExtensionDelimiter = L'.';
void SplitNameToPureNameAndExtension(const UString &fullName,
UString &pureName, UString &extensionDelimiter, UString &extension)
{
int index = fullName.ReverseFind(kExtensionDelimiter);
if (index < 0)
{
pureName = fullName;
extensionDelimiter.Empty();
extension.Empty();
}
else
{
pureName = fullName.Left(index);
extensionDelimiter = kExtensionDelimiter;
extension = fullName.Mid(index + 1);
}
}
}}}

45
Windows/FileName.h Executable file
View File

@@ -0,0 +1,45 @@
// Windows/FileName.h
#pragma once
#ifndef __WINDOWS_FILENAME_H
#define __WINDOWS_FILENAME_H
#include "../Common/String.h"
namespace NWindows {
namespace NFile {
namespace NName {
const TCHAR kDirDelimiter = '\\';
const TCHAR kAnyStringWildcard = '*';
void NormalizeDirPathPrefix(CSysString &dirPath); // ensures that it ended with '\\'
#ifndef _UNICODE
void NormalizeDirPathPrefix(UString &dirPath); // ensures that it ended with '\\'
#endif
namespace NPathType
{
enum EEnum
{
kLocal,
kUNC
};
EEnum GetPathType(const UString &path);
}
struct CParsedPath
{
UString Prefix; // Disk or UNC with slash
UStringVector PathParts;
void ParsePath(const UString &path);
UString MergePath() const;
};
void SplitNameToPureNameAndExtension(const UString &fullName,
UString &pureName, UString &extensionDelimiter, UString &extension);
}}}
#endif

77
Windows/FileSystem.cpp Executable file
View File

@@ -0,0 +1,77 @@
// Windows/FileSystem.cpp
#include "StdAfx.h"
#include "FileSystem.h"
#include "Defs.h"
namespace NWindows {
namespace NFile {
namespace NSystem {
bool MyGetVolumeInformation(
LPCTSTR rootPathName,
CSysString &volumeName,
LPDWORD volumeSerialNumber,
LPDWORD maximumComponentLength,
LPDWORD fileSystemFlags,
CSysString &fileSystemName)
{
bool result = BOOLToBool(GetVolumeInformation(
rootPathName,
volumeName.GetBuffer(MAX_PATH), MAX_PATH,
volumeSerialNumber,
maximumComponentLength,
fileSystemFlags,
fileSystemName.GetBuffer(MAX_PATH), MAX_PATH));
volumeName.ReleaseBuffer();
fileSystemName.ReleaseBuffer();
return result;
}
typedef BOOL (WINAPI * GetDiskFreeSpaceExPointer)(
LPCTSTR lpDirectoryName, // directory name
PULARGE_INTEGER lpFreeBytesAvailable, // bytes available to caller
PULARGE_INTEGER lpTotalNumberOfBytes, // bytes on disk
PULARGE_INTEGER lpTotalNumberOfFreeBytes // free bytes on disk
);
bool MyGetDiskFreeSpace(LPCTSTR rootPathName,
UINT64 &clusterSize, UINT64 &totalSize, UINT64 &freeSize)
{
GetDiskFreeSpaceExPointer pGetDiskFreeSpaceEx =
(GetDiskFreeSpaceExPointer)GetProcAddress(
GetModuleHandle(TEXT("kernel32.dll")), "GetDiskFreeSpaceExA");
bool sizeIsDetected = false;
if (pGetDiskFreeSpaceEx)
{
UINT64 i64FreeBytesToCaller;
sizeIsDetected = BOOLToBool(pGetDiskFreeSpaceEx(rootPathName,
(PULARGE_INTEGER)&i64FreeBytesToCaller,
(PULARGE_INTEGER)&totalSize,
(PULARGE_INTEGER)&freeSize));
}
DWORD numSectorsPerCluster;
DWORD bytesPerSector;
DWORD numberOfFreeClusters;
DWORD totalNumberOfClusters;
if (!::GetDiskFreeSpace(rootPathName,
&numSectorsPerCluster,
&bytesPerSector,
&numberOfFreeClusters,
&totalNumberOfClusters))
return false;
clusterSize = UINT64(bytesPerSector) * UINT64(numSectorsPerCluster);
if (!sizeIsDetected)
{
totalSize = clusterSize * UINT64(totalNumberOfClusters);
freeSize = clusterSize * UINT64(numberOfFreeClusters);
}
return true;
}
}}}

28
Windows/FileSystem.h Executable file
View File

@@ -0,0 +1,28 @@
// Windows/FileSystem.h
#pragma once
#ifndef __WINDOWS_FILESYSTEM_H
#define __WINDOWS_FILESYSTEM_H
#include "../Common/String.h"
namespace NWindows {
namespace NFile {
namespace NSystem {
bool MyGetVolumeInformation(
LPCTSTR rootPathName,
CSysString &volumeName,
LPDWORD volumeSerialNumber,
LPDWORD maximumComponentLength,
LPDWORD fileSystemFlags,
CSysString &fileSystemName);
bool MyGetDiskFreeSpace(LPCTSTR rootPathName,
UINT64 &clusterSize, UINT64 &totalSize, UINT64 &freeSize);
}}}
#endif

39
Windows/Handle.h Executable file
View File

@@ -0,0 +1,39 @@
// Windows/Handle.h
#pragma once
#ifndef __WINDOWS_HANDLE_H
#define __WINDOWS_HANDLE_H
namespace NWindows {
class CHandle
{
protected:
HANDLE _handle;
public:
operator HANDLE() { return _handle; }
CHandle(): _handle(NULL) {}
~CHandle() { Close(); }
bool Close()
{
if (_handle == NULL)
return true;
if (!::CloseHandle(_handle))
return false;
_handle = NULL;
return true;
}
void Attach(HANDLE handle)
{ _handle = handle; }
HANDLE Detach()
{
HANDLE handle = _handle;
_handle = NULL;
return handle;
}
};
}
#endif

166
Windows/ItemIDListUtils.cpp Executable file
View File

@@ -0,0 +1,166 @@
// ItemIDListUtils.h
#include "StdAfx.h"
#include "ItemIDListUtils.h"
namespace NItemIDList {
CHolder::CHolder(const CHolder& anItemIDList):
m_Object(NULL)
{
*this = anItemIDList;
}
bool CHolder::Create(UINT16 aPureSize)
{
Free();
m_Object = LPITEMIDLIST(CoTaskMemAlloc(2 + aPureSize + 2));
if(m_Object == NULL)
return false;
m_Object->mkid.cb = 2 + aPureSize;
LPITEMIDLIST aNewIDListEnd = LPITEMIDLIST(((BYTE *)m_Object) + 2 + aPureSize);
aNewIDListEnd->mkid.cb = 0;
return (m_Object != NULL);
}
void CHolder::Free()
{
if(m_Object == NULL)
return;
CoTaskMemFree(m_Object);
m_Object = NULL;
}
CHolder& CHolder::operator=(LPCITEMIDLIST anObject)
{
if(m_Object != NULL)
Free();
UINT32 aSize = GetSize(anObject);
m_Object = (LPITEMIDLIST)CoTaskMemAlloc(aSize);
if(m_Object != NULL)
MoveMemory(m_Object, anObject, aSize);
return *this;
}
CHolder& CHolder::operator=(const CHolder &anObject)
{
if(m_Object != NULL)
Free();
if(anObject.m_Object != NULL)
{
UINT32 aSize = GetSize(anObject.m_Object);
m_Object = (LPITEMIDLIST)CoTaskMemAlloc(aSize);
if(m_Object != NULL)
MoveMemory(m_Object, anObject.m_Object, aSize);
}
return *this;
}
////////////////////////
// static
LPITEMIDLIST GetNextItem(LPCITEMIDLIST anIDList)
{
if (anIDList)
return (LPITEMIDLIST)(LPBYTE) ( ((LPBYTE)anIDList) + anIDList->mkid.cb);
return (NULL);
}
UINT32 GetSize(LPCITEMIDLIST anIDList)
{
UINT32 aSizeTotal = 0;
if(anIDList != NULL)
{
while(anIDList->mkid.cb != 0)
{
aSizeTotal += anIDList->mkid.cb;
anIDList = GetNextItem(anIDList);
}
aSizeTotal += sizeof(ITEMIDLIST) - 1;
}
return (aSizeTotal);
}
LPITEMIDLIST GetLastItem(LPCITEMIDLIST anIDList)
{
LPITEMIDLIST anIDListLast = NULL;
if(anIDList)
while(anIDList->mkid.cb != 0)
{
anIDListLast = (LPITEMIDLIST)anIDList;
anIDList = GetNextItem(anIDList);
}
return anIDListLast;
}
}
////////////////////////////////////////////////////////////////
// CItemIDListManager : Class to manage pidls
CItemIDListManager::CItemIDListManager():
m_pMalloc(NULL)
{
SHGetMalloc(&m_pMalloc);
}
CItemIDListManager::~CItemIDListManager()
{
if (m_pMalloc)
m_pMalloc->Release();
}
LPITEMIDLIST CItemIDListManager::Create(UINT16 aPureSize)
{
LPITEMIDLIST aPointer = LPITEMIDLIST(m_pMalloc->Alloc(2 + aPureSize + 2));
if(aPointer == NULL)
return NULL;
aPointer->mkid.cb = 2 + aPureSize;
LPITEMIDLIST aNewIDListEnd = LPITEMIDLIST(((BYTE *)aPointer) + 2 + aPureSize);
aNewIDListEnd->mkid.cb = 0;
return aPointer;
}
void CItemIDListManager::Delete(LPITEMIDLIST anIDList)
{
m_pMalloc->Free(anIDList);
}
LPITEMIDLIST CItemIDListManager::Copy(LPCITEMIDLIST anIDListSrc)
{
if (NULL == anIDListSrc)
return (NULL);
LPITEMIDLIST anIDListTarget = NULL;
UINT32 aSize = NItemIDList::GetSize(anIDListSrc);
anIDListTarget = (LPITEMIDLIST)m_pMalloc->Alloc(aSize);
if (!anIDListTarget)
return (NULL);
MoveMemory(anIDListTarget, anIDListSrc, aSize);
return anIDListTarget;
}
LPITEMIDLIST CItemIDListManager::Concatenate(LPCITEMIDLIST anIDList1,
LPCITEMIDLIST anIDList2)
{
if(!anIDList1 && !anIDList2)
return NULL;
if(!anIDList1)
return Copy(anIDList2);
if(!anIDList2)
return Copy(anIDList1);
UINT32 cb1 = NItemIDList::GetSize(anIDList1) - 2;
UINT32 cb2 = NItemIDList::GetSize(anIDList2);
LPITEMIDLIST anIDListNew = (LPITEMIDLIST)m_pMalloc->Alloc(cb1 + cb2);
if(anIDListNew)
{
MoveMemory(anIDListNew, anIDList1, cb1);
MoveMemory(((LPBYTE)anIDListNew) + cb1, anIDList2, cb2);
}
return anIDListNew;
}

98
Windows/ItemIDListUtils.h Executable file
View File

@@ -0,0 +1,98 @@
// ItemIDListUtils.h
#pragma once
#ifndef __ITEMIDLISTUTILS_H
#define __ITEMIDLISTUTILS_H
#include "Common/Types.h"
/////////////////////////////
// It is not for shell using
// It's for internal using only
// since it uses CoTaskMemFree instead SHGetMalloc
namespace NItemIDList {
LPITEMIDLIST GetNextItem(LPCITEMIDLIST anIDList);
UINT32 GetSize(LPCITEMIDLIST anIDList);
LPITEMIDLIST GetLastItem(LPCITEMIDLIST anIDList);
class CHolder
{
LPITEMIDLIST m_Object;
public:
CHolder(): m_Object(NULL) {}
CHolder(const CHolder& anItemIDList);
~CHolder() { Free(); }
void Attach(LPITEMIDLIST anObject)
{
if (m_Object != NULL)
Free();
m_Object = anObject;
}
LPITEMIDLIST Detach()
{
LPITEMIDLIST anObject = m_Object;
m_Object = NULL;
return anObject;
}
void Free();
bool Create(UINT16 aPureSize);
operator LPITEMIDLIST() { return m_Object;}
operator LPCITEMIDLIST() const { return m_Object;}
LPITEMIDLIST* operator&() { return &m_Object; }
LPITEMIDLIST operator->() { return m_Object; }
CHolder& operator=(LPCITEMIDLIST anObject);
CHolder& operator=(const CHolder &anObject);
};
}
class CItemIDListManager
{
public:
CItemIDListManager();
~CItemIDListManager();
public:
LPITEMIDLIST Create(UINT16 aPureSize);
void Delete(LPITEMIDLIST anIDList);
LPITEMIDLIST Copy(LPCITEMIDLIST anIDListSrc);
// CZipIDData* GetDataPointer(LPCITEMIDLIST anIDList);
LPITEMIDLIST Concatenate(LPCITEMIDLIST anIDList1, LPCITEMIDLIST anIDList2);
private:
LPMALLOC m_pMalloc;
};
class CShellItemIDList
{
CItemIDListManager *m_Manager;
LPITEMIDLIST m_Object;
public:
CShellItemIDList(CItemIDListManager *aManager):
m_Manager(aManager),
m_Object(NULL) {}
bool Create(UINT16 aPureSize)
{
Free();
m_Object = m_Manager->Create(aPureSize);
return (m_Object != NULL);
}
~CShellItemIDList() { Free(); }
void Free()
{
if(m_Object != NULL)
m_Manager->Delete(m_Object);
m_Object = NULL;
}
void Attach(LPITEMIDLIST anObject)
{
Free();
m_Object = anObject;
}
operator LPITEMIDLIST() { return m_Object;}
LPITEMIDLIST* operator&() { return &m_Object; }
};
#endif

59
Windows/Memory.cpp Executable file
View File

@@ -0,0 +1,59 @@
// Windows/Memory.cpp
#include "StdAfx.h"
#include "Windows/Memory.h"
namespace NWindows {
namespace NMemory {
CGlobal::~CGlobal()
{
Free();
}
// aFlags = GMEM_MOVEABLE
bool CGlobal::Alloc(UINT aFlags, DWORD aSize)
{
HGLOBAL aNewBlock = ::GlobalAlloc(aFlags, aSize);
if (aNewBlock == NULL)
return false;
m_MemoryHandle = aNewBlock;
return true;
}
bool CGlobal::Free()
{
if (m_MemoryHandle == NULL)
return true;
m_MemoryHandle = ::GlobalFree(m_MemoryHandle);
return (m_MemoryHandle == NULL);
}
HGLOBAL CGlobal::Detach()
{
HGLOBAL aHandle = m_MemoryHandle;
m_MemoryHandle = NULL;
return aHandle;
}
LPVOID CGlobal::Lock() const
{
return ::GlobalLock(m_MemoryHandle);
}
void CGlobal::Unlock() const
{
::GlobalUnlock(m_MemoryHandle);
}
bool CGlobal::ReAlloc(DWORD aSize)
{
HGLOBAL aNewBlock = ::GlobalReAlloc(m_MemoryHandle, aSize, GMEM_MOVEABLE);
if (aNewBlock == NULL)
return false;
m_MemoryHandle = aNewBlock;
return true;
}
}}

46
Windows/Memory.h Executable file
View File

@@ -0,0 +1,46 @@
// Windows/Memory.h
#pragma once
#ifndef __WINDOWS_MEMORY_H
#define __WINDOWS_MEMORY_H
namespace NWindows {
namespace NMemory {
class CGlobal
{
HGLOBAL m_MemoryHandle;
public:
CGlobal():m_MemoryHandle(NULL){};
~CGlobal();
operator HGLOBAL() const { return m_MemoryHandle; };
HGLOBAL Detach();
bool Alloc(UINT aFlags, DWORD aSize);
bool Free();
LPVOID Lock() const;
void Unlock() const;
bool ReAlloc(DWORD aSize);
};
class CGlobalLock
{
const HGLOBAL m_Global;
LPVOID m_Pointer;
public:
LPVOID GetPointer() const { return m_Pointer; }
CGlobalLock(HGLOBAL aGlobal): m_Global(aGlobal)
{
m_Pointer = ::GlobalLock(m_Global);
};
~CGlobalLock()
{
if(m_Pointer != NULL)
::GlobalUnlock(m_Global);
}
};
}}
#endif

108
Windows/Menu.h Executable file
View File

@@ -0,0 +1,108 @@
// Windows/Menu.h
#pragma once
#ifndef __WINDOWS_MENU_H
#define __WINDOWS_MENU_H
#include "Common/String.h"
#include "Windows/Defs.h"
namespace NWindows {
class CMenu
{
HMENU _menu;
public:
CMenu(): _menu(NULL) {};
operator HMENU() const { return _menu; }
void Attach(HMENU menu) { _menu = menu; }
HMENU Detach()
{
HMENU menu = _menu;
_menu = NULL;
return menu;
}
bool Create()
{
_menu = ::CreateMenu();
return (_menu != NULL);
}
bool CreatePopup()
{
_menu = ::CreatePopupMenu();
return (_menu != NULL);
}
bool Destroy()
{
if (_menu == NULL)
return false;
return BOOLToBool(::DestroyMenu(Detach()));
}
int GetItemCount()
{ return GetMenuItemCount(_menu); }
HMENU GetSubMenu(int pos)
{ return ::GetSubMenu(_menu, pos); }
bool GetItemString(UINT idItem, UINT flag, CSysString &result)
{
result.Empty();
int len = ::GetMenuString(_menu, idItem, 0, 0, flag);
len = ::GetMenuString(_menu, idItem, result.GetBuffer(len + 2),
len + 1, flag);
result.ReleaseBuffer();
return (len != 0);
}
UINT GetItemID(int pos)
{ return ::GetMenuItemID(_menu, pos); }
UINT GetItemState(UINT id, UINT flags)
{ return ::GetMenuState(_menu, id, flags); }
bool AppendItem(UINT flags, UINT_PTR newItemID, LPCTSTR newItem)
{ return BOOLToBool(::AppendMenu(_menu, flags, newItemID, newItem)); }
bool Insert(UINT position, UINT flags, UINT_PTR idNewItem, LPCTSTR newItem)
{ return BOOLToBool(::InsertMenu(_menu, position, flags, idNewItem, newItem)); }
bool InsertItem(UINT itemIndex, bool byPosition, LPCMENUITEMINFO itemInfo)
{ return BOOLToBool(::InsertMenuItem(_menu, itemIndex,
BoolToBOOL(byPosition), itemInfo)); }
bool RemoveItem(UINT item, UINT flags)
{ return BOOLToBool(::RemoveMenu(_menu, item, flags)); }
bool GetItemInfo(UINT itemIndex, bool byPosition, LPMENUITEMINFO itemInfo)
{ return BOOLToBool(::GetMenuItemInfo(_menu, itemIndex,
BoolToBOOL(byPosition), itemInfo)); }
bool SetItemInfo(UINT itemIndex, bool byPosition, LPMENUITEMINFO itemInfo)
{ return BOOLToBool(::SetMenuItemInfo(_menu, itemIndex,
BoolToBOOL(byPosition), itemInfo)); }
int Track(UINT flags, int x, int y, HWND hWnd)
{ return ::TrackPopupMenuEx(_menu, flags, x, y, hWnd, NULL); }
bool CheckRadioItem(UINT idFirst, UINT idLast, UINT idCheck, UINT flags)
{ return BOOLToBool(::CheckMenuRadioItem(_menu, idFirst, idLast, idCheck, flags)); }
DWORD CheckItem(UINT id, UINT uCheck)
{ return ::CheckMenuItem(_menu, id, uCheck); }
};
class CMenuDestroyer
{
CMenu *_menu;
public:
CMenuDestroyer(CMenu &menu): _menu(&menu) {}
CMenuDestroyer(): _menu(0) {}
~CMenuDestroyer() { if (_menu) _menu->Destroy(); }
void Attach(CMenu &menu) { _menu = &menu; }
void Disable() { _menu = 0; }
};
}
#endif

37
Windows/NationalTime.cpp Executable file
View File

@@ -0,0 +1,37 @@
// Windows/NationalTime.cpp
#include "StdAfx.h"
#include "Windows/NationalTime.h"
namespace NWindows {
namespace NNational {
namespace NTime {
bool MyGetTimeFormat(LCID locale, DWORD flags, CONST SYSTEMTIME *time,
LPCTSTR format, CSysString &resultString)
{
resultString.Empty();
int numChars = ::GetTimeFormat(locale, flags, time, format, NULL, 0);
if(numChars == 0)
return false;
numChars = ::GetTimeFormat(locale, flags, time, format,
resultString.GetBuffer(numChars), numChars + 1);
resultString.ReleaseBuffer();
return (numChars != 0);
}
bool MyGetDateFormat(LCID locale, DWORD flags, CONST SYSTEMTIME *time,
LPCTSTR format, CSysString &resultString)
{
resultString.Empty();
int numChars = ::GetDateFormat(locale, flags, time, format, NULL, 0);
if(numChars == 0)
return false;
numChars = ::GetDateFormat(locale, flags, time, format,
resultString.GetBuffer(numChars), numChars + 1);
resultString.ReleaseBuffer();
return (numChars != 0);
}
}}}

22
Windows/NationalTime.h Executable file
View File

@@ -0,0 +1,22 @@
// Windows/NationalTime.h
#pragma once
#ifndef __WINDOWS_NATIONALTIME_H
#define __WINDOWS_NATIONALTIME_H
#include "Common/String.h"
namespace NWindows {
namespace NNational {
namespace NTime {
bool MyGetTimeFormat(LCID locale, DWORD flags, CONST SYSTEMTIME *time,
LPCTSTR format, CSysString &resultString);
bool MyGetDateFormat(LCID locale, DWORD flags, CONST SYSTEMTIME *time,
LPCTSTR format, CSysString &resultString);
}}}
#endif

158
Windows/Net.cpp Executable file
View File

@@ -0,0 +1,158 @@
// Windows/Net.cpp
#include "StdAfx.h"
#include "Windows/Net.h"
namespace NWindows {
namespace NNet {
DWORD CEnum::Open(DWORD scope, DWORD type, DWORD usage, LPNETRESOURCE netResource)
{
Close();
DWORD result = ::WNetOpenEnum(scope, type, usage, netResource, &_handle);
_handleAllocated = (result == NO_ERROR);
return result;
}
static void SetComplexString(bool &defined, CSysString &destString,
LPCTSTR srsString)
{
defined = (srsString != 0);
if (defined)
destString = srsString;
else
destString.Empty();
}
static void ConvertNETRESOURCEToCResource(const NETRESOURCE &netResource,
CResource &resource)
{
resource.Scope = netResource.dwScope;
resource.Type = netResource.dwType;
resource.DisplayType = netResource.dwDisplayType;
resource.Usage = netResource.dwUsage;
SetComplexString(resource.LocalNameIsDefined, resource.LocalName, netResource.lpLocalName);
SetComplexString(resource.RemoteNameIsDefined, resource.RemoteName, netResource.lpRemoteName);
SetComplexString(resource.CommentIsDefined, resource.Comment, netResource.lpComment);
SetComplexString(resource.ProviderIsDefined, resource.Provider, netResource.lpProvider);
}
static void SetComplexString2(LPCTSTR &destString, bool defined,
const CSysString &srsString)
{
if (defined)
destString = srsString;
else
destString = 0;
}
static void ConvertCResourceToNETRESOURCE(const CResource &resource,
NETRESOURCE &netResource)
{
netResource.dwScope = resource.Scope;
netResource.dwType = resource.Type;
netResource.dwDisplayType = resource.DisplayType;
netResource.dwUsage = resource.Usage;
SetComplexString2(netResource.lpLocalName, resource.LocalNameIsDefined, resource.LocalName);
SetComplexString2(netResource.lpRemoteName, resource.RemoteNameIsDefined, resource.RemoteName);
SetComplexString2(netResource.lpComment, resource.CommentIsDefined, resource.Comment);
SetComplexString2(netResource.lpProvider, resource.ProviderIsDefined, resource.Provider);
}
DWORD CEnum::Open(DWORD scope, DWORD type, DWORD usage,
const CResource *resource)
{
NETRESOURCE netResource;
LPNETRESOURCE pointer;
if (resource == 0)
pointer = 0;
else
{
ConvertCResourceToNETRESOURCE(*resource, netResource);
pointer = &netResource;
}
return Open(scope, type, usage, pointer);
}
DWORD CEnum::Close()
{
if(!_handleAllocated)
return NO_ERROR;
DWORD result = ::WNetCloseEnum(_handle);
_handleAllocated = (result != NO_ERROR);
return result;
}
DWORD CEnum::Next(LPDWORD lpcCount, LPVOID lpBuffer, LPDWORD lpBufferSize)
{
return ::WNetEnumResource(_handle, lpcCount, lpBuffer, lpBufferSize);
}
DWORD CEnum::Next(CResource &resource)
{
CByteBuffer byteBuffer;
const DWORD kBufferSize = 16384;
byteBuffer.SetCapacity(kBufferSize);
LPNETRESOURCE lpnrLocal = (LPNETRESOURCE) (BYTE *)(byteBuffer);
ZeroMemory(lpnrLocal, kBufferSize);
DWORD bufferSize = kBufferSize;
DWORD numEntries = 1;
DWORD result = Next(&numEntries, lpnrLocal, &bufferSize);
if (result != NO_ERROR)
return result;
if (numEntries != 1)
return (DWORD)E_FAIL;
ConvertNETRESOURCEToCResource(lpnrLocal[0], resource);
return result;
}
DWORD GetResourceParent(const CResource &resource, CResource &parentResource)
{
CByteBuffer byteBuffer;
const DWORD kBufferSize = 16384;
byteBuffer.SetCapacity(kBufferSize);
LPNETRESOURCE lpnrLocal = (LPNETRESOURCE) (BYTE *)(byteBuffer);
ZeroMemory(lpnrLocal, kBufferSize);
DWORD bufferSize = kBufferSize;
NETRESOURCE netResource;
ConvertCResourceToNETRESOURCE(resource, netResource);
DWORD result = ::WNetGetResourceParent(&netResource, lpnrLocal, &bufferSize);
if (result != NO_ERROR)
return result;
ConvertNETRESOURCEToCResource(lpnrLocal[0], parentResource);
return result;
}
DWORD GetResourceInformation(const CResource &resource,
CResource &destResource, CSysString &systemPathPart)
{
CByteBuffer byteBuffer;
const DWORD kBufferSize = 16384;
byteBuffer.SetCapacity(kBufferSize);
LPNETRESOURCE lpnrLocal = (LPNETRESOURCE) (BYTE *)(byteBuffer);
ZeroMemory(lpnrLocal, kBufferSize);
DWORD bufferSize = kBufferSize;
NETRESOURCE netResource;
ConvertCResourceToNETRESOURCE(resource, netResource);
LPTSTR lplpSystem;
DWORD result = ::WNetGetResourceInformation(&netResource,
lpnrLocal, &bufferSize, &lplpSystem);
if (result != NO_ERROR)
return result;
if (lplpSystem != 0)
systemPathPart = lplpSystem;
ConvertNETRESOURCEToCResource(lpnrLocal[0], destResource);
return result;
}
DWORD AddConnection2(const CResource &resource,
LPCTSTR password, LPCTSTR userName, DWORD flags)
{
NETRESOURCE netResource;
ConvertCResourceToNETRESOURCE(resource, netResource);
return ::WNetAddConnection2(&netResource,
password, userName, flags);
}
}}

54
Windows/Net.h Executable file
View File

@@ -0,0 +1,54 @@
// Windows/Net.h
#pragma once
#ifndef __WINDOWS_NET_H
#define __WINDOWS_NET_H
#include "Common/Buffer.h"
#include "Common/String.h"
namespace NWindows {
namespace NNet {
struct CResource
{
DWORD Scope;
DWORD Type;
DWORD DisplayType;
DWORD Usage;
bool LocalNameIsDefined;
bool RemoteNameIsDefined;
bool CommentIsDefined;
bool ProviderIsDefined;
CSysString LocalName;
CSysString RemoteName;
CSysString Comment;
CSysString Provider;
};
class CEnum
{
HANDLE _handle;
bool _handleAllocated;
protected:
bool IsHandleAllocated() const { return _handleAllocated; }
public:
CEnum(): _handleAllocated(false) {}
~CEnum() { Close(); }
DWORD Open(DWORD scope, DWORD type, DWORD usage, LPNETRESOURCE netResource);
DWORD Open(DWORD scope, DWORD type, DWORD usage, const CResource *resource);
DWORD Close();
DWORD Next(LPDWORD lpcCount, LPVOID lpBuffer, LPDWORD lpBufferSize);
DWORD Next(CResource &resource);
};
DWORD GetResourceParent(const CResource &resource, CResource &parentResource);
DWORD GetResourceInformation(const CResource &resource,
CResource &destResource, CSysString &systemPathPart);
DWORD AddConnection2(const CResource &resource,
LPCTSTR password, LPCTSTR userName, DWORD flags);
}}
#endif

22
Windows/ProcessMessages.cpp Executable file
View File

@@ -0,0 +1,22 @@
// Windows/ProcessMessages.cpp
#include "StdAfx.h"
#include "ProcessMessages.h"
namespace NWindows {
void ProcessMessages(HWND window)
{
MSG msg;
while (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) )
{
if (window == (HWND) NULL || !IsDialogMessage(window, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
}

16
Windows/ProcessMessages.h Executable file
View File

@@ -0,0 +1,16 @@
// Windows/ProcessMessages.h
#pragma once
#ifndef __WINDOWS_PROCESSMESSAGES_H
#define __WINDOWS_PROCESSMESSAGES_H
namespace NWindows {
void ProcessMessages(HWND window);
}
#endif

479
Windows/PropVariant.cpp Executable file
View File

@@ -0,0 +1,479 @@
// Windows/PropVariant.cpp
#include "StdAfx.h"
#include "PropVariant.h"
#include "../Common/Defs.h"
namespace NWindows {
namespace NCOM {
CPropVariant::CPropVariant(const PROPVARIANT& varSrc)
{
vt = VT_EMPTY;
InternalCopy(&varSrc);
}
CPropVariant::CPropVariant(const CPropVariant& varSrc)
{
vt = VT_EMPTY;
InternalCopy(&varSrc);
}
CPropVariant::CPropVariant(BSTR bstrSrc)
{
vt = VT_EMPTY;
*this = bstrSrc;
}
CPropVariant::CPropVariant(LPCOLESTR lpszSrc)
{
vt = VT_EMPTY;
*this = lpszSrc;
}
///////////////////////////
// Assignment Operators
CPropVariant& CPropVariant::operator=(const CPropVariant& varSrc)
{
InternalCopy(&varSrc);
return *this;
}
CPropVariant& CPropVariant::operator=(const PROPVARIANT& varSrc)
{
InternalCopy(&varSrc);
return *this;
}
CPropVariant& CPropVariant::operator=(BSTR bstrSrc)
{
InternalClear();
vt = VT_BSTR;
bstrVal = ::SysAllocString(bstrSrc);
if (bstrVal == NULL && bstrSrc != NULL)
{
vt = VT_ERROR;
scode = E_OUTOFMEMORY;
}
return *this;
}
CPropVariant& CPropVariant::operator=(LPCOLESTR lpszSrc)
{
InternalClear();
vt = VT_BSTR;
bstrVal = ::SysAllocString(lpszSrc);
if (bstrVal == NULL && lpszSrc != NULL)
{
vt = VT_ERROR;
scode = E_OUTOFMEMORY;
}
return *this;
}
CPropVariant& CPropVariant::operator=(bool bSrc)
{
if (vt != VT_BOOL)
{
InternalClear();
vt = VT_BOOL;
}
boolVal = bSrc ? VARIANT_TRUE : VARIANT_FALSE;
return *this;
}
CPropVariant& CPropVariant::operator=(UINT32 value)
{
if (vt != VT_UI4)
{
InternalClear();
vt = VT_UI4;
}
ulVal = value;
return *this;
}
CPropVariant& CPropVariant::operator=(UINT64 value)
{
if (vt != VT_UI8)
{
InternalClear();
vt = VT_UI8;
}
uhVal = *(ULARGE_INTEGER*)&value;
return *this;
}
CPropVariant& CPropVariant::operator=(const FILETIME &value)
{
if (vt != VT_FILETIME)
{
InternalClear();
vt = VT_FILETIME;
}
filetime = value;
return *this;
}
CPropVariant& CPropVariant::operator=(int value)
{
if (vt != VT_I4)
{
InternalClear();
vt = VT_I4;
}
lVal = value;
return *this;
}
CPropVariant& CPropVariant::operator=(BYTE value)
{
if (vt != VT_UI1)
{
InternalClear();
vt = VT_UI1;
}
bVal = value;
return *this;
}
CPropVariant& CPropVariant::operator=(short value)
{
if (vt != VT_I2)
{
InternalClear();
vt = VT_I2;
}
iVal = value;
return *this;
}
CPropVariant& CPropVariant::operator=(long value)
{
if (vt != VT_I4)
{
InternalClear();
vt = VT_I4;
}
lVal = value;
return *this;
}
static HRESULT MyPropVariantClear(PROPVARIANT *aPropVariant)
{
switch(aPropVariant->vt)
{
case VT_UI1:
case VT_I1:
case VT_I2:
case VT_UI2:
case VT_BOOL:
case VT_I4:
case VT_UI4:
case VT_R4:
case VT_INT:
case VT_UINT:
case VT_ERROR:
case VT_FILETIME:
case VT_UI8:
case VT_R8:
case VT_CY:
case VT_DATE:
aPropVariant->vt = VT_EMPTY;
return S_OK;
}
return ::VariantClear((tagVARIANT *)aPropVariant);
}
HRESULT CPropVariant::Clear()
{
return MyPropVariantClear(this);
}
HRESULT CPropVariant::Copy(const PROPVARIANT* pSrc)
{
::VariantClear((tagVARIANT *)this);
switch(pSrc->vt)
{
case VT_UI1:
case VT_I1:
case VT_I2:
case VT_UI2:
case VT_BOOL:
case VT_I4:
case VT_UI4:
case VT_R4:
case VT_INT:
case VT_UINT:
case VT_ERROR:
case VT_FILETIME:
case VT_UI8:
case VT_R8:
case VT_CY:
case VT_DATE:
MoveMemory((PROPVARIANT*)this, pSrc, sizeof(PROPVARIANT));
return S_OK;
}
return ::VariantCopy((tagVARIANT *)this, (tagVARIANT *)(pSrc));
}
HRESULT CPropVariant::Attach(PROPVARIANT* pSrc)
{
// Clear out the variant
HRESULT hr = Clear();
if (!FAILED(hr))
{
// Copy the contents and give control to CPropVariant
memcpy(this, pSrc, sizeof(PROPVARIANT));
pSrc->vt = VT_EMPTY;
hr = S_OK;
}
return hr;
}
HRESULT CPropVariant::Detach(PROPVARIANT* pDest)
{
// Clear out the variant
HRESULT hr = MyPropVariantClear(pDest);
// HRESULT hr = ::VariantClear((VARIANT* )pDest);
if (!FAILED(hr))
{
// Copy the contents and remove control from CPropVariant
memcpy(pDest, this, sizeof(PROPVARIANT));
vt = VT_EMPTY;
hr = S_OK;
}
return hr;
}
HRESULT CPropVariant::ChangeType(VARTYPE vtNew, const PROPVARIANT* pSrc)
{
PROPVARIANT* pVar = const_cast<PROPVARIANT*>(pSrc);
// Convert in place if pSrc is NULL
if (pVar == NULL)
pVar = this;
// Do nothing if doing in place convert and vts not different
return ::VariantChangeType((VARIANT *)this, (VARIANT *)pVar, 0, vtNew);
}
HRESULT CPropVariant::InternalClear()
{
HRESULT hr = Clear();
if (FAILED(hr))
{
vt = VT_ERROR;
scode = hr;
}
return hr;
}
void CPropVariant::InternalCopy(const PROPVARIANT* pSrc)
{
HRESULT hr = Copy(pSrc);
if (FAILED(hr))
{
vt = VT_ERROR;
scode = hr;
}
}
HRESULT CPropVariant::WriteToStream(ISequentialStream *stream) const
{
HRESULT aResult = stream->Write(&vt, sizeof(vt), NULL);
if (FAILED(aResult))
return aResult;
if (vt == VT_EMPTY)
return S_OK;
int aNumBytes = 0;
switch (vt)
{
case VT_UI1:
case VT_I1:
aNumBytes = sizeof(BYTE);
break;
case VT_I2:
case VT_UI2:
case VT_BOOL:
aNumBytes = sizeof(short);
break;
case VT_I4:
case VT_UI4:
case VT_R4:
case VT_INT:
case VT_UINT:
case VT_ERROR:
aNumBytes = sizeof(long);
break;
case VT_FILETIME:
case VT_UI8:
case VT_R8:
case VT_CY:
case VT_DATE:
aNumBytes = sizeof(double);
break;
default:
break;
}
if (aNumBytes != 0)
return stream->Write(&bVal, aNumBytes, NULL);
if (vt == VT_BSTR)
{
UINT32 aLen = 0;
if(bstrVal != NULL)
aLen = SysStringLen(bstrVal);
HRESULT aResult = stream->Write(&aLen, sizeof(UINT32), NULL);
if (FAILED(aResult))
return aResult;
if(bstrVal == NULL)
return S_OK;
if(aLen == 0)
return S_OK;
return stream->Write(bstrVal, aLen * sizeof(wchar_t), NULL);
}
else
{
return E_FAIL;
/*
CPropVariant varBSTR;
HRESULT hr = VariantChangeType(&varBSTR, this, VARIANT_NOVALUEPROP, VT_BSTR);
if (FAILED(hr))
return;
MoveMemory(aMemoryPointer, varBSTR.bstrVal, SysStringLen(varBSTR.bstrVal));
*/
}
}
HRESULT CPropVariant::ReadFromStream(ISequentialStream *stream)
{
HRESULT hr = Clear();
if (FAILED(hr))
return hr;
VARTYPE vtRead;
hr = stream->Read(&vtRead, sizeof(VARTYPE), NULL);
if (hr == S_FALSE)
hr = E_FAIL;
if (FAILED(hr))
return hr;
vt = vtRead;
if (vt == VT_EMPTY)
return S_OK;
int aNumBytes = 0;
switch (vt)
{
case VT_UI1:
case VT_I1:
aNumBytes = sizeof(BYTE);
break;
case VT_I2:
case VT_UI2:
case VT_BOOL:
aNumBytes = sizeof(short);
break;
case VT_I4:
case VT_UI4:
case VT_R4:
case VT_INT:
case VT_UINT:
case VT_ERROR:
aNumBytes = sizeof(long);
break;
case VT_FILETIME:
case VT_UI8:
case VT_R8:
case VT_CY:
case VT_DATE:
aNumBytes = sizeof(double);
break;
default:
break;
}
if (aNumBytes != 0)
{
hr = stream->Read(&bVal, aNumBytes, NULL);
if (hr == S_FALSE)
hr = E_FAIL;
return hr;
}
if (vt == VT_BSTR)
{
bstrVal = NULL;
UINT32 aLen = 0;
hr = stream->Read(&aLen, sizeof(UINT32), NULL);
if (hr != S_OK)
return E_FAIL;
bstrVal = SysAllocStringLen(NULL, aLen);
if(bstrVal == NULL)
return E_OUTOFMEMORY;
hr = stream->Read(bstrVal, aLen * sizeof(wchar_t), NULL);
if (hr == S_FALSE)
hr = E_FAIL;
return hr;
}
else
return E_FAIL;
}
int CPropVariant::Compare(const CPropVariant &a)
{
if(vt != a.vt)
return 0; // it's mean some bug
switch (vt)
{
case VT_EMPTY:
return 0;
/*
case VT_I1:
return MyCompare(cVal, a.cVal);
*/
case VT_UI1:
return MyCompare(bVal, a.bVal);
case VT_I2:
return MyCompare(iVal, a.iVal);
case VT_UI2:
return MyCompare(uiVal, a.uiVal);
case VT_I4:
return MyCompare(lVal, a.lVal);
/*
case VT_INT:
return MyCompare(intVal, a.intVal);
*/
case VT_UI4:
return MyCompare(ulVal, a.ulVal);
/*
case VT_UINT:
return MyCompare(uintVal, a.uintVal);
*/
case VT_I8:
return MyCompare(INT64(*(const INT64 *)&hVal), INT64(*(const INT64 *)&a.hVal));
case VT_UI8:
return MyCompare(UINT64(*(const UINT64 *)&uhVal), UINT64(*(const UINT64 *)&a.uhVal));
case VT_BOOL:
return -MyCompare(boolVal, a.boolVal); // Test it
case VT_FILETIME:
return ::CompareFileTime(&filetime, &a.filetime);
case VT_BSTR:
return 0; // Not implemented
// return MyCompare(aPropVarint.cVal);
default:
return 0;
}
}
}}

60
Windows/PropVariant.h Executable file
View File

@@ -0,0 +1,60 @@
// Windows/PropVariant.h
// #pragma once
#ifndef __WINDOWS_PROPVARIANT_H
#define __WINDOWS_PROPVARIANT_H
namespace NWindows {
namespace NCOM {
class CPropVariant : public tagPROPVARIANT
{
public:
CPropVariant() { vt = VT_EMPTY; }
~CPropVariant() { Clear(); }
CPropVariant(const PROPVARIANT& varSrc);
CPropVariant(const CPropVariant& varSrc);
CPropVariant(BSTR bstrSrc);
CPropVariant(LPCOLESTR lpszSrc);
CPropVariant(bool bSrc) { vt = VT_BOOL; boolVal = (bSrc ? VARIANT_TRUE : VARIANT_FALSE); };
CPropVariant(UINT32 value) { vt = VT_UI4; ulVal = value; }
CPropVariant(UINT64 value) { vt = VT_UI8; uhVal = *(ULARGE_INTEGER*)&value; }
CPropVariant(const FILETIME &value) { vt = VT_FILETIME; filetime = value; }
CPropVariant(int value) { vt = VT_I4; lVal = value; }
CPropVariant(BYTE value) { vt = VT_UI1; bVal = value; }
CPropVariant(short value) { vt = VT_I2; iVal = value; }
CPropVariant(long value, VARTYPE vtSrc = VT_I4) { vt = vtSrc; lVal = value; }
CPropVariant& operator=(const CPropVariant& varSrc);
CPropVariant& operator=(const PROPVARIANT& varSrc);
CPropVariant& operator=(BSTR bstrSrc);
CPropVariant& operator=(LPCOLESTR lpszSrc);
CPropVariant& operator=(bool bSrc);
CPropVariant& operator=(UINT32 value);
CPropVariant& operator=(UINT64 value);
CPropVariant& operator=(const FILETIME &value);
CPropVariant& operator=(int value);
CPropVariant& operator=(BYTE value);
CPropVariant& operator=(short value);
CPropVariant& operator=(long value);
HRESULT Clear();
HRESULT Copy(const PROPVARIANT* pSrc);
HRESULT Attach(PROPVARIANT* pSrc);
HRESULT Detach(PROPVARIANT* pDest);
HRESULT ChangeType(VARTYPE vtNew, const PROPVARIANT* pSrc = NULL);
HRESULT InternalClear();
void InternalCopy(const PROPVARIANT* pSrc);
HRESULT WriteToStream(ISequentialStream *stream) const;
HRESULT ReadFromStream(ISequentialStream *stream);
int Compare(const CPropVariant &a1);
};
}}
#endif

View File

@@ -0,0 +1,143 @@
// PropVariantConversions.cpp
#include "StdAfx.h"
#include "PropVariantConversions.h"
#include "Windows/NationalTime.h"
#include "Windows/Defs.h"
#include "Common/StringConvert.h"
#include "Common/IntToString.h"
using namespace NWindows;
static UString ConvertUINT64ToString(UINT64 value)
{
wchar_t buffer[32];
ConvertUINT64ToString(value, buffer);
return buffer;
}
static UString ConvertINT64ToString(INT64 value)
{
wchar_t buffer[32];
ConvertINT64ToString(value, buffer);
return buffer;
}
/*
CSysString ConvertFileTimeToString(const FILETIME &fileTime, bool includeTime)
{
SYSTEMTIME systemTime;
if(!BOOLToBool(FileTimeToSystemTime(&fileTime, &systemTime)))
#ifndef _WIN32_WCE
throw 311907;
#else
return CSysString();
#endif
const int kBufferSize = 64;
CSysString stringDate;
if(!NNational::NTime::MyGetDateFormat(LOCALE_USER_DEFAULT,
0, &systemTime, NULL, stringDate))
#ifndef _WIN32_WCE
throw 311908;
#else
return CSysString();
#endif
if (!includeTime)
return stringDate;
CSysString stringTime;
if(!NNational::NTime::MyGetTimeFormat(LOCALE_USER_DEFAULT,
0, &systemTime, NULL, stringTime))
#ifndef _WIN32_WCE
throw 311909;
#else
return CSysString();
#endif
return stringDate + _T(" ") + stringTime;
}
*/
UString ConvertFileTimeToString2(const FILETIME &fileTime,
bool includeTime, bool includeSeconds)
{
CSysString string;
SYSTEMTIME systemTime;
if(!BOOLToBool(FileTimeToSystemTime(&fileTime, &systemTime)))
return UString();
TCHAR buffer[64];
wsprintf(buffer, TEXT("%04d-%02d-%02d"), systemTime.wYear, systemTime.wMonth, systemTime.wDay);
if (includeTime)
{
wsprintf(buffer + lstrlen(buffer), TEXT(" %02d:%02d"), systemTime.wHour, systemTime.wMinute);
if (includeSeconds)
wsprintf(buffer + lstrlen(buffer), TEXT(":%02d"), systemTime.wSecond);
}
return GetUnicodeString(buffer);
}
UString ConvertPropVariantToString(const PROPVARIANT &propVariant)
{
switch (propVariant.vt)
{
case VT_EMPTY:
return UString();
case VT_BSTR:
return propVariant.bstrVal;
case VT_UI1:
return ConvertUINT64ToString(propVariant.bVal);
case VT_UI2:
return ConvertUINT64ToString(propVariant.uiVal);
case VT_UI4:
return ConvertUINT64ToString(propVariant.ulVal);
case VT_UI8:
return ConvertUINT64ToString(*(UINT64 *)(&propVariant.uhVal));
case VT_FILETIME:
return ConvertFileTimeToString2(propVariant.filetime, true, true);
/*
case VT_I1:
return ConvertINT64ToString(propVariant.cVal);
*/
case VT_I2:
return ConvertINT64ToString(propVariant.iVal);
case VT_I4:
return ConvertINT64ToString(propVariant.lVal);
case VT_I8:
return ConvertINT64ToString(*(INT64 *)(&propVariant.hVal));
case VT_BOOL:
return VARIANT_BOOLToBool(propVariant.boolVal) ? L"1" : L"0";
default:
#ifndef _WIN32_WCE
throw 150245;
#else
return CSysString();
#endif
}
}
UINT64 ConvertPropVariantToUINT64(const PROPVARIANT &propVariant)
{
switch (propVariant.vt)
{
case VT_UI1:
return propVariant.bVal;
case VT_UI2:
return propVariant.uiVal;
case VT_UI4:
return propVariant.ulVal;
case VT_UI8:
return (*(UINT64 *)(&propVariant.uhVal));
default:
#ifndef _WIN32_WCE
throw 151199;
#else
return 0;
#endif
}
}

View File

@@ -0,0 +1,17 @@
// Windows/PropVariantConversions.h
#pragma once
#ifndef __PROPVARIANTCONVERSIONS_H
#define __PROPVARIANTCONVERSIONS_H
#include "Common/String.h"
// CSysString ConvertFileTimeToString(const FILETIME &fileTime, bool includeTime = true);
UString ConvertFileTimeToString2(const FILETIME &fileTime, bool includeTime = true,
bool includeSeconds = true);
UString ConvertPropVariantToString(const PROPVARIANT &propVariant);
UINT64 ConvertPropVariantToUINT64(const PROPVARIANT &propVariant);
#endif

266
Windows/Registry.cpp Executable file
View File

@@ -0,0 +1,266 @@
// Windows/Registry.cpp
#include "StdAfx.h"
#include "Windows/Registry.h"
namespace NWindows {
namespace NRegistry {
#define MYASSERT(expr) // _ASSERTE(expr)
CKey::~CKey()
{
Close();
}
HKEY CKey::Detach()
{
HKEY hKey = _object;
_object = NULL;
return hKey;
}
void CKey::Attach(HKEY hKey)
{
MYASSERT(_object == NULL);
_object = hKey;
}
LONG CKey::Create(HKEY parentKey, LPCTSTR keyName,
LPTSTR keyClass, DWORD options, REGSAM accessMask,
LPSECURITY_ATTRIBUTES securityAttributes, LPDWORD disposition)
{
MYASSERT(parentKey != NULL);
DWORD dispositionReal;
HKEY key = NULL;
LONG res = RegCreateKeyEx(parentKey, keyName, 0, keyClass,
options, accessMask, securityAttributes, &key, &dispositionReal);
if (disposition != NULL)
*disposition = dispositionReal;
if (res == ERROR_SUCCESS)
{
res = Close();
_object = key;
}
return res;
}
LONG CKey::Open(HKEY parentKey, LPCTSTR keyName, REGSAM accessMask)
{
MYASSERT(parentKey != NULL);
HKEY key = NULL;
LONG res = RegOpenKeyEx(parentKey, keyName, 0, accessMask, &key);
if (res == ERROR_SUCCESS)
{
res = Close();
MYASSERT(res == ERROR_SUCCESS);
_object = key;
}
return res;
}
LONG CKey::Close()
{
LONG res = ERROR_SUCCESS;
if (_object != NULL)
{
res = RegCloseKey(_object);
_object = NULL;
}
return res;
}
// win95, win98: deletes sunkey and all its subkeys
// winNT to be deleted must not have subkeys
LONG CKey::DeleteSubKey(LPCTSTR subKeyName)
{
MYASSERT(_object != NULL);
return RegDeleteKey(_object, subKeyName);
}
LONG CKey::RecurseDeleteKey(LPCTSTR subKeyName)
{
CKey key;
LONG res = key.Open(_object, subKeyName, KEY_READ | KEY_WRITE);
if (res != ERROR_SUCCESS)
return res;
FILETIME fileTime;
const UINT32 kBufferSize = MAX_PATH + 1; // 256 in ATL
DWORD size = kBufferSize;
TCHAR buffer[kBufferSize];
while (RegEnumKeyEx(key._object, 0, buffer, &size, NULL, NULL, NULL,
&fileTime) == ERROR_SUCCESS)
{
res = key.RecurseDeleteKey(buffer);
if (res != ERROR_SUCCESS)
return res;
size = kBufferSize;
}
key.Close();
return DeleteSubKey(subKeyName);
}
/////////////////////////
// Value Functions
static inline UINT32 BoolToUINT32(bool value)
{ return (value ? 1: 0); }
static inline bool UINT32ToBool(UINT32 value)
{ return (value != 0); }
LONG CKey::DeleteValue(LPCTSTR value)
{
MYASSERT(_object != NULL);
return RegDeleteValue(_object, (LPTSTR)value);
}
LONG CKey::SetValue(LPCTSTR valueName, UINT32 value)
{
MYASSERT(_object != NULL);
return RegSetValueEx(_object, valueName, NULL, REG_DWORD,
(BYTE * const)&value, sizeof(UINT32));
}
LONG CKey::SetValue(LPCTSTR valueName, bool value)
{
return SetValue(valueName, BoolToUINT32(value));
}
LONG CKey::SetValue(LPCTSTR valueName, LPCTSTR value)
{
MYASSERT(value != NULL);
MYASSERT(_object != NULL);
return RegSetValueEx(_object, valueName, NULL, REG_SZ,
(const BYTE * )value, (lstrlen(value) + 1) * sizeof(TCHAR));
}
LONG CKey::SetValue(LPCTSTR valueName, const CSysString &value)
{
MYASSERT(value != NULL);
MYASSERT(_object != NULL);
return RegSetValueEx(_object, valueName, NULL, REG_SZ,
(const BYTE *)(const TCHAR *)value, (value.Length() + 1) * sizeof(TCHAR));
}
LONG CKey::SetValue(LPCTSTR valueName, const void *value, UINT32 size)
{
MYASSERT(value != NULL);
MYASSERT(_object != NULL);
return RegSetValueEx(_object, valueName, NULL, REG_BINARY,
(const BYTE *)value, size);
}
LONG SetValue(HKEY parentKey, LPCTSTR keyName,
LPCTSTR valueName, LPCTSTR value)
{
MYASSERT(value != NULL);
CKey key;
LONG res = key.Create(parentKey, keyName);
if (res == ERROR_SUCCESS)
res = key.SetValue(valueName, value);
return res;
}
LONG CKey::SetKeyValue(LPCTSTR keyName, LPCTSTR valueName, LPCTSTR value)
{
MYASSERT(value != NULL);
CKey key;
LONG res = key.Create(_object, keyName);
if (res == ERROR_SUCCESS)
res = key.SetValue(valueName, value);
return res;
}
LONG CKey::QueryValue(LPCTSTR valueName, UINT32 &value)
{
DWORD type = NULL;
DWORD count = sizeof(DWORD);
LONG res = RegQueryValueEx(_object, (LPTSTR)valueName, NULL, &type,
(LPBYTE)&value, &count);
MYASSERT((res!=ERROR_SUCCESS) || (type == REG_DWORD));
MYASSERT((res!=ERROR_SUCCESS) || (count == sizeof(UINT32)));
return res;
}
LONG CKey::QueryValue(LPCTSTR valueName, bool &value)
{
UINT32 uintValue = BoolToUINT32(value);
LONG res = QueryValue(valueName, uintValue);
value = UINT32ToBool(uintValue);
return res;
}
LONG CKey::QueryValue(LPCTSTR valueName, LPTSTR value, UINT32 &count)
{
MYASSERT(count != NULL);
DWORD type = NULL;
LONG res = RegQueryValueEx(_object, (LPTSTR)valueName, NULL, &type,
(LPBYTE)value, (DWORD *)&count);
MYASSERT((res!=ERROR_SUCCESS) || (type == REG_SZ) ||
(type == REG_MULTI_SZ) || (type == REG_EXPAND_SZ));
return res;
}
LONG CKey::QueryValue(LPCTSTR valueName, CSysString &value)
{
value.Empty();
DWORD type = NULL;
UINT32 currentSize = 0;
LONG res = RegQueryValueEx(_object, (LPTSTR)valueName, NULL, &type,
NULL, (DWORD *)&currentSize);
if (res != ERROR_SUCCESS && res != ERROR_MORE_DATA)
return res;
res = QueryValue(valueName, value.GetBuffer(currentSize), currentSize);
value.ReleaseBuffer();
return res;
}
LONG CKey::QueryValue(LPCTSTR valueName, void *value, UINT32 &count)
{
DWORD type = NULL;
LONG res = RegQueryValueEx(_object, (LPTSTR)valueName, NULL, &type,
(LPBYTE)value, (DWORD *)&count);
MYASSERT((res!=ERROR_SUCCESS) || (type == REG_BINARY));
return res;
}
LONG CKey::QueryValue(LPCTSTR valueName, CByteBuffer &value, UINT32 &dataSize)
{
DWORD type = NULL;
dataSize = 0;
LONG res = RegQueryValueEx(_object, (LPTSTR)valueName, NULL, &type,
NULL, (DWORD *)&dataSize);
if (res != ERROR_SUCCESS && res != ERROR_MORE_DATA)
return res;
value.SetCapacity(dataSize);
return QueryValue(valueName, (BYTE *)value, dataSize);
}
LONG CKey::EnumKeys(CSysStringVector &keyNames)
{
keyNames.Clear();
CSysString keyName;
for(UINT32 index = 0; true; index++)
{
const UINT32 kBufferSize = MAX_PATH + 1; // 256 in ATL
FILETIME lastWriteTime;
UINT32 aNameSize = kBufferSize;
LONG aResult = ::RegEnumKeyEx(_object, index, keyName.GetBuffer(kBufferSize),
(DWORD *)&aNameSize, NULL, NULL, NULL, &lastWriteTime);
keyName.ReleaseBuffer();
if(aResult == ERROR_NO_MORE_ITEMS)
break;
if(aResult != ERROR_SUCCESS)
return aResult;
keyNames.Add(keyName);
}
return ERROR_SUCCESS;
}
}}

65
Windows/Registry.h Executable file
View File

@@ -0,0 +1,65 @@
// Windows/Registry.h
#pragma once
#ifndef __WINDOWS_REGISTRY_H
#define __WINDOWS_REGISTRY_H
#include "Common/Buffer.h"
#include "Common/String.h"
namespace NWindows {
namespace NRegistry {
const TCHAR kKeyNameDelimiter = TEXT('\\');
LONG SetValue(HKEY parentKey, LPCTSTR keyName,
LPCTSTR valueName, LPCTSTR value);
class CKey
{
HKEY _object;
public:
CKey(): _object(NULL) {}
~CKey();
operator HKEY() const { return _object; }
HKEY Detach();
void Attach(HKEY key);
LONG Create(HKEY parentKey, LPCTSTR keyName,
LPTSTR keyClass = REG_NONE, DWORD options = REG_OPTION_NON_VOLATILE,
REGSAM accessMask = KEY_ALL_ACCESS,
LPSECURITY_ATTRIBUTES securityAttributes = NULL,
LPDWORD disposition = NULL);
LONG Open(HKEY parentKey, LPCTSTR keyName,
REGSAM accessMask = KEY_ALL_ACCESS);
LONG Close();
LONG DeleteSubKey(LPCTSTR subKeyName);
LONG RecurseDeleteKey(LPCTSTR subKeyName);
LONG DeleteValue(LPCTSTR value);
LONG SetValue(LPCTSTR valueName, UINT32 value);
LONG SetValue(LPCTSTR valueName, bool value);
LONG SetValue(LPCTSTR valueName, LPCTSTR value);
LONG SetValue(LPCTSTR valueName, const CSysString &value);
LONG SetValue(LPCTSTR valueName, const void *value, UINT32 size);
LONG SetKeyValue(LPCTSTR keyName, LPCTSTR valueName, LPCTSTR value);
LONG QueryValue(LPCTSTR valueName, UINT32 &value);
LONG QueryValue(LPCTSTR valueName, bool &value);
LONG QueryValue(LPCTSTR valueName, LPTSTR value, UINT32 &dataSize);
LONG QueryValue(LPCTSTR valueName, CSysString &value);
LONG QueryValue(LPCTSTR valueName, void *value, UINT32 &dataSize);
LONG QueryValue(LPCTSTR valueName, CByteBuffer &value, UINT32 &dataSize);
LONG EnumKeys(CSysStringVector &keyNames);
};
}}
#endif

50
Windows/ResourceString.cpp Executable file
View File

@@ -0,0 +1,50 @@
// Windows/ResourceString.cpp
#include "StdAfx.h"
#include "Windows/ResourceString.h"
#ifndef _UNICODE
#include "Common/StringConvert.h"
#endif
extern HINSTANCE g_hInstance;
namespace NWindows {
CSysString MyLoadString(UINT resourceID)
{
CSysString s;
int size = 256;
int len;
do
{
size += 256;
len = ::LoadString(g_hInstance, resourceID, s.GetBuffer(size - 1), size);
} while (size - len <= 1);
s.ReleaseBuffer();
return s;
}
#ifndef _UNICODE
UString MyLoadStringW(UINT resourceID)
{
UString s;
int size = 256;
int len;
do
{
size += 256;
len = ::LoadStringW(g_hInstance, resourceID, s.GetBuffer(size - 1), size);
if (len == 0)
{
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
break;
return GetUnicodeString(MyLoadString(resourceID));
}
} while (size - len <= 1);
s.ReleaseBuffer();
return s;
}
#endif
}

22
Windows/ResourceString.h Executable file
View File

@@ -0,0 +1,22 @@
// Windows/ResourceString.h
#pragma once
#ifndef __WINDOWS_RESOURCESTRING_H
#define __WINDOWS_RESOURCESTRING_H
#include "Common/String.h"
namespace NWindows {
CSysString MyLoadString(UINT resourceID);
#ifdef _UNICODE
inline UString MyLoadStringW(UINT resourceID)
{ return MyLoadString(resourceID); }
#else
UString MyLoadStringW(UINT resourceID);
#endif
}
#endif

180
Windows/Shell.cpp Executable file
View File

@@ -0,0 +1,180 @@
// Windows/Shell.cpp
#include "StdAfx.h"
#include "Common/MyCom.h"
#include "Windows/Shell.h"
#include "Windows/COM.h"
namespace NWindows {
namespace NShell {
/////////////////////////
// CItemIDList
void CItemIDList::Free()
{
if(m_Object == NULL)
return;
CMyComPtr<IMalloc> shellMalloc;
if(::SHGetMalloc(&shellMalloc) != NOERROR)
throw 41099;
shellMalloc->Free(m_Object);
m_Object = NULL;
}
/*
CItemIDList::(LPCITEMIDLIST itemIDList): m_Object(NULL)
{ *this = itemIDList; }
CItemIDList::(const CItemIDList& itemIDList): m_Object(NULL)
{ *this = itemIDList; }
CItemIDList& CItemIDList::operator=(LPCITEMIDLIST object)
{
Free();
if (object != 0)
{
UINT32 size = GetSize(object);
m_Object = (LPITEMIDLIST)CoTaskMemAlloc(size);
if(m_Object != NULL)
MoveMemory(m_Object, object, size);
}
return *this;
}
CItemIDList& CItemIDList::operator=(const CItemIDList &object)
{
Free();
if(object.m_Object != NULL)
{
UINT32 size = GetSize(object.m_Object);
m_Object = (LPITEMIDLIST)CoTaskMemAlloc(size);
if(m_Object != NULL)
MoveMemory(m_Object, object.m_Object, size);
}
return *this;
}
*/
/////////////////////////////
// CDrop
void CDrop::Attach(HDROP object)
{
Free();
m_Object = object;
m_Assigned = true;
}
void CDrop::Free()
{
if(m_MustBeFinished && m_Assigned)
Finish();
m_Assigned = false;
}
CDrop::~CDrop()
{
Free();
}
UINT CDrop::QueryFile(UINT fileIndex, LPTSTR fileName, UINT fileNameSize)
{
return ::DragQueryFile(m_Object, fileIndex, fileName, fileNameSize);
}
UINT CDrop::QueryCountOfFiles()
{
return QueryFile(0xFFFFFFFF, NULL, 0);
}
CSysString CDrop::QueryFileName(UINT fileIndex)
{
CSysString fileName;
UINT bufferSize = QueryFile(fileIndex, NULL, 0);
QueryFile(fileIndex, fileName.GetBuffer(bufferSize), bufferSize + 1);
fileName.ReleaseBuffer();
return fileName;
}
void CDrop::QueryFileNames(CSysStringVector &fileNames)
{
fileNames.Clear();
UINT numFiles = QueryCountOfFiles();
fileNames.Reserve(numFiles);
for(UINT i = 0; i < numFiles; i++)
fileNames.Add(QueryFileName(i));
}
/////////////////////////////
// Functions
bool GetPathFromIDList(LPCITEMIDLIST itemIDList, CSysString &path)
{
bool result = BOOLToBool(::SHGetPathFromIDList(itemIDList,
path.GetBuffer(MAX_PATH)));
path.ReleaseBuffer();
return result;
}
bool BrowseForFolder(LPBROWSEINFO browseInfo, CSysString &resultPath)
{
NWindows::NCOM::CComInitializer comInitializer;
LPITEMIDLIST itemIDList = ::SHBrowseForFolder(browseInfo);
if (itemIDList == NULL)
return false;
CItemIDList itemIDListHolder;
itemIDListHolder.Attach(itemIDList);
return GetPathFromIDList(itemIDList, resultPath);
}
int CALLBACK BrowseCallbackProc(HWND hwnd, UINT uMsg, LPARAM lp, LPARAM data)
{
switch(uMsg)
{
case BFFM_INITIALIZED:
{
SendMessage(hwnd, BFFM_SETSELECTION, TRUE, data);
break;
}
case BFFM_SELCHANGED:
{
TCHAR dir[MAX_PATH];
if (::SHGetPathFromIDList((LPITEMIDLIST) lp , dir))
SendMessage(hwnd, BFFM_SETSTATUSTEXT, 0, (LPARAM)dir);
else
SendMessage(hwnd, BFFM_SETSTATUSTEXT, 0, (LPARAM)TEXT(""));
break;
}
default:
break;
}
return 0;
}
bool BrowseForFolder(HWND owner, LPCTSTR title, UINT ulFlags,
LPCTSTR initialFolder, CSysString &resultPath)
{
CSysString displayName;
BROWSEINFO browseInfo;
browseInfo.hwndOwner = owner;
browseInfo.pidlRoot = NULL;
browseInfo.pszDisplayName = displayName.GetBuffer(MAX_PATH);
browseInfo.lpszTitle = title;
browseInfo.ulFlags = ulFlags;
browseInfo.lpfn = (initialFolder != NULL) ? BrowseCallbackProc : NULL;
browseInfo.lParam = (LPARAM)initialFolder;
return BrowseForFolder(&browseInfo, resultPath);
}
bool BrowseForFolder(HWND owner, LPCTSTR title,
LPCTSTR initialFolder, CSysString &resultPath)
{
return BrowseForFolder(owner, title,
BIF_NEWDIALOGSTYLE | BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT, initialFolder, resultPath);
// BIF_STATUSTEXT; BIF_USENEWUI (Version 5.0)
}
}}

82
Windows/Shell.h Executable file
View File

@@ -0,0 +1,82 @@
// Windows/Shell.h
#pragma once
#ifndef __WINDOWS_SHELL_H
#define __WINDOWS_SHELL_H
#include "Common/String.h"
#include "Windows/Defs.h"
namespace NWindows{
namespace NShell{
/////////////////////////
// CItemIDList
class CItemIDList
{
LPITEMIDLIST m_Object;
public:
CItemIDList(): m_Object(NULL) {}
// CItemIDList(LPCITEMIDLIST itemIDList);
// CItemIDList(const CItemIDList& itemIDList);
~CItemIDList() { Free(); }
void Free();
void Attach(LPITEMIDLIST object)
{
Free();
m_Object = object;
}
LPITEMIDLIST Detach()
{
LPITEMIDLIST object = m_Object;
m_Object = NULL;
return object;
}
operator LPITEMIDLIST() { return m_Object;}
operator LPCITEMIDLIST() const { return m_Object;}
LPITEMIDLIST* operator&() { return &m_Object; }
LPITEMIDLIST operator->() { return m_Object; }
// CItemIDList& operator=(LPCITEMIDLIST object);
// CItemIDList& operator=(const CItemIDList &object);
};
/////////////////////////////
// CDrop
class CDrop
{
HDROP m_Object;
bool m_MustBeFinished;
bool m_Assigned;
void Free();
public:
CDrop(bool mustBeFinished) : m_MustBeFinished(mustBeFinished),
m_Assigned(false) {}
~CDrop();
void Attach(HDROP object);
operator HDROP() { return m_Object;}
bool QueryPoint(LPPOINT point)
{ return BOOLToBool(::DragQueryPoint(m_Object, point)); }
void Finish() { ::DragFinish(m_Object); }
UINT QueryFile(UINT fileIndex, LPTSTR fileName, UINT fileNameSize);
UINT QueryCountOfFiles();
CSysString QueryFileName(UINT fileIndex);
void QueryFileNames(CSysStringVector &fileNames);
};
/////////////////////////////
// Functions
bool GetPathFromIDList(LPCITEMIDLIST itemIDList, CSysString &path);
bool BrowseForFolder(LPBROWSEINFO lpbi, CSysString &resultPath);
bool BrowseForFolder(HWND owner, LPCTSTR title,
LPCTSTR initialFolder, CSysString &resultPath);
}}
#endif

8
Windows/StdAfx.h Executable file
View File

@@ -0,0 +1,8 @@
// stdafx.h
#ifndef __STDAFX_H
#define __STDAFX_H
#include <windows.h>
#endif

17
Windows/Synchronization.cpp Executable file
View File

@@ -0,0 +1,17 @@
// Windows/Synchronization.cpp
#include "StdAfx.h"
#include "Synchronization.h"
namespace NWindows {
namespace NSynchronization {
CEvent::CEvent(bool manualReset, bool initiallyOwn, LPCTSTR name,
LPSECURITY_ATTRIBUTES securityAttributes)
{
if (!Create(manualReset, initiallyOwn, name, securityAttributes))
throw "CreateEvent error";
}
}}

116
Windows/Synchronization.h Executable file
View File

@@ -0,0 +1,116 @@
// Windows/Synchronization.h
#pragma once
#ifndef __WINDOWS_SYNCHRONIZATION_H
#define __WINDOWS_SYNCHRONIZATION_H
#include "Defs.h"
#include "Handle.h"
namespace NWindows {
namespace NSynchronization {
class CObject: public CHandle
{
public:
bool Lock(DWORD timeoutInterval = INFINITE)
{ return (::WaitForSingleObject(_handle, timeoutInterval) == WAIT_OBJECT_0); }
};
class CBaseEvent: public CObject
{
public:
bool Create(bool manualReset, bool initiallyOwn, LPCTSTR name = NULL,
LPSECURITY_ATTRIBUTES securityAttributes = NULL)
{
_handle = ::CreateEvent(securityAttributes, BoolToBOOL(manualReset),
BoolToBOOL(initiallyOwn), name);
return (_handle != 0);
}
bool Open(DWORD desiredAccess, bool inheritHandle, LPCTSTR name)
{
_handle = ::OpenEvent(desiredAccess, BoolToBOOL(inheritHandle), name);
return (_handle != 0);
}
bool Set() { return BOOLToBool(::SetEvent(_handle)); }
bool Pulse() { return BOOLToBool(::PulseEvent(_handle)); }
bool Reset() { return BOOLToBool(::ResetEvent(_handle)); }
};
class CEvent: public CBaseEvent
{
public:
CEvent() {};
CEvent(bool manualReset, bool initiallyOwn,
LPCTSTR name = NULL, LPSECURITY_ATTRIBUTES securityAttributes = NULL);
};
class CManualResetEvent: public CEvent
{
public:
CManualResetEvent(bool initiallyOwn = false, LPCTSTR name = NULL,
LPSECURITY_ATTRIBUTES securityAttributes = NULL):
CEvent(true, initiallyOwn, name, securityAttributes) {};
};
class CAutoResetEvent: public CEvent
{
public:
CAutoResetEvent(bool initiallyOwn = false, LPCTSTR name = NULL,
LPSECURITY_ATTRIBUTES securityAttributes = NULL):
CEvent(false, initiallyOwn, name, securityAttributes) {};
};
class CMutex: public CObject
{
public:
bool Create(bool initiallyOwn, LPCTSTR name = NULL,
LPSECURITY_ATTRIBUTES securityAttributes = NULL)
{
_handle = ::CreateMutex(securityAttributes, BoolToBOOL(initiallyOwn), name);
return (_handle != 0);
}
bool Open(DWORD desiredAccess, bool inheritHandle, LPCTSTR name)
{
_handle = ::OpenMutex(desiredAccess, BoolToBOOL(inheritHandle), name);
return (_handle != 0);
}
bool Release() { return BOOLToBool(::ReleaseMutex(_handle)); }
};
class CMutexLock
{
CMutex &_object;
public:
CMutexLock(CMutex &object): _object(object) { _object.Lock(); }
~CMutexLock() { _object.Release(); }
};
class CCriticalSection
{
CRITICAL_SECTION _object;
// void Initialize() { ::InitializeCriticalSection(&_object); }
// void Delete() { ::DeleteCriticalSection(&_object); }
public:
CCriticalSection() { ::InitializeCriticalSection(&_object); }
~CCriticalSection() { ::DeleteCriticalSection(&_object); }
void Enter() { ::EnterCriticalSection(&_object); }
void Leave() { ::LeaveCriticalSection(&_object); }
};
class CCriticalSectionLock
{
CCriticalSection &_object;
void Unlock() { _object.Leave(); }
public:
CCriticalSectionLock(CCriticalSection &object): _object(object)
{_object.Enter(); }
~CCriticalSectionLock() { Unlock(); }
};
}}
#endif

15
Windows/System.cpp Executable file
View File

@@ -0,0 +1,15 @@
// Windows/System.h
#include "StdAfx.h"
#include "System.h"
#ifndef _UNICODE
#include "../Common/StringConvert.h"
#endif
namespace NWindows {
namespace NSystem {
}}

15
Windows/System.h Executable file
View File

@@ -0,0 +1,15 @@
// Windows/System.h
#pragma once
#ifndef __WINDOWS_SYSTEM_H
#define __WINDOWS_SYSTEM_H
#include "../Common/String.h"
namespace NWindows {
namespace NSystem {
}}
#endif

45
Windows/Thread.h Executable file
View File

@@ -0,0 +1,45 @@
// Windows/Thread.h
#pragma once
#ifndef __WINDOWS_THREAD_H
#define __WINDOWS_THREAD_H
#include "Handle.h"
#include "Defs.h"
namespace NWindows {
class CThread: public CHandle
{
public:
bool Create(LPSECURITY_ATTRIBUTES threadAttributes,
SIZE_T stackSize, LPTHREAD_START_ROUTINE startAddress,
LPVOID parameter, DWORD creationFlags, LPDWORD threadId)
{
_handle = ::CreateThread(threadAttributes, stackSize, startAddress,
parameter, creationFlags, threadId);
return (_handle != NULL);
}
bool Create(LPTHREAD_START_ROUTINE startAddress, LPVOID parameter)
{
DWORD threadId;
return Create(NULL, 0, startAddress, parameter, 0, &threadId);
}
DWORD Resume()
{ return ::ResumeThread(_handle); }
DWORD Suspend()
{ return ::SuspendThread(_handle); }
bool Terminate(DWORD exitCode)
{ return BOOLToBool(::TerminateThread(_handle, exitCode)); }
int GetPriority()
{ return ::GetThreadPriority(_handle); }
bool SetPriority(int priority)
{ return BOOLToBool(::SetThreadPriority(_handle, priority)); }
};
}
#endif

58
Windows/Time.h Executable file
View File

@@ -0,0 +1,58 @@
// Windows/Time.h
#pragma once
#ifndef __WINDOWS_TIME_H
#define __WINDOWS_TIME_H
#include "Common/Types.h"
// #include <windows.h>
// #include <time.h>
#include "Windows/Defs.h"
namespace NWindows {
namespace NTime {
inline bool DosTimeToFileTime(UINT32 dosTime, FILETIME &fileTime)
{
return BOOLToBool(::DosDateTimeToFileTime(UINT16(dosTime >> 16),
UINT16(dosTime & 0xFFFF), &fileTime));
}
inline bool FileTimeToDosTime(const FILETIME &fileTime, UINT32 &dosTime)
{
return BOOLToBool(::FileTimeToDosDateTime(&fileTime,
((LPWORD)&dosTime) + 1, (LPWORD)&dosTime));
}
const UINT64 kUnixTimeStartValue =
#if ( __GNUC__)
116444736000000000LL;
#else
116444736000000000;
#endif
const UINT32 kNumTimeQuantumsInSecond = 10000000;
inline void UnixTimeToFileTime(long unixTime, FILETIME &fileTime)
{
ULONGLONG ll = UInt32x32To64(unixTime, kNumTimeQuantumsInSecond) +
kUnixTimeStartValue;
fileTime.dwLowDateTime = (DWORD) ll;
fileTime.dwHighDateTime = DWORD(ll >> 32);
}
inline bool FileTimeToUnixTime(const FILETIME &fileTime, long &unixTime)
{
UINT64 winTime = (((UINT64)fileTime.dwHighDateTime) << 32) + fileTime.dwLowDateTime;
if (winTime < kUnixTimeStartValue)
return false;
winTime = (winTime - kUnixTimeStartValue) / kNumTimeQuantumsInSecond;
if (winTime >= 0xFFFFFFFF)
return false;
unixTime = (long)winTime;
return true;
}
}}
#endif

80
Windows/Window.cpp Executable file
View File

@@ -0,0 +1,80 @@
// Windows/Window.cpp
#include "StdAfx.h"
#include "Windows/Window.h"
#ifndef _UNICODE
#include "Common/StringConvert.h"
#endif
namespace NWindows {
#ifndef _UNICODE
bool CWindow::SetText(LPCWSTR s)
{
if (::SetWindowTextW(_window, s))
return true;
if (::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return false;
return SetText(UnicodeStringToMultiByte(s));
}
#endif
bool CWindow::GetText(CSysString &s)
{
s.Empty();
int length = GetTextLength();
if (length == 0)
return (::GetLastError() == ERROR_SUCCESS);
length = GetText(s.GetBuffer(length), length + 1);
s.ReleaseBuffer();
if (length == 0)
return (::GetLastError() != ERROR_SUCCESS);
return true;
}
#ifndef _UNICODE
bool CWindow::GetText(UString &s)
{
s.Empty();
int length = GetWindowTextLengthW(_window);
if (length == 0)
{
UINT lastError = ::GetLastError();
if (lastError == ERROR_SUCCESS)
return true;
if (lastError != ERROR_CALL_NOT_IMPLEMENTED)
return false;
CSysString sysString;
bool result = GetText(sysString);
s = GetUnicodeString(sysString);
return result;
}
length = GetWindowTextW(_window, s.GetBuffer(length), length + 1);
s.ReleaseBuffer();
if (length == 0)
return (::GetLastError() == ERROR_SUCCESS);
return true;
}
#endif
/*
bool CWindow::ModifyStyleBase(int styleOffset,
DWORD remove, DWORD add, UINT flags)
{
DWORD style = GetWindowLong(styleOffset);
DWORD newStyle = (style & ~remove) | add;
if (style == newStyle)
return false; // it is not good
SetWindowLong(styleOffset, newStyle);
if (flags != 0)
{
::SetWindowPos(_window, NULL, 0, 0, 0, 0,
SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE | flags);
}
return TRUE;
}
*/
}

176
Windows/Window.h Executable file
View File

@@ -0,0 +1,176 @@
// Windows/Window.h
#pragma once
#ifndef __WINDOWS_WINDOW_H
#define __WINDOWS_WINDOW_H
#include "Windows/Defs.h"
#include "Common/String.h"
namespace NWindows {
class CWindow
{
private:
// bool ModifyStyleBase(int styleOffset, DWORD remove, DWORD add, UINT flags);
protected:
HWND _window;
public:
CWindow(HWND newWindow = NULL): _window(newWindow){};
CWindow& operator=(HWND newWindow)
{
_window = newWindow;
return *this;
}
operator HWND() const { return _window; }
void Attach(HWND newWindow)
{ _window = newWindow; }
HWND Detach()
{
HWND window = _window;
_window = NULL;
return window;
}
HWND GetParent() const
{ return ::GetParent(_window); }
bool GetWindowRect(LPRECT rect) const
{ return BOOLToBool(::GetWindowRect(_window,rect )); }
bool IsZoomed() const
{ return BOOLToBool(::IsZoomed(_window)); }
bool ClientToScreen(LPPOINT point) const
{ return BOOLToBool(::ClientToScreen(_window, point)); }
bool ScreenToClient(LPPOINT point) const
{ return BOOLToBool(::ScreenToClient(_window, point)); }
bool CreateEx(DWORD exStyle, LPCTSTR className,
LPCTSTR windowName, DWORD style,
int x, int y, int width, int height,
HWND parentWindow, HMENU idOrHMenu,
HINSTANCE instance, LPVOID createParam)
{
_window = ::CreateWindowEx(exStyle, className, windowName,
style, x, y, width, height, parentWindow,
idOrHMenu, instance, createParam);
return (_window != NULL);
}
bool Destroy()
{
if (_window == NULL)
return true;
bool result = BOOLToBool(::DestroyWindow(_window));
if(result)
_window = NULL;
return result;
}
bool IsWindow()
{ return BOOLToBool(::IsWindow(_window)); }
bool Move(int x, int y, int width, int height, bool repaint = true)
{ return BOOLToBool(::MoveWindow(_window, x, y, width, height, BoolToBOOL(repaint))); }
bool GetClientRect(LPRECT rect)
{ return BOOLToBool(::GetClientRect(_window, rect)); }
bool Show(int cmdShow)
{ return BOOLToBool(::ShowWindow(_window, cmdShow)); }
bool SetPlacement(CONST WINDOWPLACEMENT *placement)
{ return BOOLToBool(::SetWindowPlacement(_window, placement)); }
bool GetPlacement(WINDOWPLACEMENT *placement)
{ return BOOLToBool(::GetWindowPlacement(_window, placement)); }
bool Update()
{ return BOOLToBool(::UpdateWindow(_window)); }
bool InvalidateRect(LPCRECT rect, bool backgroundErase = true)
{ return BOOLToBool(::InvalidateRect(_window, rect, BoolToBOOL(backgroundErase))); }
void SetRedraw(bool redraw = true)
{ SendMessage(WM_SETREDRAW, BoolToBOOL(redraw), 0); }
#ifndef _WIN32_WCE
LONG SetStyle(LONG_PTR style)
{ return SetLongPtr(GWL_STYLE, style); }
DWORD GetStyle( ) const
{ return GetLongPtr(GWL_STYLE); }
#else
LONG SetStyle(LONG_PTR style)
{ return SetLong(GWL_STYLE, style); }
DWORD GetStyle( ) const
{ return GetLong(GWL_STYLE); }
#endif
LONG_PTR SetLong(int index, LONG_PTR newLongPtr )
{ return ::SetWindowLong(_window, index, newLongPtr); }
LONG_PTR GetLong(int index) const
{ return ::GetWindowLong(_window, index ); }
LONG_PTR SetUserDataLong(LONG_PTR newLongPtr )
{ return SetLong(GWL_USERDATA, newLongPtr); }
LONG_PTR GetUserDataLong() const
{ return GetLong(GWL_USERDATA); }
#ifndef _WIN32_WCE
LONG_PTR SetLongPtr(int index, LONG_PTR newLongPtr )
{ return ::SetWindowLongPtr(_window, index, newLongPtr); }
LONG_PTR GetLongPtr(int index) const
{ return ::GetWindowLongPtr(_window, index ); }
LONG_PTR SetUserDataLongPtr(LONG_PTR newLongPtr )
{ return SetLongPtr(GWLP_USERDATA, newLongPtr); }
LONG_PTR GetUserDataLongPtr() const
{ return GetLongPtr(GWLP_USERDATA); }
#endif
/*
bool ModifyStyle(HWND hWnd, DWORD remove, DWORD add, UINT flags = 0)
{ return ModifyStyleBase(GWL_STYLE, remove, add, flags); }
bool ModifyStyleEx(HWND hWnd, DWORD remove, DWORD add, UINT flags = 0)
{ return ModifyStyleBase(GWL_EXSTYLE, remove, add, flags); }
*/
HWND SetFocus()
{ return ::SetFocus(_window); }
LRESULT SendMessage(UINT message, WPARAM wParam = 0, LPARAM lParam = 0)
{ return ::SendMessage(_window, message, wParam, lParam) ;}
bool PostMessage(UINT message, WPARAM wParam = 0, LPARAM lParam = 0)
{ return BOOLToBool(::PostMessage(_window, message, wParam, lParam)) ;}
bool SetText(LPCTSTR s)
{ return BOOLToBool(::SetWindowText(_window, s)); }
#ifndef _UNICODE
bool CWindow::SetText(LPCWSTR s);
#endif
int GetTextLength() const
{ return GetWindowTextLength(_window); }
UINT GetText(LPTSTR string, int maxCount) const
{ return GetWindowText(_window, string, maxCount); }
bool GetText(CSysString &s);
#ifndef _UNICODE
/*
UINT GetText(LPWSTR string, int maxCount) const
{ return GetWindowTextW(_window, string, maxCount); }
*/
bool GetText(UString &s);
#endif
bool Enable(bool enable)
{ return BOOLToBool(::EnableWindow(_window, BoolToBOOL(enable))); }
bool IsEnabled()
{ return BOOLToBool(::IsWindowEnabled(_window)); }
#ifndef _WIN32_WCE
HMENU GetSystemMenu(bool revert)
{ return ::GetSystemMenu(_window, BoolToBOOL(revert)); }
#endif
UINT_PTR SetTimer(UINT_PTR idEvent, UINT elapse, TIMERPROC timerFunc = 0)
{ return ::SetTimer(_window, idEvent, elapse, timerFunc); }
bool KillTimer(UINT_PTR idEvent)
{return BOOLToBool(::KillTimer(_window, idEvent)); }
};
}
#endif