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