]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/msw/volume.cpp
GetParent() was always used in test for wxHSCROLL checked in in last commit; use...
[wxWidgets.git] / src / msw / volume.cpp
... / ...
CommitLineData
1///////////////////////////////////////////////////////////////////////////////
2// Name: src/msw/volume.cpp
3// Purpose: wxFSVolume - encapsulates system volume information
4// Author: George Policello
5// Modified by:
6// Created: 28 Jan 02
7// RCS-ID: $Id$
8// Copyright: (c) 2002 George Policello
9// Licence: wxWindows licence
10///////////////////////////////////////////////////////////////////////////////
11
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
20#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
21 #pragma implementation "fsvolume.h"
22#endif
23
24#include "wx/wxprec.h"
25
26#ifdef __BORLANDC__
27 #pragma hdrstop
28#endif
29
30#if wxUSE_FSVOLUME
31
32#ifndef WX_PRECOMP
33 #if wxUSE_GUI
34 #include "wx/icon.h"
35 #endif
36 #include "wx/intl.h"
37#endif // WX_PRECOMP
38
39#include "wx/dir.h"
40#include "wx/hashmap.h"
41#include "wx/dynlib.h"
42#include "wx/arrimpl.cpp"
43
44#include "wx/volume.h"
45
46#include <shellapi.h>
47#include <shlobj.h>
48#include "wx/msw/missing.h"
49
50#if wxUSE_BASE
51
52//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
53// Dynamic library function defs.
54//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
55
56static wxDynamicLibrary s_mprLib;
57
58typedef DWORD (WINAPI* WNetOpenEnumPtr)(DWORD, DWORD, DWORD, LPNETRESOURCE, LPHANDLE);
59typedef DWORD (WINAPI* WNetEnumResourcePtr)(HANDLE, LPDWORD, LPVOID, LPDWORD);
60typedef DWORD (WINAPI* WNetCloseEnumPtr)(HANDLE);
61
62static WNetOpenEnumPtr s_pWNetOpenEnum;
63static WNetEnumResourcePtr s_pWNetEnumResource;
64static WNetCloseEnumPtr s_pWNetCloseEnum;
65
66//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
67// Globals/Statics
68//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
69static long s_cancelSearch = FALSE;
70
71struct FileInfo
72{
73 FileInfo(unsigned flag=0, wxFSVolumeKind type=wxFS_VOL_OTHER) :
74 m_flags(flag), m_type(type) {}
75
76 FileInfo(const FileInfo& other) { *this = other; }
77 FileInfo& operator=(const FileInfo& other)
78 {
79 m_flags = other.m_flags;
80 m_type = other.m_type;
81 return *this;
82 }
83
84 unsigned m_flags;
85 wxFSVolumeKind m_type;
86};
87WX_DECLARE_STRING_HASH_MAP(FileInfo, FileInfoMap);
88// Cygwin bug (?) destructor for global s_fileInfo is called twice...
89static FileInfoMap& GetFileInfoMap()
90{
91 static FileInfoMap s_fileInfo(25);
92
93 return s_fileInfo;
94}
95#define s_fileInfo (GetFileInfoMap())
96
97//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
98// Local helper functions.
99//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
100
101//=============================================================================
102// Function: GetBasicFlags
103// Purpose: Set basic flags, primarily wxFS_VOL_REMOTE and wxFS_VOL_REMOVABLE.
104// Notes: - Local and mapped drives are mounted by definition. We have no
105// way to determine mounted status of network drives, so assume that
106// all drives are mounted, and let the caller decide otherwise.
107// - Other flags are 'best guess' from type of drive. The system will
108// not report the file attributes with any degree of accuracy.
109//=============================================================================
110static unsigned GetBasicFlags(const wxChar* filename)
111{
112 unsigned flags = wxFS_VOL_MOUNTED;
113
114 //----------------------------------
115 // 'Best Guess' based on drive type.
116 //----------------------------------
117 wxFSVolumeKind type;
118 switch(GetDriveType(filename))
119 {
120 case DRIVE_FIXED:
121 type = wxFS_VOL_DISK;
122 break;
123
124 case DRIVE_REMOVABLE:
125 flags |= wxFS_VOL_REMOVABLE;
126 type = wxFS_VOL_FLOPPY;
127 break;
128
129 case DRIVE_CDROM:
130 flags |= wxFS_VOL_REMOVABLE | wxFS_VOL_READONLY;
131 type = wxFS_VOL_CDROM;
132 break;
133
134 case DRIVE_REMOTE:
135 flags |= wxFS_VOL_REMOTE;
136 type = wxFS_VOL_NETWORK;
137 break;
138
139 case DRIVE_NO_ROOT_DIR:
140 flags &= ~wxFS_VOL_MOUNTED;
141 type = wxFS_VOL_OTHER;
142 break;
143
144 default:
145 type = wxFS_VOL_OTHER;
146 break;
147 }
148
149 //-----------------------------------------------------------------------
150 // The following will most likely will not modify anything not set above,
151 // and will not work at all for network shares or empty CD ROM drives.
152 // But it is a good check if the Win API ever gets better about reporting
153 // this information.
154 //-----------------------------------------------------------------------
155 SHFILEINFO fi;
156 long rc;
157 rc = SHGetFileInfo(filename, 0, &fi, sizeof(fi), SHGFI_ATTRIBUTES );
158 if (!rc)
159 {
160 wxLogError(_("Cannot read typename from '%s'!"), filename);
161 }
162 else
163 {
164 if (fi.dwAttributes & SFGAO_READONLY)
165 flags |= wxFS_VOL_READONLY;
166 if (fi.dwAttributes & SFGAO_REMOVABLE)
167 flags |= wxFS_VOL_REMOVABLE;
168 }
169
170 //------------------
171 // Flags are cached.
172 //------------------
173 s_fileInfo[filename] = FileInfo(flags, type);
174
175 return flags;
176} // GetBasicFlags
177
178//=============================================================================
179// Function: FilteredAdd
180// Purpose: Add a file to the list if it meets the filter requirement.
181// Notes: - See GetBasicFlags for remarks about the Mounted flag.
182//=============================================================================
183static bool FilteredAdd(wxArrayString& list, const wxChar* filename,
184 unsigned flagsSet, unsigned flagsUnset)
185{
186 bool accept = true;
187 unsigned flags = GetBasicFlags(filename);
188
189 if (flagsSet & wxFS_VOL_MOUNTED && !(flags & wxFS_VOL_MOUNTED))
190 accept = false;
191 else if (flagsUnset & wxFS_VOL_MOUNTED && (flags & wxFS_VOL_MOUNTED))
192 accept = false;
193 else if (flagsSet & wxFS_VOL_REMOVABLE && !(flags & wxFS_VOL_REMOVABLE))
194 accept = false;
195 else if (flagsUnset & wxFS_VOL_REMOVABLE && (flags & wxFS_VOL_REMOVABLE))
196 accept = false;
197 else if (flagsSet & wxFS_VOL_READONLY && !(flags & wxFS_VOL_READONLY))
198 accept = false;
199 else if (flagsUnset & wxFS_VOL_READONLY && (flags & wxFS_VOL_READONLY))
200 accept = false;
201 else if (flagsSet & wxFS_VOL_REMOTE && !(flags & wxFS_VOL_REMOTE))
202 accept = false;
203 else if (flagsUnset & wxFS_VOL_REMOTE && (flags & wxFS_VOL_REMOTE))
204 accept = false;
205
206 // Add to the list if passed the filter.
207 if (accept)
208 list.Add(filename);
209
210 return accept;
211} // FilteredAdd
212
213//=============================================================================
214// Function: BuildListFromNN
215// Purpose: Append or remove items from the list
216// Notes: - There is no way to find all disconnected NN items, or even to find
217// all items while determining which are connected and not. So this
218// function will find either all items or connected items.
219//=============================================================================
220static void BuildListFromNN(wxArrayString& list, NETRESOURCE* pResSrc,
221 unsigned flagsSet, unsigned flagsUnset)
222{
223 HANDLE hEnum;
224 int rc;
225
226 //-----------------------------------------------
227 // Scope may be all drives or all mounted drives.
228 //-----------------------------------------------
229 unsigned scope = RESOURCE_GLOBALNET;
230 if (flagsSet & wxFS_VOL_MOUNTED)
231 scope = RESOURCE_CONNECTED;
232
233 //----------------------------------------------------------------------
234 // Enumerate all items, adding only non-containers (ie. network shares).
235 // Containers cause a recursive call to this function for their own
236 // enumeration.
237 //----------------------------------------------------------------------
238 if (rc = s_pWNetOpenEnum(scope, RESOURCETYPE_DISK, 0, pResSrc, &hEnum), rc == NO_ERROR)
239 {
240 DWORD count = 1;
241 DWORD size = 256;
242 NETRESOURCE* pRes = (NETRESOURCE*)malloc(size);
243 memset(pRes, 0, sizeof(NETRESOURCE));
244 while (rc = s_pWNetEnumResource(hEnum, &count, pRes, &size), rc == NO_ERROR || rc == ERROR_MORE_DATA)
245 {
246 if (s_cancelSearch)
247 break;
248
249 if (rc == ERROR_MORE_DATA)
250 {
251 pRes = (NETRESOURCE*)realloc(pRes, size);
252 count = 1;
253 }
254 else if (count == 1)
255 {
256 // Enumerate the container.
257 if (pRes->dwUsage & RESOURCEUSAGE_CONTAINER)
258 {
259 BuildListFromNN(list, pRes, flagsSet, flagsUnset);
260 }
261
262 // Add the network share.
263 else
264 {
265 wxString filename(pRes->lpRemoteName);
266
267 if (filename.Len())
268 {
269 if (filename.Last() != '\\')
270 filename.Append('\\');
271
272 // The filter function will not know mounted from unmounted, and neither do we unless
273 // we are iterating using RESOURCE_CONNECTED, in which case they all are mounted.
274 // Volumes on disconnected servers, however, will correctly show as unmounted.
275 FilteredAdd(list, filename, flagsSet, flagsUnset&~wxFS_VOL_MOUNTED);
276 if (scope == RESOURCE_GLOBALNET)
277 s_fileInfo[filename].m_flags &= ~wxFS_VOL_MOUNTED;
278 }
279 }
280 }
281 else if (count == 0)
282 break;
283 }
284 free(pRes);
285 s_pWNetCloseEnum(hEnum);
286 }
287} // BuildListFromNN
288
289//=============================================================================
290// Function: CompareFcn
291// Purpose: Used to sort the NN list alphabetically, case insensitive.
292//=============================================================================
293static int CompareFcn(const wxString& first, const wxString& second)
294{
295 return wxStricmp(first.c_str(), second.c_str());
296} // CompareFcn
297
298//=============================================================================
299// Function: BuildRemoteList
300// Purpose: Append Network Neighborhood items to the list.
301// Notes: - Mounted gets transalated into Connected. FilteredAdd is told
302// to ignore the Mounted flag since we need to handle it in a weird
303// way manually.
304// - The resulting list is sorted alphabetically.
305//=============================================================================
306static bool BuildRemoteList(wxArrayString& list, NETRESOURCE* pResSrc,
307 unsigned flagsSet, unsigned flagsUnset)
308{
309 // NN query depends on dynamically loaded library.
310 if (!s_pWNetOpenEnum || !s_pWNetEnumResource || !s_pWNetCloseEnum)
311 {
312 wxLogError(_("Failed to load mpr.dll."));
313 return false;
314 }
315
316 // Don't waste time doing the work if the flags conflict.
317 if (flagsSet & wxFS_VOL_MOUNTED && flagsUnset & wxFS_VOL_MOUNTED)
318 return false;
319
320 //----------------------------------------------
321 // Generate the list according to the flags set.
322 //----------------------------------------------
323 BuildListFromNN(list, pResSrc, flagsSet, flagsUnset);
324 list.Sort(CompareFcn);
325
326 //-------------------------------------------------------------------------
327 // If mounted only is requested, then we only need one simple pass.
328 // Otherwise, we need to build a list of all NN volumes and then apply the
329 // list of mounted drives to it.
330 //-------------------------------------------------------------------------
331 if (!(flagsSet & wxFS_VOL_MOUNTED))
332 {
333 // generate.
334 wxArrayString mounted;
335 BuildListFromNN(mounted, pResSrc, flagsSet | wxFS_VOL_MOUNTED, flagsUnset & ~wxFS_VOL_MOUNTED);
336 mounted.Sort(CompareFcn);
337
338 // apply list from bottom to top to preserve indexes if removing items.
339 int iList = list.GetCount()-1;
340 int iMounted;
341 for (iMounted = mounted.GetCount()-1; iMounted >= 0 && iList >= 0; iMounted--)
342 {
343 int compare;
344 wxString all(list[iList]);
345 wxString mount(mounted[iMounted]);
346
347 while (compare =
348 wxStricmp(list[iList].c_str(), mounted[iMounted].c_str()),
349 compare > 0 && iList >= 0)
350 {
351 iList--;
352 all = list[iList];
353 }
354
355
356 if (compare == 0)
357 {
358 // Found the element. Remove it or mark it mounted.
359 if (flagsUnset & wxFS_VOL_MOUNTED)
360 list.RemoveAt(iList);
361 else
362 s_fileInfo[list[iList]].m_flags |= wxFS_VOL_MOUNTED;
363
364 }
365
366 iList--;
367 }
368 }
369
370 return true;
371} // BuildRemoteList
372
373//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
374// wxFSVolume
375//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
376
377//=============================================================================
378// Function: GetVolumes
379// Purpose: Generate and return a list of all volumes (drives) available.
380// Notes:
381//=============================================================================
382wxArrayString wxFSVolumeBase::GetVolumes(int flagsSet, int flagsUnset)
383{
384 ::InterlockedExchange(&s_cancelSearch, FALSE); // reset
385
386 if (!s_mprLib.IsLoaded() && s_mprLib.Load(_T("mpr.dll")))
387 {
388#ifdef UNICODE
389 s_pWNetOpenEnum = (WNetOpenEnumPtr)s_mprLib.GetSymbol(_T("WNetOpenEnumW"));
390 s_pWNetEnumResource = (WNetEnumResourcePtr)s_mprLib.GetSymbol(_T("WNetEnumResourceW"));
391#else
392 s_pWNetOpenEnum = (WNetOpenEnumPtr)s_mprLib.GetSymbol(_T("WNetOpenEnumA"));
393 s_pWNetEnumResource = (WNetEnumResourcePtr)s_mprLib.GetSymbol(_T("WNetEnumResourceA"));
394#endif
395 s_pWNetCloseEnum = (WNetCloseEnumPtr)s_mprLib.GetSymbol(_T("WNetCloseEnum"));
396 }
397
398 wxArrayString list;
399
400 //-------------------------------
401 // Local and mapped drives first.
402 //-------------------------------
403 // Allocate the required space for the API call.
404 size_t chars = GetLogicalDriveStrings(0, 0);
405 TCHAR* buf = new TCHAR[chars+1];
406
407 // Get the list of drives.
408 GetLogicalDriveStrings(chars, buf);
409
410 // Parse the list into an array, applying appropriate filters.
411 TCHAR *pVol;
412 pVol = buf;
413 while (*pVol)
414 {
415 FilteredAdd(list, pVol, flagsSet, flagsUnset);
416 pVol = pVol + wxStrlen(pVol) + 1;
417 }
418
419 // Cleanup.
420 delete[] buf;
421
422 //---------------------------
423 // Network Neighborhood next.
424 //---------------------------
425
426 // not exclude remote and not removable
427 if (!(flagsUnset & wxFS_VOL_REMOTE) &&
428 !(flagsSet & wxFS_VOL_REMOVABLE)
429 )
430 {
431 // The returned list will be sorted alphabetically. We don't pass
432 // our in since we don't want to change to order of the local drives.
433 wxArrayString nn;
434 if (BuildRemoteList(nn, 0, flagsSet, flagsUnset))
435 {
436 for (size_t idx = 0; idx < nn.GetCount(); idx++)
437 list.Add(nn[idx]);
438 }
439 }
440
441 return list;
442} // GetVolumes
443
444//=============================================================================
445// Function: CancelSearch
446// Purpose: Instruct an active search to stop.
447// Notes: - This will only sensibly be called by a thread other than the one
448// performing the search. This is the only thread-safe function
449// provided by the class.
450//=============================================================================
451void wxFSVolumeBase::CancelSearch()
452{
453 ::InterlockedExchange(&s_cancelSearch, TRUE);
454} // CancelSearch
455
456//=============================================================================
457// Function: constructor
458// Purpose: default constructor
459//=============================================================================
460wxFSVolumeBase::wxFSVolumeBase()
461{
462 m_isOk = false;
463} // wxVolume
464
465//=============================================================================
466// Function: constructor
467// Purpose: constructor that calls Create
468//=============================================================================
469wxFSVolumeBase::wxFSVolumeBase(const wxString& name)
470{
471 Create(name);
472} // wxVolume
473
474//=============================================================================
475// Function: Create
476// Purpose: Finds, logs in, etc. to the request volume.
477//=============================================================================
478bool wxFSVolumeBase::Create(const wxString& name)
479{
480 // assume fail.
481 m_isOk = false;
482
483 // supplied.
484 m_volName = name;
485
486 // Display name.
487 SHFILEINFO fi;
488 long rc = SHGetFileInfo(m_volName, 0, &fi, sizeof(fi), SHGFI_DISPLAYNAME);
489 if (!rc)
490 {
491 wxLogError(_("Cannot read typename from '%s'!"), m_volName.c_str());
492 return m_isOk;
493 }
494 m_dispName = fi.szDisplayName;
495
496 // all tests passed.
497 return m_isOk = true;
498} // Create
499
500//=============================================================================
501// Function: IsOk
502// Purpose: returns true if the volume is legal.
503// Notes: For fixed disks, it must exist. For removable disks, it must also
504// be present. For Network Shares, it must also be logged in, etc.
505//=============================================================================
506bool wxFSVolumeBase::IsOk() const
507{
508 return m_isOk;
509} // IsOk
510
511//=============================================================================
512// Function: GetKind
513// Purpose: Return the type of the volume.
514//=============================================================================
515wxFSVolumeKind wxFSVolumeBase::GetKind() const
516{
517 if (!m_isOk)
518 return wxFS_VOL_OTHER;
519
520 FileInfoMap::iterator itr = s_fileInfo.find(m_volName);
521 if (itr == s_fileInfo.end())
522 return wxFS_VOL_OTHER;
523
524 return itr->second.m_type;
525}
526
527//=============================================================================
528// Function: GetFlags
529// Purpose: Return the caches flags for this volume.
530// Notes: - Returns -1 if no flags were cached.
531//=============================================================================
532int wxFSVolumeBase::GetFlags() const
533{
534 if (!m_isOk)
535 return -1;
536
537 FileInfoMap::iterator itr = s_fileInfo.find(m_volName);
538 if (itr == s_fileInfo.end())
539 return -1;
540
541 return itr->second.m_flags;
542} // GetFlags
543
544#endif // wxUSE_BASE
545
546// ============================================================================
547// wxFSVolume
548// ============================================================================
549
550#if wxUSE_GUI
551
552void wxFSVolume::InitIcons()
553{
554 m_icons.Alloc(wxFS_VOL_ICO_MAX);
555 wxIcon null;
556 for (int idx = 0; idx < wxFS_VOL_ICO_MAX; idx++)
557 m_icons.Add(null);
558}
559
560//=============================================================================
561// Function: GetIcon
562// Purpose: return the requested icon.
563//=============================================================================
564
565wxIcon wxFSVolume::GetIcon(wxFSIconType type) const
566{
567 wxCHECK_MSG( type >= 0 && (size_t)type < m_icons.GetCount(), wxNullIcon,
568 _T("wxFSIconType::GetIcon(): invalid icon index") );
569
570 // Load on demand.
571 if (m_icons[type].IsNull())
572 {
573 UINT flags = SHGFI_ICON;
574 switch (type)
575 {
576 case wxFS_VOL_ICO_SMALL:
577 flags |= SHGFI_SMALLICON;
578 break;
579
580 case wxFS_VOL_ICO_LARGE:
581 flags |= SHGFI_SHELLICONSIZE;
582 break;
583
584 case wxFS_VOL_ICO_SEL_SMALL:
585 flags |= SHGFI_SMALLICON | SHGFI_OPENICON;
586 break;
587
588 case wxFS_VOL_ICO_SEL_LARGE:
589 flags |= SHGFI_SHELLICONSIZE | SHGFI_OPENICON;
590 break;
591
592 case wxFS_VOL_ICO_MAX:
593 wxFAIL_MSG(_T("wxFS_VOL_ICO_MAX is not valid icon type"));
594 break;
595 }
596
597 SHFILEINFO fi;
598 long rc = SHGetFileInfo(m_volName, 0, &fi, sizeof(fi), flags);
599 m_icons[type].SetHICON((WXHICON)fi.hIcon);
600 if (!rc || !fi.hIcon)
601 wxLogError(_("Cannot load icon from '%s'."), m_volName.c_str());
602 }
603
604 return m_icons[type];
605} // GetIcon
606
607#endif // wxUSE_GUI
608
609#endif // wxUSE_FSVOLUME
610