avoid streaming of 'private' children
[wxWidgets.git] / src / generic / dirctrlg.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: dirctrlg.cpp
3 // Purpose: wxGenericDirCtrl
4 // Author: Harm van der Heijden, Robert Roebling, Julian Smart
5 // Modified by:
6 // Created: 12/12/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Harm van der Heijden, Robert Roebling and Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
13 #pragma implementation "dirctrlg.h"
14 #endif
15
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
18
19 #ifdef __BORLANDC__
20 #pragma hdrstop
21 #endif
22
23 #if wxUSE_DIRDLG
24
25 #include "wx/generic/dirctrlg.h"
26
27 #include "wx/module.h"
28 #include "wx/utils.h"
29 #include "wx/button.h"
30 #include "wx/layout.h"
31 #include "wx/msgdlg.h"
32 #include "wx/textctrl.h"
33 #include "wx/textdlg.h"
34 #include "wx/filefn.h"
35 #include "wx/cmndata.h"
36 #include "wx/gdicmn.h"
37 #include "wx/intl.h"
38 #include "wx/imaglist.h"
39 #include "wx/icon.h"
40 #include "wx/log.h"
41 #include "wx/sizer.h"
42 #include "wx/tokenzr.h"
43 #include "wx/dir.h"
44 #include "wx/settings.h"
45 #include "wx/artprov.h"
46 #include "wx/hash.h"
47 #include "wx/mimetype.h"
48 #include "wx/image.h"
49 #include "wx/choice.h"
50 #include "wx/filedlg.h" // for wxFileDialogBase::ParseWildcard
51
52 #if wxUSE_STATLINE
53 #include "wx/statline.h"
54 #endif
55
56 #if defined(__WXMAC__)
57 #include "wx/mac/private.h" // includes mac headers
58 #endif
59
60 #ifdef __WXMSW__
61 #include <windows.h>
62
63 // FIXME - Mingw32 1.0 has both _getdrive() and _chdrive(). For now, let's assume
64 // older releases don't, but it should be verified and the checks modified
65 // accordingly.
66 #if !defined(__GNUWIN32__) || (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
67 #if !defined(__WXWINCE__)
68 #include <direct.h>
69 #endif
70 #include <stdlib.h>
71 #include <ctype.h>
72 #endif
73
74 #endif
75
76 #ifdef __WXPM__
77
78 #define INCL_BASE
79 #include <os2.h>
80 #ifndef __EMX__
81 #include <direct.h>
82 #endif
83 #include <stdlib.h>
84 #include <ctype.h>
85 extern bool wxIsDriveAvailable(const wxString& dirName);
86 #endif // __WXPM__
87
88 #if defined(__WXMAC__)
89 # ifdef __DARWIN__
90 # include "MoreFilesX.h"
91 # else
92 # include "MoreFilesExtras.h"
93 # endif
94 #endif
95
96 #ifdef __BORLANDC__
97 #include "dos.h"
98 #endif
99
100 // If compiled under Windows, this macro can cause problems
101 #ifdef GetFirstChild
102 #undef GetFirstChild
103 #endif
104
105 // ----------------------------------------------------------------------------
106 // wxGetAvailableDrives, for WINDOWS, DOS, WXPM, MAC, UNIX (returns "/")
107 // ----------------------------------------------------------------------------
108
109 size_t wxGetAvailableDrives(wxArrayString &paths, wxArrayString &names, wxArrayInt &icon_ids)
110 {
111 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
112
113 #ifdef __WXWINCE__
114 // No logical drives; return "\"
115 paths.Add(wxT("\\"));
116 names.Add(wxT("\\"));
117 return 1;
118 #elif defined(__WIN32__)
119 wxChar driveBuffer[256];
120 size_t n = (size_t) GetLogicalDriveStrings(255, driveBuffer);
121 size_t i = 0;
122 while (i < n)
123 {
124 wxString path, name;
125 path.Printf(wxT("%c:\\"), driveBuffer[i]);
126 name.Printf(wxT("%c:"), driveBuffer[i]);
127
128 int imageId = wxFileIconsTable::drive;
129 int driveType = ::GetDriveType(path);
130 switch (driveType)
131 {
132 case DRIVE_REMOVABLE:
133 if (path == wxT("a:\\") || path == wxT("b:\\"))
134 imageId = wxFileIconsTable::floppy;
135 else
136 imageId = wxFileIconsTable::removeable;
137 break;
138 case DRIVE_CDROM:
139 imageId = wxFileIconsTable::cdrom;
140 break;
141 case DRIVE_REMOTE:
142 case DRIVE_FIXED:
143 default:
144 imageId = wxFileIconsTable::drive;
145 break;
146 }
147
148 paths.Add(path);
149 names.Add(name);
150 icon_ids.Add(imageId);
151
152 while (driveBuffer[i] != wxT('\0'))
153 i ++;
154 i ++;
155 if (driveBuffer[i] == wxT('\0'))
156 break;
157 }
158 #else // !__WIN32__
159 int drive;
160
161 /* If we can switch to the drive, it exists. */
162 for( drive = 1; drive <= 26; drive++ )
163 {
164 wxString path, name;
165 path.Printf(wxT("%c:\\"), (char) (drive + 'a' - 1));
166 name.Printf(wxT("%c:"), (char) (drive + 'A' - 1));
167
168 if (wxIsDriveAvailable(path))
169 {
170 paths.Add(path);
171 names.Add(name);
172 icon_ids.Add((drive <= 2) ? wxFileIconsTable::floppy : wxFileIconsTable::drive);
173 }
174 }
175 #endif // __WIN32__/!__WIN32__
176
177 #elif defined(__WXMAC__)
178 #ifdef __DARWIN__
179 FSRef **theVolRefs;
180 ItemCount theVolCount;
181 char thePath[FILENAME_MAX];
182
183 if (FSGetMountedVolumes(&theVolRefs, &theVolCount) == noErr) {
184 ItemCount index;
185 ::HLock( (Handle)theVolRefs ) ;
186 for (index = 0; index < theVolCount; ++index) {
187 // get the POSIX path associated with the FSRef
188 if ( FSRefMakePath(&((*theVolRefs)[index]),
189 (UInt8 *)thePath, sizeof(thePath)) != noErr ) {
190 continue;
191 }
192 // add path separator at end if necessary
193 wxString path( thePath , wxConvLocal) ;
194 if (path.Last() != wxFILE_SEP_PATH) {
195 path += wxFILE_SEP_PATH;
196 }
197 // get Mac volume name for display
198 FSVolumeRefNum vRefNum ;
199 HFSUniStr255 volumeName ;
200
201 if ( FSGetVRefNum(&((*theVolRefs)[index]), &vRefNum) != noErr ) {
202 continue;
203 }
204 if ( FSGetVInfo(vRefNum, &volumeName, NULL, NULL) != noErr ) {
205 continue;
206 }
207 // get C string from Unicode HFS name
208 // see: http://developer.apple.com/carbon/tipsandtricks.html
209 CFStringRef cfstr = CFStringCreateWithCharacters( kCFAllocatorDefault,
210 volumeName.unicode,
211 volumeName.length );
212 // Do something with str
213 char *cstr = NewPtr(CFStringGetLength(cfstr) + 1);
214 if (( cstr == NULL ) ||
215 !CFStringGetCString(cfstr, cstr, CFStringGetLength(cfstr) + 1,
216 kCFStringEncodingMacRoman))
217 {
218 CFRelease( cstr );
219 continue;
220 }
221 wxString name( cstr , wxConvLocal );
222 DisposePtr( cstr );
223 CFRelease( cfstr );
224
225 GetVolParmsInfoBuffer volParmsInfo;
226 UInt32 actualSize;
227 if ( FSGetVolParms(vRefNum, sizeof(volParmsInfo), &volParmsInfo, &actualSize) != noErr ) {
228 continue;
229 }
230
231 paths.Add(path);
232 names.Add(name);
233
234 if ( VolIsEjectable(&volParmsInfo) )
235 icon_ids.Add(wxFileIconsTable::cdrom);
236 else
237 icon_ids.Add(wxFileIconsTable::drive);
238 }
239 ::HUnlock( (Handle)theVolRefs );
240 ::DisposeHandle( (Handle)theVolRefs );
241 }
242 #else // !__DARWIN__
243 FSSpec volume;
244 short index = 1;
245 while(1)
246 {
247 short actualCount = 0 ;
248 if (OnLine(&volume, 1, &actualCount, &index ) != noErr || actualCount==0)
249 {
250 break;
251 }
252
253 wxString name = wxMacFSSpec2MacFilename( &volume );
254 paths.Add(name + wxFILE_SEP_PATH);
255 names.Add(name);
256 icon_ids.Add(wxFileIconsTable::drive);
257 }
258 #endif // __DARWIN__
259
260 #elif defined(__UNIX__)
261 paths.Add(wxT("/"));
262 names.Add(wxT("/"));
263 icon_ids.Add(wxFileIconsTable::computer);
264 #else
265 #error "Unsupported platform in wxGenericDirCtrl!"
266 #endif
267 return paths.GetCount();
268 }
269
270 // ----------------------------------------------------------------------------
271 // wxIsDriveAvailable
272 // ----------------------------------------------------------------------------
273
274 #if defined(__DOS__)
275
276 bool wxIsDriveAvailable(const wxString& dirName)
277 {
278 // FIXME_MGL - this method leads to hang up under Watcom for some reason
279 #ifndef __WATCOMC__
280 if ( dirName.Len() == 3 && dirName[1u] == wxT(':') )
281 {
282 wxString dirNameLower(dirName.Lower());
283 // VS: always return TRUE for removable media, since Win95 doesn't
284 // like it when MS-DOS app accesses empty floppy drive
285 return (dirNameLower[0u] == wxT('a') ||
286 dirNameLower[0u] == wxT('b') ||
287 wxPathExists(dirNameLower));
288 }
289 else
290 #endif
291 return TRUE;
292 }
293
294 #elif defined(__WINDOWS__) || defined(__WXPM__)
295
296 int setdrive(int drive)
297 {
298 #ifdef __WXWINCE__
299 return 0;
300 #elif defined(__GNUWIN32__) && \
301 (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
302 return _chdrive(drive);
303 #else
304 wxChar newdrive[3];
305
306 if (drive < 1 || drive > 31)
307 return -1;
308 newdrive[0] = (wxChar)(wxT('A') + drive - 1);
309 newdrive[1] = wxT(':');
310 newdrive[2] = wxT('\0');
311 #if defined(__WXMSW__)
312 if (::SetCurrentDirectory(newdrive))
313 #else
314 // VA doesn't know what LPSTR is and has its own set
315 if (DosSetCurrentDir((PSZ)newdrive))
316 #endif
317 return 0;
318 else
319 return -1;
320 #endif // !GNUWIN32
321 }
322
323 bool wxIsDriveAvailable(const wxString& dirName)
324 {
325 #ifdef __WXWINCE__
326 return FALSE;
327 #else
328 #ifdef __WIN32__
329 UINT errorMode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
330 #endif
331 bool success = TRUE;
332
333 // Check if this is a root directory and if so,
334 // whether the drive is available.
335 if (dirName.Len() == 3 && dirName[(size_t)1] == wxT(':'))
336 {
337 wxString dirNameLower(dirName.Lower());
338 #if defined(__GNUWIN32__) && !(defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
339 success = wxPathExists(dirNameLower);
340 #else
341 int currentDrive = _getdrive();
342 int thisDrive = (int) (dirNameLower[(size_t)0] - 'a' + 1) ;
343 int err = setdrive( thisDrive ) ;
344 setdrive( currentDrive );
345
346 if (err == -1)
347 {
348 success = FALSE;
349 }
350 #endif
351 }
352 #ifdef __WIN32__
353 (void) SetErrorMode(errorMode);
354 #endif
355
356 return success;
357 #endif
358 }
359 #endif // __WINDOWS__ || __WXPM__
360
361
362 // Function which is called by quick sort. We want to override the default wxArrayString behaviour,
363 // and sort regardless of case.
364 static int LINKAGEMODE wxDirCtrlStringCompareFunction(wxString* strFirst, wxString* strSecond)
365 {
366 return strFirst->CmpNoCase(*strSecond);
367 }
368
369 //-----------------------------------------------------------------------------
370 // wxDirItemData
371 //-----------------------------------------------------------------------------
372
373 wxDirItemData::wxDirItemData(const wxString& path, const wxString& name,
374 bool isDir)
375 {
376 m_path = path;
377 m_name = name;
378 /* Insert logic to detect hidden files here
379 * In UnixLand we just check whether the first char is a dot
380 * For FileNameFromPath read LastDirNameInThisPath ;-) */
381 // m_isHidden = (bool)(wxFileNameFromPath(*m_path)[0] == '.');
382 m_isHidden = FALSE;
383 m_isExpanded = FALSE;
384 m_isDir = isDir;
385 }
386
387 wxDirItemData::~wxDirItemData()
388 {
389 }
390
391 void wxDirItemData::SetNewDirName(const wxString& path)
392 {
393 m_path = path;
394 m_name = wxFileNameFromPath(path);
395 }
396
397 bool wxDirItemData::HasSubDirs() const
398 {
399 if (m_path.IsEmpty())
400 return FALSE;
401
402 wxDir dir;
403 {
404 wxLogNull nolog;
405 if ( !dir.Open(m_path) )
406 return FALSE;
407 }
408
409 return dir.HasSubDirs();
410 }
411
412 bool wxDirItemData::HasFiles(const wxString& WXUNUSED(spec)) const
413 {
414 if (m_path.IsEmpty())
415 return FALSE;
416
417 wxDir dir;
418 {
419 wxLogNull nolog;
420 if ( !dir.Open(m_path) )
421 return FALSE;
422 }
423
424 return dir.HasFiles();
425 }
426
427 //-----------------------------------------------------------------------------
428 // wxGenericDirCtrl
429 //-----------------------------------------------------------------------------
430
431
432 #if wxUSE_EXTENDED_RTTI
433 IMPLEMENT_DYNAMIC_CLASS_XTI(wxGenericDirCtrl, wxControl,"wx/dirctrl.h")
434
435 WX_BEGIN_PROPERTIES_TABLE(wxGenericDirCtrl)
436 WX_HIDE_PROPERTY( Children )
437 WX_PROPERTY( DefaultPath , wxString , SetDefaultPath , GetDefaultPath , , 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
438 WX_PROPERTY( Filter , wxString , SetFilter , GetFilter ,, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
439 WX_PROPERTY( DefaultFilter , int , SetFilterIndex, GetFilterIndex,, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
440 WX_END_PROPERTIES_TABLE()
441
442 WX_BEGIN_HANDLERS_TABLE(wxGenericDirCtrl)
443 WX_END_HANDLERS_TABLE()
444
445 WX_CONSTRUCTOR_8( wxGenericDirCtrl , wxWindow* , Parent , wxWindowID , Id , wxString , DefaultPath ,
446 wxPoint , Position , wxSize , Size , long , WindowStyle , wxString , Filter , int , DefaultFilter )
447 #else
448 IMPLEMENT_DYNAMIC_CLASS(wxGenericDirCtrl, wxControl)
449 #endif
450
451 BEGIN_EVENT_TABLE(wxGenericDirCtrl, wxControl)
452 EVT_TREE_ITEM_EXPANDING (-1, wxGenericDirCtrl::OnExpandItem)
453 EVT_TREE_ITEM_COLLAPSED (-1, wxGenericDirCtrl::OnCollapseItem)
454 EVT_TREE_BEGIN_LABEL_EDIT (-1, wxGenericDirCtrl::OnBeginEditItem)
455 EVT_TREE_END_LABEL_EDIT (-1, wxGenericDirCtrl::OnEndEditItem)
456 EVT_SIZE (wxGenericDirCtrl::OnSize)
457 END_EVENT_TABLE()
458
459 wxGenericDirCtrl::wxGenericDirCtrl(void)
460 {
461 Init();
462 }
463
464 bool wxGenericDirCtrl::Create(wxWindow *parent,
465 const wxWindowID id,
466 const wxString& dir,
467 const wxPoint& pos,
468 const wxSize& size,
469 long style,
470 const wxString& filter,
471 int defaultFilter,
472 const wxString& name)
473 {
474 if (!wxControl::Create(parent, id, pos, size, style, wxDefaultValidator, name))
475 return FALSE;
476
477 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE));
478
479 Init();
480
481 long treeStyle = wxTR_HAS_BUTTONS | wxTR_HIDE_ROOT;
482
483 if (style & wxDIRCTRL_EDIT_LABELS)
484 treeStyle |= wxTR_EDIT_LABELS;
485
486 if ((style & wxDIRCTRL_3D_INTERNAL) == 0)
487 treeStyle |= wxNO_BORDER;
488 else
489 treeStyle |= wxBORDER_SUNKEN;
490
491 long filterStyle = 0;
492 if ((style & wxDIRCTRL_3D_INTERNAL) == 0)
493 filterStyle |= wxNO_BORDER;
494 else
495 filterStyle |= wxBORDER_SUNKEN;
496
497 m_treeCtrl = new wxTreeCtrl(this, wxID_TREECTRL, pos, size, treeStyle);
498
499 if (!filter.IsEmpty() && (style & wxDIRCTRL_SHOW_FILTERS))
500 m_filterListCtrl = new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL, wxDefaultPosition, wxDefaultSize, filterStyle);
501
502 m_defaultPath = dir;
503 m_filter = filter;
504
505 SetFilterIndex(defaultFilter);
506
507 if (m_filterListCtrl)
508 m_filterListCtrl->FillFilterList(filter, defaultFilter);
509
510 m_treeCtrl->SetImageList(wxTheFileIconsTable->GetSmallImageList());
511
512 m_showHidden = FALSE;
513 wxDirItemData* rootData = new wxDirItemData(wxT(""), wxT(""), TRUE);
514
515 wxString rootName;
516
517 #if defined(__WINDOWS__) || defined(__WXPM__) || defined(__DOS__)
518 rootName = _("Computer");
519 #else
520 rootName = _("Sections");
521 #endif
522
523 m_rootId = m_treeCtrl->AddRoot( rootName, 3, -1, rootData);
524 m_treeCtrl->SetItemHasChildren(m_rootId);
525 ExpandDir(m_rootId); // automatically expand first level
526
527 // Expand and select the default path
528 if (!m_defaultPath.IsEmpty())
529 ExpandPath(m_defaultPath);
530
531 DoResize();
532
533 return TRUE;
534 }
535
536 wxGenericDirCtrl::~wxGenericDirCtrl()
537 {
538 }
539
540 void wxGenericDirCtrl::Init()
541 {
542 m_showHidden = FALSE;
543 m_currentFilter = 0;
544 m_currentFilterStr = wxEmptyString; // Default: any file
545 m_treeCtrl = NULL;
546 m_filterListCtrl = NULL;
547 }
548
549 void wxGenericDirCtrl::ShowHidden( bool show )
550 {
551 m_showHidden = show;
552
553 wxString path = GetPath();
554 ReCreateTree();
555 SetPath(path);
556 }
557
558 const wxTreeItemId
559 wxGenericDirCtrl::AddSection(const wxString& path, const wxString& name, int imageId)
560 {
561 wxDirItemData *dir_item = new wxDirItemData(path,name,TRUE);
562
563 wxTreeItemId id = AppendItem( m_rootId, name, imageId, -1, dir_item);
564
565 m_treeCtrl->SetItemHasChildren(id);
566
567 return id;
568 }
569
570 void wxGenericDirCtrl::SetupSections()
571 {
572 wxArrayString paths, names;
573 wxArrayInt icons;
574
575 size_t n, count = wxGetAvailableDrives(paths, names, icons);
576
577 for (n = 0; n < count; n++)
578 {
579 AddSection(paths[n], names[n], icons[n]);
580 }
581 }
582
583 void wxGenericDirCtrl::OnBeginEditItem(wxTreeEvent &event)
584 {
585 // don't rename the main entry "Sections"
586 if (event.GetItem() == m_rootId)
587 {
588 event.Veto();
589 return;
590 }
591
592 // don't rename the individual sections
593 if (m_treeCtrl->GetItemParent( event.GetItem() ) == m_rootId)
594 {
595 event.Veto();
596 return;
597 }
598 }
599
600 void wxGenericDirCtrl::OnEndEditItem(wxTreeEvent &event)
601 {
602 if ((event.GetLabel().IsEmpty()) ||
603 (event.GetLabel() == _(".")) ||
604 (event.GetLabel() == _("..")) ||
605 (event.GetLabel().Find(wxT('/')) != wxNOT_FOUND) ||
606 (event.GetLabel().Find(wxT('\\')) != wxNOT_FOUND) ||
607 (event.GetLabel().Find(wxT('|')) != wxNOT_FOUND))
608 {
609 wxMessageDialog dialog(this, _("Illegal directory name."), _("Error"), wxOK | wxICON_ERROR );
610 dialog.ShowModal();
611 event.Veto();
612 return;
613 }
614
615 wxTreeItemId id = event.GetItem();
616 wxDirItemData *data = (wxDirItemData*)m_treeCtrl->GetItemData( id );
617 wxASSERT( data );
618
619 wxString new_name( wxPathOnly( data->m_path ) );
620 new_name += wxString(wxFILE_SEP_PATH);
621 new_name += event.GetLabel();
622
623 wxLogNull log;
624
625 if (wxFileExists(new_name))
626 {
627 wxMessageDialog dialog(this, _("File name exists already."), _("Error"), wxOK | wxICON_ERROR );
628 dialog.ShowModal();
629 event.Veto();
630 }
631
632 if (wxRenameFile(data->m_path,new_name))
633 {
634 data->SetNewDirName( new_name );
635 }
636 else
637 {
638 wxMessageDialog dialog(this, _("Operation not permitted."), _("Error"), wxOK | wxICON_ERROR );
639 dialog.ShowModal();
640 event.Veto();
641 }
642 }
643
644 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent &event)
645 {
646 wxTreeItemId parentId = event.GetItem();
647
648 // VS: this is needed because the event handler is called from wxTreeCtrl
649 // ctor when wxTR_HIDE_ROOT was specified
650
651 if (!m_rootId.IsOk())
652
653 m_rootId = m_treeCtrl->GetRootItem();
654
655 ExpandDir(parentId);
656 }
657
658 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent &event )
659 {
660 CollapseDir(event.GetItem());
661 }
662
663 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId)
664 {
665 wxTreeItemId child;
666
667 wxDirItemData *data = (wxDirItemData *) m_treeCtrl->GetItemData(parentId);
668 if (!data->m_isExpanded)
669 return;
670
671 data->m_isExpanded = FALSE;
672 wxTreeItemIdValue cookie;
673 /* Workaround because DeleteChildren has disapeared (why?) and
674 * CollapseAndReset doesn't work as advertised (deletes parent too) */
675 child = m_treeCtrl->GetFirstChild(parentId, cookie);
676 while (child.IsOk())
677 {
678 m_treeCtrl->Delete(child);
679 /* Not GetNextChild below, because the cookie mechanism can't
680 * handle disappearing children! */
681 child = m_treeCtrl->GetFirstChild(parentId, cookie);
682 }
683 }
684
685 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId)
686 {
687 wxDirItemData *data = (wxDirItemData *) m_treeCtrl->GetItemData(parentId);
688
689 if (data->m_isExpanded)
690 return;
691
692 data->m_isExpanded = TRUE;
693
694 if (parentId == m_treeCtrl->GetRootItem())
695 {
696 SetupSections();
697 return;
698 }
699
700 wxASSERT(data);
701
702 wxString search,path,filename;
703
704 wxString dirName(data->m_path);
705
706 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
707 // Check if this is a root directory and if so,
708 // whether the drive is avaiable.
709 if (!wxIsDriveAvailable(dirName))
710 {
711 data->m_isExpanded = FALSE;
712 //wxMessageBox(wxT("Sorry, this drive is not available."));
713 return;
714 }
715 #endif
716
717 // This may take a longish time. Go to busy cursor
718 wxBusyCursor busy;
719
720 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
721 if (dirName.Last() == ':')
722 dirName += wxString(wxFILE_SEP_PATH);
723 #endif
724
725 wxArrayString dirs;
726 wxArrayString filenames;
727
728 wxDir d;
729 wxString eachFilename;
730
731 wxLogNull log;
732 d.Open(dirName);
733
734 if (d.IsOpened())
735 {
736 int style = wxDIR_DIRS;
737 if (m_showHidden) style |= wxDIR_HIDDEN;
738 if (d.GetFirst(& eachFilename, wxEmptyString, style))
739 {
740 do
741 {
742 if ((eachFilename != wxT(".")) && (eachFilename != wxT("..")))
743 {
744 dirs.Add(eachFilename);
745 }
746 }
747 while (d.GetNext(& eachFilename));
748 }
749 }
750 dirs.Sort(wxDirCtrlStringCompareFunction);
751
752 // Now do the filenames -- but only if we're allowed to
753 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY) == 0)
754 {
755 wxLogNull log;
756
757 d.Open(dirName);
758
759 if (d.IsOpened())
760 {
761 if (d.GetFirst(& eachFilename, m_currentFilterStr, wxDIR_FILES))
762 {
763 do
764 {
765 if ((eachFilename != wxT(".")) && (eachFilename != wxT("..")))
766 {
767 filenames.Add(eachFilename);
768 }
769 }
770 while (d.GetNext(& eachFilename));
771 }
772 }
773 filenames.Sort(wxDirCtrlStringCompareFunction);
774 }
775
776 // Add the sorted dirs
777 size_t i;
778 for (i = 0; i < dirs.Count(); i++)
779 {
780 wxString eachFilename(dirs[i]);
781 path = dirName;
782 if (!wxEndsWithPathSeparator(path))
783 path += wxString(wxFILE_SEP_PATH);
784 path += eachFilename;
785
786 wxDirItemData *dir_item = new wxDirItemData(path,eachFilename,TRUE);
787 wxTreeItemId id = AppendItem( parentId, eachFilename,
788 wxFileIconsTable::folder, -1, dir_item);
789 m_treeCtrl->SetItemImage( id, wxFileIconsTable::folder_open,
790 wxTreeItemIcon_Expanded );
791
792 // Has this got any children? If so, make it expandable.
793 // (There are two situations when a dir has children: either it
794 // has subdirectories or it contains files that weren't filtered
795 // out. The latter only applies to dirctrl with files.)
796 if ( dir_item->HasSubDirs() ||
797 (((GetWindowStyle() & wxDIRCTRL_DIR_ONLY) == 0) &&
798 dir_item->HasFiles(m_currentFilterStr)) )
799 {
800 m_treeCtrl->SetItemHasChildren(id);
801 }
802 }
803
804 // Add the sorted filenames
805 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY) == 0)
806 {
807 for (i = 0; i < filenames.Count(); i++)
808 {
809 wxString eachFilename(filenames[i]);
810 path = dirName;
811 if (!wxEndsWithPathSeparator(path))
812 path += wxString(wxFILE_SEP_PATH);
813 path += eachFilename;
814 //path = dirName + wxString(wxT("/")) + eachFilename;
815 wxDirItemData *dir_item = new wxDirItemData(path,eachFilename,FALSE);
816 int image_id = wxFileIconsTable::file;
817 if (eachFilename.Find(wxT('.')) != wxNOT_FOUND)
818 image_id = wxTheFileIconsTable->GetIconID(eachFilename.AfterLast(wxT('.')));
819 (void) AppendItem( parentId, eachFilename, image_id, -1, dir_item);
820 }
821 }
822 }
823
824 void wxGenericDirCtrl::ReCreateTree()
825 {
826 CollapseDir(m_treeCtrl->GetRootItem());
827 ExpandDir(m_treeCtrl->GetRootItem());
828 }
829
830 // Find the child that matches the first part of 'path'.
831 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
832 // then the child for /usr is returned.
833 wxTreeItemId wxGenericDirCtrl::FindChild(wxTreeItemId parentId, const wxString& path, bool& done)
834 {
835 wxString path2(path);
836
837 // Make sure all separators are as per the current platform
838 path2.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH));
839 path2.Replace(wxT("/"), wxString(wxFILE_SEP_PATH));
840
841 // Append a separator to foil bogus substring matching
842 path2 += wxString(wxFILE_SEP_PATH);
843
844 // In MSW or PM, case is not significant
845 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
846 path2.MakeLower();
847 #endif
848
849 wxTreeItemIdValue cookie;
850 wxTreeItemId childId = m_treeCtrl->GetFirstChild(parentId, cookie);
851 while (childId.IsOk())
852 {
853 wxDirItemData* data = (wxDirItemData*) m_treeCtrl->GetItemData(childId);
854
855 if (data && !data->m_path.IsEmpty())
856 {
857 wxString childPath(data->m_path);
858 if (!wxEndsWithPathSeparator(childPath))
859 childPath += wxString(wxFILE_SEP_PATH);
860
861 // In MSW and PM, case is not significant
862 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
863 childPath.MakeLower();
864 #endif
865
866 if (childPath.Len() <= path2.Len())
867 {
868 wxString path3 = path2.Mid(0, childPath.Len());
869 if (childPath == path3)
870 {
871 if (path3.Len() == path2.Len())
872 done = TRUE;
873 else
874 done = FALSE;
875 return childId;
876 }
877 }
878 }
879
880 childId = m_treeCtrl->GetNextChild(parentId, cookie);
881 }
882 wxTreeItemId invalid;
883 return invalid;
884 }
885
886 // Try to expand as much of the given path as possible,
887 // and select the given tree item.
888 bool wxGenericDirCtrl::ExpandPath(const wxString& path)
889 {
890 bool done = FALSE;
891 wxTreeItemId id = FindChild(m_rootId, path, done);
892 wxTreeItemId lastId = id; // The last non-zero id
893 while (id.IsOk() && !done)
894 {
895 ExpandDir(id);
896
897 id = FindChild(id, path, done);
898 if (id.IsOk())
899 lastId = id;
900 }
901 if (lastId.IsOk())
902 {
903 wxDirItemData *data = (wxDirItemData *) m_treeCtrl->GetItemData(lastId);
904 if (data->m_isDir)
905 {
906 m_treeCtrl->Expand(lastId);
907 }
908 if ((GetWindowStyle() & wxDIRCTRL_SELECT_FIRST) && data->m_isDir)
909 {
910 // Find the first file in this directory
911 wxTreeItemIdValue cookie;
912 wxTreeItemId childId = m_treeCtrl->GetFirstChild(lastId, cookie);
913 bool selectedChild = FALSE;
914 while (childId.IsOk())
915 {
916 wxDirItemData* data = (wxDirItemData*) m_treeCtrl->GetItemData(childId);
917
918 if (data && data->m_path != wxT("") && !data->m_isDir)
919 {
920 m_treeCtrl->SelectItem(childId);
921 m_treeCtrl->EnsureVisible(childId);
922 selectedChild = TRUE;
923 break;
924 }
925 childId = m_treeCtrl->GetNextChild(lastId, cookie);
926 }
927 if (!selectedChild)
928 {
929 m_treeCtrl->SelectItem(lastId);
930 m_treeCtrl->EnsureVisible(lastId);
931 }
932 }
933 else
934 {
935 m_treeCtrl->SelectItem(lastId);
936 m_treeCtrl->EnsureVisible(lastId);
937 }
938
939 return TRUE;
940 }
941 else
942 return FALSE;
943 }
944
945 wxString wxGenericDirCtrl::GetPath() const
946 {
947 wxTreeItemId id = m_treeCtrl->GetSelection();
948 if (id)
949 {
950 wxDirItemData* data = (wxDirItemData*) m_treeCtrl->GetItemData(id);
951 return data->m_path;
952 }
953 else
954 return wxEmptyString;
955 }
956
957 wxString wxGenericDirCtrl::GetFilePath() const
958 {
959 wxTreeItemId id = m_treeCtrl->GetSelection();
960 if (id)
961 {
962 wxDirItemData* data = (wxDirItemData*) m_treeCtrl->GetItemData(id);
963 if (data->m_isDir)
964 return wxEmptyString;
965 else
966 return data->m_path;
967 }
968 else
969 return wxEmptyString;
970 }
971
972 void wxGenericDirCtrl::SetPath(const wxString& path)
973 {
974 m_defaultPath = path;
975 if (m_rootId)
976 ExpandPath(path);
977 }
978
979 // Not used
980 #if 0
981 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId id, int dirFlags, wxArrayString& filenames)
982 {
983 wxDirItemData *data = (wxDirItemData *) m_treeCtrl->GetItemData(id);
984
985 // This may take a longish time. Go to busy cursor
986 wxBusyCursor busy;
987
988 wxASSERT(data);
989
990 wxString search,path,filename;
991
992 wxString dirName(data->m_path);
993
994 #if defined(__WXMSW__) || defined(__WXPM__)
995 if (dirName.Last() == ':')
996 dirName += wxString(wxFILE_SEP_PATH);
997 #endif
998
999 wxDir d;
1000 wxString eachFilename;
1001
1002 wxLogNull log;
1003 d.Open(dirName);
1004
1005 if (d.IsOpened())
1006 {
1007 if (d.GetFirst(& eachFilename, m_currentFilterStr, dirFlags))
1008 {
1009 do
1010 {
1011 if ((eachFilename != wxT(".")) && (eachFilename != wxT("..")))
1012 {
1013 filenames.Add(eachFilename);
1014 }
1015 }
1016 while (d.GetNext(& eachFilename)) ;
1017 }
1018 }
1019 }
1020 #endif
1021
1022 void wxGenericDirCtrl::SetFilterIndex(int n)
1023 {
1024 m_currentFilter = n;
1025
1026 wxString f, d;
1027 if (ExtractWildcard(m_filter, n, f, d))
1028 m_currentFilterStr = f;
1029 else
1030 m_currentFilterStr = wxT("*.*");
1031 }
1032
1033 void wxGenericDirCtrl::SetFilter(const wxString& filter)
1034 {
1035 m_filter = filter;
1036
1037 wxString f, d;
1038 if (ExtractWildcard(m_filter, m_currentFilter, f, d))
1039 m_currentFilterStr = f;
1040 else
1041 m_currentFilterStr = wxT("*.*");
1042 }
1043
1044 // Extract description and actual filter from overall filter string
1045 bool wxGenericDirCtrl::ExtractWildcard(const wxString& filterStr, int n, wxString& filter, wxString& description)
1046 {
1047 wxArrayString filters, descriptions;
1048 int count = ParseFilter(filterStr, filters, descriptions);
1049 if (count > 0 && n < count)
1050 {
1051 filter = filters[n];
1052 description = descriptions[n];
1053 return TRUE;
1054 }
1055
1056 return FALSE;
1057 }
1058
1059 // Parses the global filter, returning the number of filters.
1060 // Returns 0 if none or if there's a problem.
1061 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpg"
1062
1063 int wxGenericDirCtrl::ParseFilter(const wxString& filterStr, wxArrayString& filters, wxArrayString& descriptions)
1064 {
1065 return wxFileDialogBase::ParseWildcard(filterStr, descriptions, filters );
1066 }
1067
1068 void wxGenericDirCtrl::DoResize()
1069 {
1070 wxSize sz = GetClientSize();
1071 int verticalSpacing = 3;
1072 if (m_treeCtrl)
1073 {
1074 wxSize filterSz ;
1075 if (m_filterListCtrl)
1076 {
1077 #ifdef __WXMSW__
1078 // For some reason, this is required in order for the
1079 // correct control height to always be returned, rather
1080 // than the drop-down list height which is sometimes returned.
1081 wxSize oldSize = m_filterListCtrl->GetSize();
1082 m_filterListCtrl->SetSize(-1, -1, oldSize.x+10, -1, wxSIZE_USE_EXISTING);
1083 m_filterListCtrl->SetSize(-1, -1, oldSize.x, -1, wxSIZE_USE_EXISTING);
1084 #endif
1085 filterSz = m_filterListCtrl->GetSize();
1086 sz.y -= (filterSz.y + verticalSpacing);
1087 }
1088 m_treeCtrl->SetSize(0, 0, sz.x, sz.y);
1089 if (m_filterListCtrl)
1090 {
1091 m_filterListCtrl->SetSize(0, sz.y + verticalSpacing, sz.x, filterSz.y);
1092 // Don't know why, but this needs refreshing after a resize (wxMSW)
1093 m_filterListCtrl->Refresh();
1094 }
1095 }
1096 }
1097
1098
1099 void wxGenericDirCtrl::OnSize(wxSizeEvent& WXUNUSED(event))
1100 {
1101 DoResize();
1102 }
1103
1104 wxTreeItemId wxGenericDirCtrl::AppendItem (const wxTreeItemId & parent,
1105 const wxString & text,
1106 int image, int selectedImage,
1107 wxTreeItemData * data)
1108 {
1109 wxTreeCtrl *treeCtrl = GetTreeCtrl ();
1110
1111 wxASSERT (treeCtrl);
1112
1113 if (treeCtrl)
1114 {
1115 return treeCtrl->AppendItem (parent, text, image, selectedImage, data);
1116 }
1117 else
1118 {
1119 return wxTreeItemId();
1120 }
1121 }
1122
1123
1124 //-----------------------------------------------------------------------------
1125 // wxDirFilterListCtrl
1126 //-----------------------------------------------------------------------------
1127
1128 IMPLEMENT_CLASS(wxDirFilterListCtrl, wxChoice)
1129
1130 BEGIN_EVENT_TABLE(wxDirFilterListCtrl, wxChoice)
1131 EVT_CHOICE(-1, wxDirFilterListCtrl::OnSelFilter)
1132 END_EVENT_TABLE()
1133
1134 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl* parent, const wxWindowID id,
1135 const wxPoint& pos,
1136 const wxSize& size,
1137 long style)
1138 {
1139 m_dirCtrl = parent;
1140 return wxChoice::Create(parent, id, pos, size, 0, NULL, style);
1141 }
1142
1143 void wxDirFilterListCtrl::Init()
1144 {
1145 m_dirCtrl = NULL;
1146 }
1147
1148 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent& WXUNUSED(event))
1149 {
1150 int sel = GetSelection();
1151
1152 wxString currentPath = m_dirCtrl->GetPath();
1153
1154 m_dirCtrl->SetFilterIndex(sel);
1155
1156 // If the filter has changed, the view is out of date, so
1157 // collapse the tree.
1158 m_dirCtrl->ReCreateTree();
1159
1160 // Try to restore the selection, or at least the directory
1161 m_dirCtrl->ExpandPath(currentPath);
1162 }
1163
1164 void wxDirFilterListCtrl::FillFilterList(const wxString& filter, int defaultFilter)
1165 {
1166 Clear();
1167 wxArrayString descriptions, filters;
1168 size_t n = (size_t) m_dirCtrl->ParseFilter(filter, filters, descriptions);
1169
1170 if (n > 0 && defaultFilter < (int) n)
1171 {
1172 size_t i = 0;
1173 for (i = 0; i < n; i++)
1174 Append(descriptions[i]);
1175 SetSelection(defaultFilter);
1176 }
1177 }
1178
1179
1180 // ----------------------------------------------------------------------------
1181 // wxFileIconsTable icons
1182 // ----------------------------------------------------------------------------
1183
1184 /* Open folder */
1185 static const char * file_icons_tbl_folder_open_xpm[] = {
1186 /* width height ncolors chars_per_pixel */
1187 "16 16 6 1",
1188 /* colors */
1189 " s None c None",
1190 ". c #000000",
1191 "+ c #c0c0c0",
1192 "@ c #808080",
1193 "# c #ffff00",
1194 "$ c #ffffff",
1195 /* pixels */
1196 " ",
1197 " @@@@@ ",
1198 " @$$$$$@ ",
1199 " @$#+#+#$@@@@@@ ",
1200 " @$+#+#+$$$$$$@.",
1201 " @$#+#+#+#+#+#@.",
1202 "@@@@@@@@@@@@@#@.",
1203 "@$$$$$$$$$$@@+@.",
1204 "@$#+#+#+#+##.@@.",
1205 " @$#+#+#+#+#+.@.",
1206 " @$+#+#+#+#+#.@.",
1207 " @$+#+#+#+##@..",
1208 " @@@@@@@@@@@@@.",
1209 " .............",
1210 " ",
1211 " "};
1212
1213 /* Computer */
1214 static const char * file_icons_tbl_computer_xpm[] = {
1215 "16 16 7 1",
1216 " s None c None",
1217 ". c #808080",
1218 "X c #c0c0c0",
1219 "o c Black",
1220 "O c Gray100",
1221 "+ c #008080",
1222 "@ c Blue",
1223 " ........... ",
1224 " .XXXXXXXXXX.o",
1225 " .OOOOOOOOO..o",
1226 " .OoooooooX..o",
1227 " .Oo+...@+X..o",
1228 " .Oo+XXX.+X..o",
1229 " .Oo+....+X..o",
1230 " .Oo++++++X..o",
1231 " .OXXXXXXXX.oo",
1232 " ..........o.o",
1233 " ...........Xo",
1234 " .XXXXXXXXXX.o",
1235 " .o.o.o.o.o...o",
1236 " .oXoXoXoXoXo.o ",
1237 ".XOXXXXXXXXX.o ",
1238 "............o "};
1239
1240 /* Drive */
1241 static const char * file_icons_tbl_drive_xpm[] = {
1242 "16 16 7 1",
1243 " s None c None",
1244 ". c #808080",
1245 "X c #c0c0c0",
1246 "o c Black",
1247 "O c Gray100",
1248 "+ c Green",
1249 "@ c #008000",
1250 " ",
1251 " ",
1252 " ",
1253 " ",
1254 " ............. ",
1255 " .XXXXXXXXXXXX.o",
1256 ".OOOOOOOOOOOO..o",
1257 ".XXXXXXXXX+@X..o",
1258 ".XXXXXXXXXXXX..o",
1259 ".X..........X..o",
1260 ".XOOOOOOOOOOX..o",
1261 "..............o ",
1262 " ooooooooooooo ",
1263 " ",
1264 " ",
1265 " "};
1266
1267 /* CD-ROM */
1268 static const char *file_icons_tbl_cdrom_xpm[] = {
1269 "16 16 10 1",
1270 " s None c None",
1271 ". c #808080",
1272 "X c #c0c0c0",
1273 "o c Yellow",
1274 "O c Blue",
1275 "+ c Black",
1276 "@ c Gray100",
1277 "# c #008080",
1278 "$ c Green",
1279 "% c #008000",
1280 " ... ",
1281 " ..XoX.. ",
1282 " .O.XoXXX+ ",
1283 " ...O.oXXXX+ ",
1284 " .O..X.XXXX+ ",
1285 " ....X.+..XXX+",
1286 " .XXX.+@+.XXX+",
1287 " .X@XX.+.X@@X+",
1288 " .....X...#XX@+ ",
1289 ".@@@...XXo.O@X+ ",
1290 ".@XXX..XXoXOO+ ",
1291 ".@++++..XoX+++ ",
1292 ".@$%@@XX+++X.+ ",
1293 ".............+ ",
1294 " ++++++++++++ ",
1295 " "};
1296
1297 /* Floppy */
1298 static const char * file_icons_tbl_floppy_xpm[] = {
1299 "16 16 7 1",
1300 " s None c None",
1301 ". c #808080",
1302 "X c Gray100",
1303 "o c #c0c0c0",
1304 "O c Black",
1305 "+ c Cyan",
1306 "@ c Red",
1307 " ......X",
1308 " .ooooooO",
1309 " .+++++OO",
1310 " .++++++O",
1311 " .++++++O",
1312 " .ooooooO",
1313 " .......o....oO",
1314 " .oooooo.o.O.XoO",
1315 ".XXXXXXXXOOOOOO ",
1316 ".ooooooooo@o..O ",
1317 ".ooo....oooo..O ",
1318 ".o..OOOO...o..O ",
1319 ".oooXXXXoooo..O ",
1320 ".............O ",
1321 " OOOOOOOOOOOO ",
1322 " "};
1323
1324 /* Removeable */
1325 static const char * file_icons_tbl_removeable_xpm[] = {
1326 "16 16 7 1",
1327 " s None c None",
1328 ". c #808080",
1329 "X c #c0c0c0",
1330 "o c Black",
1331 "O c Gray100",
1332 "+ c Red",
1333 "@ c #800000",
1334 " ",
1335 " ",
1336 " ",
1337 " ............. ",
1338 " .XXXXXXXXXXXX.o",
1339 ".OOOOOOOOOOOO..o",
1340 ".OXXXXXXXXXXX..o",
1341 ".O+@.oooooo.X..o",
1342 ".OXXOooooooOX..o",
1343 ".OXXXOOOOOOXX..o",
1344 ".OXXXXXXXXXXX..o",
1345 ".O............o ",
1346 " ooooooooooooo ",
1347 " ",
1348 " ",
1349 " "};
1350
1351 // ----------------------------------------------------------------------------
1352 // wxFileIconsTable & friends
1353 // ----------------------------------------------------------------------------
1354
1355 // global instance of a wxFileIconsTable
1356 wxFileIconsTable* wxTheFileIconsTable = (wxFileIconsTable *)NULL;
1357
1358 // A module to allow icons table cleanup
1359
1360 class wxFileIconsTableModule: public wxModule
1361 {
1362 DECLARE_DYNAMIC_CLASS(wxFileIconsTableModule)
1363 public:
1364 wxFileIconsTableModule() {}
1365 bool OnInit() { wxTheFileIconsTable = new wxFileIconsTable; return TRUE; }
1366 void OnExit()
1367 {
1368 if (wxTheFileIconsTable)
1369 {
1370 delete wxTheFileIconsTable;
1371 wxTheFileIconsTable = NULL;
1372 }
1373 }
1374 };
1375
1376 IMPLEMENT_DYNAMIC_CLASS(wxFileIconsTableModule, wxModule)
1377
1378 class wxFileIconEntry : public wxObject
1379 {
1380 public:
1381 wxFileIconEntry(int i) { id = i; }
1382
1383 int id;
1384 };
1385
1386 wxFileIconsTable::wxFileIconsTable()
1387 {
1388 m_HashTable = NULL;
1389 m_smallImageList = NULL;
1390 }
1391
1392 wxFileIconsTable::~wxFileIconsTable()
1393 {
1394 if (m_HashTable)
1395 {
1396 WX_CLEAR_HASH_TABLE(*m_HashTable);
1397 delete m_HashTable;
1398 }
1399 if (m_smallImageList) delete m_smallImageList;
1400 }
1401
1402 // delayed initialization - wait until first use (wxArtProv not created yet)
1403 void wxFileIconsTable::Create()
1404 {
1405 wxCHECK_RET(!m_smallImageList && !m_HashTable, wxT("creating icons twice"));
1406 m_HashTable = new wxHashTable(wxKEY_STRING);
1407 m_smallImageList = new wxImageList(16, 16);
1408
1409 // folder:
1410 m_smallImageList->Add(wxArtProvider::GetBitmap(wxART_FOLDER, wxART_CMN_DIALOG));
1411 // folder_open
1412 m_smallImageList->Add(wxIcon(file_icons_tbl_folder_open_xpm));
1413 // computer
1414 m_smallImageList->Add(wxIcon(file_icons_tbl_computer_xpm));
1415 // drive
1416 m_smallImageList->Add(wxIcon(file_icons_tbl_drive_xpm));
1417 // cdrom
1418 m_smallImageList->Add(wxIcon(file_icons_tbl_cdrom_xpm));
1419 // floppy
1420 m_smallImageList->Add(wxIcon(file_icons_tbl_floppy_xpm));
1421 // removeable
1422 m_smallImageList->Add(wxIcon(file_icons_tbl_removeable_xpm));
1423 // file
1424 m_smallImageList->Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE, wxART_CMN_DIALOG));
1425 // executable
1426 if (GetIconID(wxEmptyString, _T("application/x-executable")) == file)
1427 {
1428 m_smallImageList->Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE, wxART_CMN_DIALOG));
1429 delete m_HashTable->Get(_T("exe"));
1430 m_HashTable->Delete(_T("exe"));
1431 m_HashTable->Put(_T("exe"), new wxFileIconEntry(executable));
1432 }
1433 /* else put into list by GetIconID
1434 (KDE defines application/x-executable for *.exe and has nice icon)
1435 */
1436 }
1437
1438 wxImageList *wxFileIconsTable::GetSmallImageList()
1439 {
1440 if (!m_smallImageList)
1441 Create();
1442
1443 return m_smallImageList;
1444 }
1445
1446 #if wxUSE_MIMETYPE
1447 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
1448 // one icon and we won't resize it
1449
1450 static wxBitmap CreateAntialiasedBitmap(const wxImage& img)
1451 {
1452 wxImage smallimg (16, 16);
1453 unsigned char *p1, *p2, *ps;
1454 unsigned char mr = img.GetMaskRed(),
1455 mg = img.GetMaskGreen(),
1456 mb = img.GetMaskBlue();
1457
1458 unsigned x, y;
1459 unsigned sr, sg, sb, smask;
1460
1461 p1 = img.GetData(), p2 = img.GetData() + 3 * 32, ps = smallimg.GetData();
1462 smallimg.SetMaskColour(mr, mr, mr);
1463
1464 for (y = 0; y < 16; y++)
1465 {
1466 for (x = 0; x < 16; x++)
1467 {
1468 sr = sg = sb = smask = 0;
1469 if (p1[0] != mr || p1[1] != mg || p1[2] != mb)
1470 sr += p1[0], sg += p1[1], sb += p1[2];
1471 else smask++;
1472 p1 += 3;
1473 if (p1[0] != mr || p1[1] != mg || p1[2] != mb)
1474 sr += p1[0], sg += p1[1], sb += p1[2];
1475 else smask++;
1476 p1 += 3;
1477 if (p2[0] != mr || p2[1] != mg || p2[2] != mb)
1478 sr += p2[0], sg += p2[1], sb += p2[2];
1479 else smask++;
1480 p2 += 3;
1481 if (p2[0] != mr || p2[1] != mg || p2[2] != mb)
1482 sr += p2[0], sg += p2[1], sb += p2[2];
1483 else smask++;
1484 p2 += 3;
1485
1486 if (smask > 2)
1487 ps[0] = ps[1] = ps[2] = mr;
1488 else
1489 ps[0] = sr >> 2, ps[1] = sg >> 2, ps[2] = sb >> 2;
1490 ps += 3;
1491 }
1492 p1 += 32 * 3, p2 += 32 * 3;
1493 }
1494
1495 return wxBitmap(smallimg);
1496 }
1497
1498 // finds empty borders and return non-empty area of image:
1499 static wxImage CutEmptyBorders(const wxImage& img)
1500 {
1501 unsigned char mr = img.GetMaskRed(),
1502 mg = img.GetMaskGreen(),
1503 mb = img.GetMaskBlue();
1504 unsigned char *dt = img.GetData(), *dttmp;
1505 unsigned w = img.GetWidth(), h = img.GetHeight();
1506
1507 unsigned top, bottom, left, right, i;
1508 bool empt;
1509
1510 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
1511 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = FALSE; break;}
1512
1513 for (empt = TRUE, top = 0; empt && top < h; top++)
1514 {
1515 MK_DTTMP(0, top);
1516 for (i = 0; i < w; i++, dttmp+=3)
1517 NOEMPTY_PIX(empt)
1518 }
1519 for (empt = TRUE, bottom = h-1; empt && bottom > top; bottom--)
1520 {
1521 MK_DTTMP(0, bottom);
1522 for (i = 0; i < w; i++, dttmp+=3)
1523 NOEMPTY_PIX(empt)
1524 }
1525 for (empt = TRUE, left = 0; empt && left < w; left++)
1526 {
1527 MK_DTTMP(left, 0);
1528 for (i = 0; i < h; i++, dttmp+=3*w)
1529 NOEMPTY_PIX(empt)
1530 }
1531 for (empt = TRUE, right = w-1; empt && right > left; right--)
1532 {
1533 MK_DTTMP(right, 0);
1534 for (i = 0; i < h; i++, dttmp+=3*w)
1535 NOEMPTY_PIX(empt)
1536 }
1537 top--, left--, bottom++, right++;
1538
1539 return img.GetSubImage(wxRect(left, top, right - left + 1, bottom - top + 1));
1540 }
1541 #endif // wxUSE_MIMETYPE
1542
1543 int wxFileIconsTable::GetIconID(const wxString& extension, const wxString& mime)
1544 {
1545 if (!m_smallImageList)
1546 Create();
1547
1548 #if wxUSE_MIMETYPE
1549 if (!extension.IsEmpty())
1550 {
1551 wxFileIconEntry *entry = (wxFileIconEntry*) m_HashTable->Get(extension);
1552 if (entry) return (entry -> id);
1553 }
1554
1555 wxFileType *ft = (mime.IsEmpty()) ?
1556 wxTheMimeTypesManager -> GetFileTypeFromExtension(extension) :
1557 wxTheMimeTypesManager -> GetFileTypeFromMimeType(mime);
1558
1559 wxIconLocation iconLoc;
1560 wxIcon ic;
1561 if ( ft && ft->GetIcon(&iconLoc) )
1562 {
1563 ic = wxIcon(iconLoc);
1564 }
1565
1566 delete ft;
1567
1568 if ( !ic.Ok() )
1569 {
1570 int newid = file;
1571 m_HashTable->Put(extension, new wxFileIconEntry(newid));
1572 return newid;
1573 }
1574
1575 wxBitmap tmpBmp;
1576 tmpBmp.CopyFromIcon(ic);
1577 wxImage img = tmpBmp.ConvertToImage();
1578
1579 int id = m_smallImageList->GetImageCount();
1580 if (img.GetWidth() == 16 && img.GetHeight() == 16)
1581 m_smallImageList->Add(wxBitmap(img));
1582 else
1583 {
1584 if (img.GetWidth() != 32 || img.GetHeight() != 32)
1585 m_smallImageList->Add(CreateAntialiasedBitmap(CutEmptyBorders(img).Rescale(32, 32)));
1586 else
1587 m_smallImageList->Add(CreateAntialiasedBitmap(img));
1588 }
1589 m_HashTable->Put(extension, new wxFileIconEntry(id));
1590 return id;
1591
1592 #else // !wxUSE_MIMETYPE
1593
1594 if (extension == wxT("exe"))
1595 return executable;
1596 else
1597 return file;
1598 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
1599 }
1600
1601 #endif // wxUSE_DIRDLG