]> git.saurik.com Git - wxWidgets.git/blob - src/msw/volume.cpp
test for remote drive existence using wxDirExists() first if it's mapped locally...
[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 #include "wx/wxprec.h"
21
22 #ifdef __BORLANDC__
23 #pragma hdrstop
24 #endif
25
26 #if wxUSE_FSVOLUME
27
28 #include "wx/volume.h"
29
30 #ifndef WX_PRECOMP
31 #if wxUSE_GUI
32 #include "wx/icon.h"
33 #endif
34 #include "wx/intl.h"
35 #include "wx/hashmap.h"
36 #endif // WX_PRECOMP
37
38 #include "wx/dir.h"
39 #include "wx/dynlib.h"
40 #include "wx/arrimpl.cpp"
41
42 #include <shellapi.h>
43 #include <shlobj.h>
44 #include "wx/msw/missing.h"
45
46 #if wxUSE_BASE
47
48 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
49 // Dynamic library function defs.
50 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
51
52 #if wxUSE_DYNLIB_CLASS
53 static wxDynamicLibrary s_mprLib;
54 #endif
55
56 typedef DWORD (WINAPI* WNetOpenEnumPtr)(DWORD, DWORD, DWORD, LPNETRESOURCE, LPHANDLE);
57 typedef DWORD (WINAPI* WNetEnumResourcePtr)(HANDLE, LPDWORD, LPVOID, LPDWORD);
58 typedef DWORD (WINAPI* WNetCloseEnumPtr)(HANDLE);
59
60 static WNetOpenEnumPtr s_pWNetOpenEnum;
61 static WNetEnumResourcePtr s_pWNetEnumResource;
62 static WNetCloseEnumPtr s_pWNetCloseEnum;
63
64 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
65 // Globals/Statics
66 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
67 static long s_cancelSearch = FALSE;
68
69 struct FileInfo
70 {
71 FileInfo(unsigned flag=0, wxFSVolumeKind type=wxFS_VOL_OTHER) :
72 m_flags(flag), m_type(type) {}
73
74 FileInfo(const FileInfo& other) { *this = other; }
75 FileInfo& operator=(const FileInfo& other)
76 {
77 m_flags = other.m_flags;
78 m_type = other.m_type;
79 return *this;
80 }
81
82 unsigned m_flags;
83 wxFSVolumeKind m_type;
84 };
85 WX_DECLARE_STRING_HASH_MAP(FileInfo, FileInfoMap);
86 // Cygwin bug (?) destructor for global s_fileInfo is called twice...
87 static FileInfoMap& GetFileInfoMap()
88 {
89 static FileInfoMap s_fileInfo(25);
90
91 return s_fileInfo;
92 }
93 #define s_fileInfo (GetFileInfoMap())
94
95 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
96 // Local helper functions.
97 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
98
99 //=============================================================================
100 // Function: GetBasicFlags
101 // Purpose: Set basic flags, primarily wxFS_VOL_REMOTE and wxFS_VOL_REMOVABLE.
102 // Notes: - Local and mapped drives are mounted by definition. We have no
103 // way to determine mounted status of network drives, so assume that
104 // all drives are mounted, and let the caller decide otherwise.
105 // - Other flags are 'best guess' from type of drive. The system will
106 // not report the file attributes with any degree of accuracy.
107 //=============================================================================
108 static unsigned GetBasicFlags(const wxChar* filename)
109 {
110 unsigned flags = wxFS_VOL_MOUNTED;
111
112 //----------------------------------
113 // 'Best Guess' based on drive type.
114 //----------------------------------
115 wxFSVolumeKind type;
116 switch(GetDriveType(filename))
117 {
118 case DRIVE_FIXED:
119 type = wxFS_VOL_DISK;
120 break;
121
122 case DRIVE_REMOVABLE:
123 flags |= wxFS_VOL_REMOVABLE;
124 type = wxFS_VOL_FLOPPY;
125 break;
126
127 case DRIVE_CDROM:
128 flags |= wxFS_VOL_REMOVABLE | wxFS_VOL_READONLY;
129 type = wxFS_VOL_CDROM;
130 break;
131
132 case DRIVE_REMOTE:
133 flags |= wxFS_VOL_REMOTE;
134 type = wxFS_VOL_NETWORK;
135 break;
136
137 case DRIVE_NO_ROOT_DIR:
138 flags &= ~wxFS_VOL_MOUNTED;
139 type = wxFS_VOL_OTHER;
140 break;
141
142 default:
143 type = wxFS_VOL_OTHER;
144 break;
145 }
146
147 //-----------------------------------------------------------------------
148 // The following most likely will not modify anything not set above,
149 // and will not work at all for network shares or empty CD ROM drives.
150 // But it is a good check if the Win API ever gets better about reporting
151 // this information.
152 //-----------------------------------------------------------------------
153 SHFILEINFO fi;
154 long rc = SHGetFileInfo(filename, 0, &fi, sizeof(fi), SHGFI_ATTRIBUTES);
155 if (!rc)
156 {
157 // this error is not fatal, so don't show a message to the user about
158 // it, otherwise it would appear every time a generic directory picker
159 // dialog is used and there is a connected network drive
160 wxLogLastError(_T("SHGetFileInfo"));
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 //=============================================================================
183 static 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 //=============================================================================
220 static 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 the drive is unavailable, FilteredAdd() can hang for
268 // a long time and, moreover, its failure appears to be not
269 // cached so this will happen every time we use it, so try
270 // a much quicker wxDirExists() test (which still hangs but
271 // for much shorter time) for locally mapped drives first
272 // to try to avoid this
273 if ( pRes->lpLocalName &&
274 *pRes->lpLocalName &&
275 !wxDirExists(pRes->lpLocalName) )
276 continue;
277
278 if (!filename.empty())
279 {
280 if (filename.Last() != '\\')
281 filename.Append('\\');
282
283 // The filter function will not know mounted from unmounted, and neither do we unless
284 // we are iterating using RESOURCE_CONNECTED, in which case they all are mounted.
285 // Volumes on disconnected servers, however, will correctly show as unmounted.
286 FilteredAdd(list, filename.wx_str(), flagsSet, flagsUnset&~wxFS_VOL_MOUNTED);
287 if (scope == RESOURCE_GLOBALNET)
288 s_fileInfo[filename].m_flags &= ~wxFS_VOL_MOUNTED;
289 }
290 }
291 }
292 else if (count == 0)
293 break;
294 }
295 free(pRes);
296 s_pWNetCloseEnum(hEnum);
297 }
298 } // BuildListFromNN
299
300 //=============================================================================
301 // Function: CompareFcn
302 // Purpose: Used to sort the NN list alphabetically, case insensitive.
303 //=============================================================================
304 static int CompareFcn(const wxString& first, const wxString& second)
305 {
306 return wxStricmp(first.c_str(), second.c_str());
307 } // CompareFcn
308
309 //=============================================================================
310 // Function: BuildRemoteList
311 // Purpose: Append Network Neighborhood items to the list.
312 // Notes: - Mounted gets transalated into Connected. FilteredAdd is told
313 // to ignore the Mounted flag since we need to handle it in a weird
314 // way manually.
315 // - The resulting list is sorted alphabetically.
316 //=============================================================================
317 static bool BuildRemoteList(wxArrayString& list, NETRESOURCE* pResSrc,
318 unsigned flagsSet, unsigned flagsUnset)
319 {
320 // NN query depends on dynamically loaded library.
321 if (!s_pWNetOpenEnum || !s_pWNetEnumResource || !s_pWNetCloseEnum)
322 {
323 wxLogError(_("Failed to load mpr.dll."));
324 return false;
325 }
326
327 // Don't waste time doing the work if the flags conflict.
328 if (flagsSet & wxFS_VOL_MOUNTED && flagsUnset & wxFS_VOL_MOUNTED)
329 return false;
330
331 //----------------------------------------------
332 // Generate the list according to the flags set.
333 //----------------------------------------------
334 BuildListFromNN(list, pResSrc, flagsSet, flagsUnset);
335 list.Sort(CompareFcn);
336
337 //-------------------------------------------------------------------------
338 // If mounted only is requested, then we only need one simple pass.
339 // Otherwise, we need to build a list of all NN volumes and then apply the
340 // list of mounted drives to it.
341 //-------------------------------------------------------------------------
342 if (!(flagsSet & wxFS_VOL_MOUNTED))
343 {
344 // generate.
345 wxArrayString mounted;
346 BuildListFromNN(mounted, pResSrc, flagsSet | wxFS_VOL_MOUNTED, flagsUnset & ~wxFS_VOL_MOUNTED);
347 mounted.Sort(CompareFcn);
348
349 // apply list from bottom to top to preserve indexes if removing items.
350 ssize_t iList = list.GetCount()-1;
351 for (ssize_t iMounted = mounted.GetCount()-1; iMounted >= 0 && iList >= 0; iMounted--)
352 {
353 int compare;
354 wxString all(list[iList]);
355 wxString mount(mounted[iMounted]);
356
357 while (compare =
358 wxStricmp(list[iList].c_str(), mounted[iMounted].c_str()),
359 compare > 0 && iList >= 0)
360 {
361 iList--;
362 all = list[iList];
363 }
364
365
366 if (compare == 0)
367 {
368 // Found the element. Remove it or mark it mounted.
369 if (flagsUnset & wxFS_VOL_MOUNTED)
370 list.RemoveAt(iList);
371 else
372 s_fileInfo[list[iList]].m_flags |= wxFS_VOL_MOUNTED;
373
374 }
375
376 iList--;
377 }
378 }
379
380 return true;
381 } // BuildRemoteList
382
383 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
384 // wxFSVolume
385 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
386
387 //=============================================================================
388 // Function: GetVolumes
389 // Purpose: Generate and return a list of all volumes (drives) available.
390 // Notes:
391 //=============================================================================
392 wxArrayString wxFSVolumeBase::GetVolumes(int flagsSet, int flagsUnset)
393 {
394 ::InterlockedExchange(&s_cancelSearch, FALSE); // reset
395
396 #if wxUSE_DYNLIB_CLASS
397 if (!s_mprLib.IsLoaded() && s_mprLib.Load(_T("mpr.dll")))
398 {
399 #ifdef UNICODE
400 s_pWNetOpenEnum = (WNetOpenEnumPtr)s_mprLib.GetSymbol(_T("WNetOpenEnumW"));
401 s_pWNetEnumResource = (WNetEnumResourcePtr)s_mprLib.GetSymbol(_T("WNetEnumResourceW"));
402 #else
403 s_pWNetOpenEnum = (WNetOpenEnumPtr)s_mprLib.GetSymbol(_T("WNetOpenEnumA"));
404 s_pWNetEnumResource = (WNetEnumResourcePtr)s_mprLib.GetSymbol(_T("WNetEnumResourceA"));
405 #endif
406 s_pWNetCloseEnum = (WNetCloseEnumPtr)s_mprLib.GetSymbol(_T("WNetCloseEnum"));
407 }
408 #endif
409
410 wxArrayString list;
411
412 //-------------------------------
413 // Local and mapped drives first.
414 //-------------------------------
415 // Allocate the required space for the API call.
416 const DWORD chars = GetLogicalDriveStrings(0, NULL);
417 TCHAR* buf = new TCHAR[chars+1];
418
419 // Get the list of drives.
420 GetLogicalDriveStrings(chars, buf);
421
422 // Parse the list into an array, applying appropriate filters.
423 TCHAR *pVol;
424 pVol = buf;
425 while (*pVol)
426 {
427 FilteredAdd(list, pVol, flagsSet, flagsUnset);
428 pVol = pVol + wxStrlen(pVol) + 1;
429 }
430
431 // Cleanup.
432 delete[] buf;
433
434 //---------------------------
435 // Network Neighborhood next.
436 //---------------------------
437
438 // not exclude remote and not removable
439 if (!(flagsUnset & wxFS_VOL_REMOTE) &&
440 !(flagsSet & wxFS_VOL_REMOVABLE)
441 )
442 {
443 // The returned list will be sorted alphabetically. We don't pass
444 // our in since we don't want to change to order of the local drives.
445 wxArrayString nn;
446 if (BuildRemoteList(nn, 0, flagsSet, flagsUnset))
447 {
448 for (size_t idx = 0; idx < nn.GetCount(); idx++)
449 list.Add(nn[idx]);
450 }
451 }
452
453 return list;
454 } // GetVolumes
455
456 //=============================================================================
457 // Function: CancelSearch
458 // Purpose: Instruct an active search to stop.
459 // Notes: - This will only sensibly be called by a thread other than the one
460 // performing the search. This is the only thread-safe function
461 // provided by the class.
462 //=============================================================================
463 void wxFSVolumeBase::CancelSearch()
464 {
465 ::InterlockedExchange(&s_cancelSearch, TRUE);
466 } // CancelSearch
467
468 //=============================================================================
469 // Function: constructor
470 // Purpose: default constructor
471 //=============================================================================
472 wxFSVolumeBase::wxFSVolumeBase()
473 {
474 m_isOk = false;
475 } // wxVolume
476
477 //=============================================================================
478 // Function: constructor
479 // Purpose: constructor that calls Create
480 //=============================================================================
481 wxFSVolumeBase::wxFSVolumeBase(const wxString& name)
482 {
483 Create(name);
484 } // wxVolume
485
486 //=============================================================================
487 // Function: Create
488 // Purpose: Finds, logs in, etc. to the request volume.
489 //=============================================================================
490 bool wxFSVolumeBase::Create(const wxString& name)
491 {
492 // assume fail.
493 m_isOk = false;
494
495 // supplied.
496 m_volName = name;
497
498 // Display name.
499 SHFILEINFO fi;
500 long rc = SHGetFileInfo(m_volName.wx_str(), 0, &fi, sizeof(fi), SHGFI_DISPLAYNAME);
501 if (!rc)
502 {
503 wxLogError(_("Cannot read typename from '%s'!"), m_volName.c_str());
504 return m_isOk;
505 }
506 m_dispName = fi.szDisplayName;
507
508 // all tests passed.
509 return m_isOk = true;
510 } // Create
511
512 //=============================================================================
513 // Function: IsOk
514 // Purpose: returns true if the volume is legal.
515 // Notes: For fixed disks, it must exist. For removable disks, it must also
516 // be present. For Network Shares, it must also be logged in, etc.
517 //=============================================================================
518 bool wxFSVolumeBase::IsOk() const
519 {
520 return m_isOk;
521 } // IsOk
522
523 //=============================================================================
524 // Function: GetKind
525 // Purpose: Return the type of the volume.
526 //=============================================================================
527 wxFSVolumeKind wxFSVolumeBase::GetKind() const
528 {
529 if (!m_isOk)
530 return wxFS_VOL_OTHER;
531
532 FileInfoMap::iterator itr = s_fileInfo.find(m_volName);
533 if (itr == s_fileInfo.end())
534 return wxFS_VOL_OTHER;
535
536 return itr->second.m_type;
537 }
538
539 //=============================================================================
540 // Function: GetFlags
541 // Purpose: Return the caches flags for this volume.
542 // Notes: - Returns -1 if no flags were cached.
543 //=============================================================================
544 int wxFSVolumeBase::GetFlags() const
545 {
546 if (!m_isOk)
547 return -1;
548
549 FileInfoMap::iterator itr = s_fileInfo.find(m_volName);
550 if (itr == s_fileInfo.end())
551 return -1;
552
553 return itr->second.m_flags;
554 } // GetFlags
555
556 #endif // wxUSE_BASE
557
558 // ============================================================================
559 // wxFSVolume
560 // ============================================================================
561
562 #if wxUSE_GUI
563
564 void wxFSVolume::InitIcons()
565 {
566 m_icons.Alloc(wxFS_VOL_ICO_MAX);
567 wxIcon null;
568 for (int idx = 0; idx < wxFS_VOL_ICO_MAX; idx++)
569 m_icons.Add(null);
570 }
571
572 //=============================================================================
573 // Function: GetIcon
574 // Purpose: return the requested icon.
575 //=============================================================================
576
577 wxIcon wxFSVolume::GetIcon(wxFSIconType type) const
578 {
579 wxCHECK_MSG( type >= 0 && (size_t)type < m_icons.GetCount(), wxNullIcon,
580 _T("wxFSIconType::GetIcon(): invalid icon index") );
581
582 // Load on demand.
583 if (m_icons[type].IsNull())
584 {
585 UINT flags = SHGFI_ICON;
586 switch (type)
587 {
588 case wxFS_VOL_ICO_SMALL:
589 flags |= SHGFI_SMALLICON;
590 break;
591
592 case wxFS_VOL_ICO_LARGE:
593 flags |= SHGFI_SHELLICONSIZE;
594 break;
595
596 case wxFS_VOL_ICO_SEL_SMALL:
597 flags |= SHGFI_SMALLICON | SHGFI_OPENICON;
598 break;
599
600 case wxFS_VOL_ICO_SEL_LARGE:
601 flags |= SHGFI_SHELLICONSIZE | SHGFI_OPENICON;
602 break;
603
604 case wxFS_VOL_ICO_MAX:
605 wxFAIL_MSG(_T("wxFS_VOL_ICO_MAX is not valid icon type"));
606 break;
607 }
608
609 SHFILEINFO fi;
610 long rc = SHGetFileInfo(m_volName.wx_str(), 0, &fi, sizeof(fi), flags);
611 m_icons[type].SetHICON((WXHICON)fi.hIcon);
612 if (!rc || !fi.hIcon)
613 wxLogError(_("Cannot load icon from '%s'."), m_volName.c_str());
614 }
615
616 return m_icons[type];
617 } // GetIcon
618
619 #endif // wxUSE_GUI
620
621 #endif // wxUSE_FSVOLUME