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