]> git.saurik.com Git - wxWidgets.git/blame - src/msw/volume.cpp
Do not allow events to fire after socket is closed (fixes crash on GTK with GDK_Input...
[wxWidgets.git] / src / msw / volume.cpp
CommitLineData
7183fd72
VZ
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
65571936 9// Licence: wxWindows licence
7183fd72
VZ
10///////////////////////////////////////////////////////////////////////////////
11
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
7183fd72
VZ
20#include "wx/wxprec.h"
21
22#ifdef __BORLANDC__
23 #pragma hdrstop
24#endif
25
05815ab3
VZ
26#if wxUSE_FSVOLUME
27
7183fd72 28#ifndef WX_PRECOMP
df5168c4
MB
29 #if wxUSE_GUI
30 #include "wx/icon.h"
31 #endif
05815ab3 32 #include "wx/intl.h"
7183fd72
VZ
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
eaeeb91e 42#include <shellapi.h>
a6c7a0f8 43#include <shlobj.h>
e2478fde 44#include "wx/msw/missing.h"
eaeeb91e 45
ec67cff1 46#if wxUSE_BASE
7cfdeaad 47
7183fd72
VZ
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
17ebae65 67struct FileInfo
7183fd72
VZ
68{
69 FileInfo(unsigned flag=0, wxFSVolumeKind type=wxFS_VOL_OTHER) :
70 m_flags(flag), m_type(type) {}
51fdd3da
VZ
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
7183fd72
VZ
80 unsigned m_flags;
81 wxFSVolumeKind m_type;
82};
83WX_DECLARE_STRING_HASH_MAP(FileInfo, FileInfoMap);
17ebae65
MB
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())
7183fd72 92
7183fd72
VZ
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//=============================================================================
4d90b8de 106static unsigned GetBasicFlags(const wxChar* filename)
7183fd72
VZ
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 will 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//=============================================================================
27d2dbbc 179static bool FilteredAdd(wxArrayString& list, const wxChar* filename,
4d90b8de 180 unsigned flagsSet, unsigned flagsUnset)
7183fd72 181{
27d2dbbc 182 bool accept = true;
7183fd72
VZ
183 unsigned flags = GetBasicFlags(filename);
184
185 if (flagsSet & wxFS_VOL_MOUNTED && !(flags & wxFS_VOL_MOUNTED))
27d2dbbc 186 accept = false;
7183fd72 187 else if (flagsUnset & wxFS_VOL_MOUNTED && (flags & wxFS_VOL_MOUNTED))
27d2dbbc 188 accept = false;
7183fd72 189 else if (flagsSet & wxFS_VOL_REMOVABLE && !(flags & wxFS_VOL_REMOVABLE))
27d2dbbc 190 accept = false;
7183fd72 191 else if (flagsUnset & wxFS_VOL_REMOVABLE && (flags & wxFS_VOL_REMOVABLE))
27d2dbbc 192 accept = false;
7183fd72 193 else if (flagsSet & wxFS_VOL_READONLY && !(flags & wxFS_VOL_READONLY))
27d2dbbc 194 accept = false;
7183fd72 195 else if (flagsUnset & wxFS_VOL_READONLY && (flags & wxFS_VOL_READONLY))
27d2dbbc 196 accept = false;
7183fd72 197 else if (flagsSet & wxFS_VOL_REMOTE && !(flags & wxFS_VOL_REMOTE))
27d2dbbc 198 accept = false;
7183fd72 199 else if (flagsUnset & wxFS_VOL_REMOTE && (flags & wxFS_VOL_REMOTE))
27d2dbbc 200 accept = false;
7183fd72
VZ
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//=============================================================================
27d2dbbc 216static void BuildListFromNN(wxArrayString& list, NETRESOURCE* pResSrc,
4d90b8de 217 unsigned flagsSet, unsigned flagsUnset)
7183fd72
VZ
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 {
4aebbc59
MB
236 DWORD count = 1;
237 DWORD size = 256;
7183fd72
VZ
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//=============================================================================
99f161bd 289static int CompareFcn(const wxString& first, const wxString& second)
7183fd72 290{
99f161bd 291 return wxStricmp(first.c_str(), second.c_str());
7183fd72
VZ
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//=============================================================================
27d2dbbc 302static bool BuildRemoteList(wxArrayString& list, NETRESOURCE* pResSrc,
4d90b8de 303 unsigned flagsSet, unsigned flagsUnset)
7183fd72
VZ
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."));
27d2dbbc 309 return false;
7183fd72
VZ
310 }
311
312 // Don't waste time doing the work if the flags conflict.
313 if (flagsSet & wxFS_VOL_MOUNTED && flagsUnset & wxFS_VOL_MOUNTED)
27d2dbbc 314 return false;
7183fd72
VZ
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.
4a559093
WS
335 ssize_t iList = list.GetCount()-1;
336 for (ssize_t iMounted = mounted.GetCount()-1; iMounted >= 0 && iList >= 0; iMounted--)
7183fd72
VZ
337 {
338 int compare;
339 wxString all(list[iList]);
340 wxString mount(mounted[iMounted]);
341
27d2dbbc 342 while (compare =
4d90b8de
VS
343 wxStricmp(list[iList].c_str(), mounted[iMounted].c_str()),
344 compare > 0 && iList >= 0)
7183fd72
VZ
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)
ba8c1601 355 list.RemoveAt(iList);
7183fd72
VZ
356 else
357 s_fileInfo[list[iList]].m_flags |= wxFS_VOL_MOUNTED;
358
359 }
360
361 iList--;
362 }
363 }
364
27d2dbbc 365 return true;
7183fd72
VZ
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//=============================================================================
e2478fde 377wxArrayString wxFSVolumeBase::GetVolumes(int flagsSet, int flagsUnset)
7183fd72 378{
27d2dbbc 379 ::InterlockedExchange(&s_cancelSearch, FALSE); // reset
7183fd72
VZ
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"));
2b5f62a0 385 s_pWNetEnumResource = (WNetEnumResourcePtr)s_mprLib.GetSymbol(_T("WNetEnumResourceW"));
7183fd72
VZ
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.
95dc6a2b 399 const DWORD chars = GetLogicalDriveStrings(0, NULL);
7183fd72
VZ
400 TCHAR* buf = new TCHAR[chars+1];
401
402 // Get the list of drives.
999836aa 403 GetLogicalDriveStrings(chars, buf);
7183fd72
VZ
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);
67fade33 411 pVol = pVol + wxStrlen(pVol) + 1;
7183fd72
VZ
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 {
89c98653 431 for (size_t idx = 0; idx < nn.GetCount(); idx++)
7183fd72
VZ
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//=============================================================================
e2478fde 446void wxFSVolumeBase::CancelSearch()
7183fd72 447{
27d2dbbc 448 ::InterlockedExchange(&s_cancelSearch, TRUE);
7183fd72
VZ
449} // CancelSearch
450
451//=============================================================================
452// Function: constructor
453// Purpose: default constructor
454//=============================================================================
e2478fde 455wxFSVolumeBase::wxFSVolumeBase()
7183fd72 456{
27d2dbbc 457 m_isOk = false;
7183fd72
VZ
458} // wxVolume
459
460//=============================================================================
461// Function: constructor
462// Purpose: constructor that calls Create
463//=============================================================================
e2478fde 464wxFSVolumeBase::wxFSVolumeBase(const wxString& name)
7183fd72
VZ
465{
466 Create(name);
467} // wxVolume
468
469//=============================================================================
470// Function: Create
471// Purpose: Finds, logs in, etc. to the request volume.
472//=============================================================================
e2478fde 473bool wxFSVolumeBase::Create(const wxString& name)
7183fd72
VZ
474{
475 // assume fail.
27d2dbbc 476 m_isOk = false;
7183fd72
VZ
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 {
4d90b8de 486 wxLogError(_("Cannot read typename from '%s'!"), m_volName.c_str());
7183fd72
VZ
487 return m_isOk;
488 }
489 m_dispName = fi.szDisplayName;
490
7183fd72 491 // all tests passed.
27d2dbbc 492 return m_isOk = true;
7183fd72
VZ
493} // Create
494
495//=============================================================================
496// Function: IsOk
27d2dbbc 497// Purpose: returns true if the volume is legal.
7183fd72
VZ
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//=============================================================================
e2478fde 501bool wxFSVolumeBase::IsOk() const
7183fd72
VZ
502{
503 return m_isOk;
504} // IsOk
505
506//=============================================================================
507// Function: GetKind
508// Purpose: Return the type of the volume.
509//=============================================================================
e2478fde 510wxFSVolumeKind wxFSVolumeBase::GetKind() const
7183fd72
VZ
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//=============================================================================
e2478fde 527int wxFSVolumeBase::GetFlags() const
7183fd72
VZ
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
ec67cff1 539#endif // wxUSE_BASE
e2478fde
VZ
540
541// ============================================================================
542// wxFSVolume
543// ============================================================================
544
0e7fa3a6 545#if wxUSE_GUI
7183fd72 546
e2478fde
VZ
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
7183fd72
VZ
555//=============================================================================
556// Function: GetIcon
557// Purpose: return the requested icon.
558//=============================================================================
e2478fde 559
7183fd72
VZ
560wxIcon wxFSVolume::GetIcon(wxFSIconType type) const
561{
e2478fde
VZ
562 wxCHECK_MSG( type >= 0 && (size_t)type < m_icons.GetCount(), wxNullIcon,
563 _T("wxFSIconType::GetIcon(): invalid icon index") );
7183fd72
VZ
564
565 // Load on demand.
566 if (m_icons[type].IsNull())
567 {
e2478fde 568 UINT flags = SHGFI_ICON;
7183fd72
VZ
569 switch (type)
570 {
571 case wxFS_VOL_ICO_SMALL:
e2478fde 572 flags |= SHGFI_SMALLICON;
7183fd72
VZ
573 break;
574
575 case wxFS_VOL_ICO_LARGE:
e2478fde 576 flags |= SHGFI_SHELLICONSIZE;
7183fd72
VZ
577 break;
578
579 case wxFS_VOL_ICO_SEL_SMALL:
e2478fde 580 flags |= SHGFI_SMALLICON | SHGFI_OPENICON;
7183fd72
VZ
581 break;
582
583 case wxFS_VOL_ICO_SEL_LARGE:
e2478fde 584 flags |= SHGFI_SHELLICONSIZE | SHGFI_OPENICON;
7183fd72 585 break;
27d2dbbc 586
4d90b8de
VS
587 case wxFS_VOL_ICO_MAX:
588 wxFAIL_MSG(_T("wxFS_VOL_ICO_MAX is not valid icon type"));
589 break;
7183fd72
VZ
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)
4d90b8de 596 wxLogError(_("Cannot load icon from '%s'."), m_volName.c_str());
7183fd72
VZ
597 }
598
599 return m_icons[type];
600} // GetIcon
601
602#endif // wxUSE_GUI
603
05815ab3 604#endif // wxUSE_FSVOLUME