]> git.saurik.com Git - wxWidgets.git/blob - src/msw/volume.cpp
Fixed OS/2 compilation problems.
[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 unsigned GetBasicFlags(const char* 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 bool FilteredAdd(wxArrayString& list, const char* filename, unsigned flagsSet, unsigned flagsUnset)
166 {
167 bool accept = TRUE;
168 unsigned flags = GetBasicFlags(filename);
169
170 if (flagsSet & wxFS_VOL_MOUNTED && !(flags & wxFS_VOL_MOUNTED))
171 accept = FALSE;
172 else if (flagsUnset & wxFS_VOL_MOUNTED && (flags & wxFS_VOL_MOUNTED))
173 accept = FALSE;
174 else if (flagsSet & wxFS_VOL_REMOVABLE && !(flags & wxFS_VOL_REMOVABLE))
175 accept = FALSE;
176 else if (flagsUnset & wxFS_VOL_REMOVABLE && (flags & wxFS_VOL_REMOVABLE))
177 accept = FALSE;
178 else if (flagsSet & wxFS_VOL_READONLY && !(flags & wxFS_VOL_READONLY))
179 accept = FALSE;
180 else if (flagsUnset & wxFS_VOL_READONLY && (flags & wxFS_VOL_READONLY))
181 accept = FALSE;
182 else if (flagsSet & wxFS_VOL_REMOTE && !(flags & wxFS_VOL_REMOTE))
183 accept = FALSE;
184 else if (flagsUnset & wxFS_VOL_REMOTE && (flags & wxFS_VOL_REMOTE))
185 accept = FALSE;
186
187 // Add to the list if passed the filter.
188 if (accept)
189 list.Add(filename);
190
191 return accept;
192 } // FilteredAdd
193
194 //=============================================================================
195 // Function: BuildListFromNN
196 // Purpose: Append or remove items from the list
197 // Notes: - There is no way to find all disconnected NN items, or even to find
198 // all items while determining which are connected and not. So this
199 // function will find either all items or connected items.
200 //=============================================================================
201 void BuildListFromNN(wxArrayString& list, NETRESOURCE* pResSrc, unsigned flagsSet, unsigned flagsUnset)
202 {
203 HANDLE hEnum;
204 int rc;
205
206 //-----------------------------------------------
207 // Scope may be all drives or all mounted drives.
208 //-----------------------------------------------
209 unsigned scope = RESOURCE_GLOBALNET;
210 if (flagsSet & wxFS_VOL_MOUNTED)
211 scope = RESOURCE_CONNECTED;
212
213 //----------------------------------------------------------------------
214 // Enumerate all items, adding only non-containers (ie. network shares).
215 // Containers cause a recursive call to this function for their own
216 // enumeration.
217 //----------------------------------------------------------------------
218 if (rc = s_pWNetOpenEnum(scope, RESOURCETYPE_DISK, 0, pResSrc, &hEnum), rc == NO_ERROR)
219 {
220 unsigned long count = 1;
221 unsigned long size = 256;
222 NETRESOURCE* pRes = (NETRESOURCE*)malloc(size);
223 memset(pRes, 0, sizeof(NETRESOURCE));
224 while (rc = s_pWNetEnumResource(hEnum, &count, pRes, &size), rc == NO_ERROR || rc == ERROR_MORE_DATA)
225 {
226 if (s_cancelSearch)
227 break;
228
229 if (rc == ERROR_MORE_DATA)
230 {
231 pRes = (NETRESOURCE*)realloc(pRes, size);
232 count = 1;
233 }
234 else if (count == 1)
235 {
236 // Enumerate the container.
237 if (pRes->dwUsage & RESOURCEUSAGE_CONTAINER)
238 {
239 BuildListFromNN(list, pRes, flagsSet, flagsUnset);
240 }
241
242 // Add the network share.
243 else
244 {
245 wxString filename(pRes->lpRemoteName);
246
247 if (filename.Len())
248 {
249 if (filename.Last() != '\\')
250 filename.Append('\\');
251
252 // The filter function will not know mounted from unmounted, and neither do we unless
253 // we are iterating using RESOURCE_CONNECTED, in which case they all are mounted.
254 // Volumes on disconnected servers, however, will correctly show as unmounted.
255 FilteredAdd(list, filename, flagsSet, flagsUnset&~wxFS_VOL_MOUNTED);
256 if (scope == RESOURCE_GLOBALNET)
257 s_fileInfo[filename].m_flags &= ~wxFS_VOL_MOUNTED;
258 }
259 }
260 }
261 else if (count == 0)
262 break;
263 }
264 free(pRes);
265 s_pWNetCloseEnum(hEnum);
266 }
267 } // BuildListFromNN
268
269 //=============================================================================
270 // Function: CompareFcn
271 // Purpose: Used to sort the NN list alphabetically, case insensitive.
272 //=============================================================================
273 static int CompareFcn(const wxString& first, const wxString& second)
274 {
275 return stricmp(first.c_str(), second.c_str());
276 } // CompareFcn
277
278 //=============================================================================
279 // Function: BuildRemoteList
280 // Purpose: Append Network Neighborhood items to the list.
281 // Notes: - Mounted gets transalated into Connected. FilteredAdd is told
282 // to ignore the Mounted flag since we need to handle it in a weird
283 // way manually.
284 // - The resulting list is sorted alphabetically.
285 //=============================================================================
286 bool BuildRemoteList(wxArrayString& list, NETRESOURCE* pResSrc, unsigned flagsSet, unsigned flagsUnset)
287 {
288 // NN query depends on dynamically loaded library.
289 if (!s_pWNetOpenEnum || !s_pWNetEnumResource || !s_pWNetCloseEnum)
290 {
291 wxLogError(_("Failed to load mpr.dll."));
292 return FALSE;
293 }
294
295 // Don't waste time doing the work if the flags conflict.
296 if (flagsSet & wxFS_VOL_MOUNTED && flagsUnset & wxFS_VOL_MOUNTED)
297 return FALSE;
298
299 //----------------------------------------------
300 // Generate the list according to the flags set.
301 //----------------------------------------------
302 BuildListFromNN(list, pResSrc, flagsSet, flagsUnset);
303 list.Sort(CompareFcn);
304
305 //-------------------------------------------------------------------------
306 // If mounted only is requested, then we only need one simple pass.
307 // Otherwise, we need to build a list of all NN volumes and then apply the
308 // list of mounted drives to it.
309 //-------------------------------------------------------------------------
310 if (!(flagsSet & wxFS_VOL_MOUNTED))
311 {
312 // generate.
313 wxArrayString mounted;
314 BuildListFromNN(mounted, pResSrc, flagsSet | wxFS_VOL_MOUNTED, flagsUnset & ~wxFS_VOL_MOUNTED);
315 mounted.Sort(CompareFcn);
316
317 // apply list from bottom to top to preserve indexes if removing items.
318 int iList = list.GetCount()-1;
319 int iMounted;
320 for (iMounted = mounted.GetCount()-1; iMounted >= 0 && iList >= 0; iMounted--)
321 {
322 int compare;
323 wxString all(list[iList]);
324 wxString mount(mounted[iMounted]);
325
326 while (compare = stricmp(list[iList], mounted[iMounted]), compare > 0 && iList >= 0)
327 {
328 iList--;
329 all = list[iList];
330 }
331
332
333 if (compare == 0)
334 {
335 // Found the element. Remove it or mark it mounted.
336 if (flagsUnset & wxFS_VOL_MOUNTED)
337 list.Remove(iList);
338 else
339 s_fileInfo[list[iList]].m_flags |= wxFS_VOL_MOUNTED;
340
341 }
342
343 iList--;
344 }
345 }
346
347 return TRUE;
348 } // BuildRemoteList
349
350 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
351 // wxFSVolume
352 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
353
354 //=============================================================================
355 // Function: GetVolumes
356 // Purpose: Generate and return a list of all volumes (drives) available.
357 // Notes:
358 //=============================================================================
359 wxArrayString wxFSVolume::GetVolumes(int flagsSet, int flagsUnset)
360 {
361 InterlockedExchange(&s_cancelSearch, FALSE); // reset
362
363 if (!s_mprLib.IsLoaded() && s_mprLib.Load(_T("mpr.dll")))
364 {
365 #ifdef UNICODE
366 s_pWNetOpenEnum = (WNetOpenEnumPtr)s_mprLib.GetSymbol(_T("WNetOpenEnumW"));
367 s_pWNetEnumResource = (WNetEnumResourcePtr)s_mprLib.GetSymbol("WNetEnumResourceW");
368 #else
369 s_pWNetOpenEnum = (WNetOpenEnumPtr)s_mprLib.GetSymbol(_T("WNetOpenEnumA"));
370 s_pWNetEnumResource = (WNetEnumResourcePtr)s_mprLib.GetSymbol(_T("WNetEnumResourceA"));
371 #endif
372 s_pWNetCloseEnum = (WNetCloseEnumPtr)s_mprLib.GetSymbol(_T("WNetCloseEnum"));
373 }
374
375 wxArrayString list;
376
377 //-------------------------------
378 // Local and mapped drives first.
379 //-------------------------------
380 // Allocate the required space for the API call.
381 size_t chars = GetLogicalDriveStrings(0, 0);
382 TCHAR* buf = new TCHAR[chars+1];
383
384 // Get the list of drives.
385 chars = GetLogicalDriveStrings(chars, buf);
386
387 // Parse the list into an array, applying appropriate filters.
388 TCHAR *pVol;
389 pVol = buf;
390 while (*pVol)
391 {
392 FilteredAdd(list, pVol, flagsSet, flagsUnset);
393 pVol = pVol + wxStrlen(pVol) + 1;
394 }
395
396 // Cleanup.
397 delete[] buf;
398
399 //---------------------------
400 // Network Neighborhood next.
401 //---------------------------
402
403 // not exclude remote and not removable
404 if (!(flagsUnset & wxFS_VOL_REMOTE) &&
405 !(flagsSet & wxFS_VOL_REMOVABLE)
406 )
407 {
408 // The returned list will be sorted alphabetically. We don't pass
409 // our in since we don't want to change to order of the local drives.
410 wxArrayString nn;
411 if (BuildRemoteList(nn, 0, flagsSet, flagsUnset))
412 {
413 int idx;
414 for (idx = 0; idx < nn.GetCount(); idx++)
415 list.Add(nn[idx]);
416 }
417 }
418
419 return list;
420 } // GetVolumes
421
422 //=============================================================================
423 // Function: CancelSearch
424 // Purpose: Instruct an active search to stop.
425 // Notes: - This will only sensibly be called by a thread other than the one
426 // performing the search. This is the only thread-safe function
427 // provided by the class.
428 //=============================================================================
429 void wxFSVolume::CancelSearch()
430 {
431 InterlockedExchange(&s_cancelSearch, TRUE);
432 } // CancelSearch
433
434 //=============================================================================
435 // Function: constructor
436 // Purpose: default constructor
437 //=============================================================================
438 wxFSVolume::wxFSVolume()
439 {
440 m_isOk = FALSE;
441 } // wxVolume
442
443 //=============================================================================
444 // Function: constructor
445 // Purpose: constructor that calls Create
446 //=============================================================================
447 wxFSVolume::wxFSVolume(const wxString& name)
448 {
449 Create(name);
450 } // wxVolume
451
452 //=============================================================================
453 // Function: Create
454 // Purpose: Finds, logs in, etc. to the request volume.
455 //=============================================================================
456 bool wxFSVolume::Create(const wxString& name)
457 {
458 // assume fail.
459 m_isOk = FALSE;
460
461 // supplied.
462 m_volName = name;
463
464 // Display name.
465 SHFILEINFO fi;
466 long rc = SHGetFileInfo(m_volName, 0, &fi, sizeof(fi), SHGFI_DISPLAYNAME);
467 if (!rc)
468 {
469 wxLogError(_("Cannot read typename from '%s'!"), m_volName);
470 return m_isOk;
471 }
472 m_dispName = fi.szDisplayName;
473
474 #ifdef wxUSE_GUI
475
476 m_icons.Alloc(wxFS_VOL_ICO_MAX);
477 int idx;
478 wxIcon null;
479 for (idx = 0; idx < wxFS_VOL_ICO_MAX; idx++)
480 m_icons.Add(null);
481
482 #endif
483
484 // all tests passed.
485 return m_isOk = TRUE;
486 } // Create
487
488 //=============================================================================
489 // Function: IsOk
490 // Purpose: returns TRUE if the volume is legal.
491 // Notes: For fixed disks, it must exist. For removable disks, it must also
492 // be present. For Network Shares, it must also be logged in, etc.
493 //=============================================================================
494 bool wxFSVolume::IsOk() const
495 {
496 return m_isOk;
497 } // IsOk
498
499 //=============================================================================
500 // Function: GetKind
501 // Purpose: Return the type of the volume.
502 //=============================================================================
503 wxFSVolumeKind wxFSVolume::GetKind() const
504 {
505 if (!m_isOk)
506 return wxFS_VOL_OTHER;
507
508 FileInfoMap::iterator itr = s_fileInfo.find(m_volName);
509 if (itr == s_fileInfo.end())
510 return wxFS_VOL_OTHER;
511
512 return itr->second.m_type;
513 }
514
515 //=============================================================================
516 // Function: GetFlags
517 // Purpose: Return the caches flags for this volume.
518 // Notes: - Returns -1 if no flags were cached.
519 //=============================================================================
520 int wxFSVolume::GetFlags() const
521 {
522 if (!m_isOk)
523 return -1;
524
525 FileInfoMap::iterator itr = s_fileInfo.find(m_volName);
526 if (itr == s_fileInfo.end())
527 return -1;
528
529 return itr->second.m_flags;
530 } // GetFlags
531
532 #ifdef wxUSE_GUI
533
534 //=============================================================================
535 // Function: GetIcon
536 // Purpose: return the requested icon.
537 //=============================================================================
538 wxIcon wxFSVolume::GetIcon(wxFSIconType type) const
539 {
540 wxASSERT(type < m_icons.GetCount());
541
542 if (type >= m_icons.GetCount())
543 {
544 wxLogError(_("Invalid request for icon type!"));
545 wxIcon null;
546 return null;
547 }
548
549 // Load on demand.
550 if (m_icons[type].IsNull())
551 {
552 unsigned flags = 0;
553 switch (type)
554 {
555 case wxFS_VOL_ICO_SMALL:
556 flags = SHGFI_ICON | SHGFI_SMALLICON;
557 break;
558
559 case wxFS_VOL_ICO_LARGE:
560 flags = SHGFI_ICON | SHGFI_SHELLICONSIZE;
561 break;
562
563 case wxFS_VOL_ICO_SEL_SMALL:
564 flags = SHGFI_ICON | SHGFI_SMALLICON | SHGFI_OPENICON;
565 break;
566
567 case wxFS_VOL_ICO_SEL_LARGE:
568 flags = SHGFI_ICON | SHGFI_SHELLICONSIZE | SHGFI_OPENICON;
569 break;
570 }
571
572 SHFILEINFO fi;
573 long rc = SHGetFileInfo(m_volName, 0, &fi, sizeof(fi), flags);
574 m_icons[type].SetHICON((WXHICON)fi.hIcon);
575 if (!rc || !fi.hIcon)
576 wxLogError(_("Cannot load icon from '%s'."), m_volName);
577 }
578
579 return m_icons[type];
580 } // GetIcon
581
582 #endif // wxUSE_GUI
583