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