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