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