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