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