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