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