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