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