1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxGenericDirCtrl
4 // Author: Harm van der Heijden, Robert Roebling, Julian Smart
8 // Copyright: (c) Harm van der Heijden, Robert Roebling and Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
13 #pragma implementation "dirctrlg.h"
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
25 #include "wx/generic/dirctrlg.h"
27 #include "wx/module.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"
38 #include "wx/imaglist.h"
42 #include "wx/tokenzr.h"
44 #include "wx/settings.h"
45 #include "wx/artprov.h"
47 #include "wx/mimetype.h"
49 #include "wx/choice.h"
50 #include "wx/filedlg.h" // for wxFileDialogBase::ParseWildcard
53 #include "wx/statline.h"
56 #if defined(__WXMAC__)
57 #include "wx/mac/private.h" // includes mac headers
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
66 #if !defined(__GNUWIN32__) || (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
67 #if !defined(__WXWINCE__)
76 #if defined(__OS2__) || defined(__DOS__)
86 extern bool wxIsDriveAvailable(const wxString
& dirName
);
89 #if defined(__WXMAC__)
91 # include "MoreFilesX.h"
93 # include "MoreFilesExtras.h"
101 // If compiled under Windows, this macro can cause problems
106 // ----------------------------------------------------------------------------
107 // wxGetAvailableDrives, for WINDOWS, DOS, OS2, MAC, UNIX (returns "/")
108 // ----------------------------------------------------------------------------
110 size_t wxGetAvailableDrives(wxArrayString
&paths
, wxArrayString
&names
, wxArrayInt
&icon_ids
)
112 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
115 // No logical drives; return "\"
116 paths
.Add(wxT("\\"));
117 names
.Add(wxT("\\"));
119 #elif defined(__WIN32__)
120 wxChar driveBuffer
[256];
121 size_t n
= (size_t) GetLogicalDriveStrings(255, driveBuffer
);
126 path
.Printf(wxT("%c:\\"), driveBuffer
[i
]);
127 name
.Printf(wxT("%c:"), driveBuffer
[i
]);
130 int driveType
= ::GetDriveType(path
);
133 case DRIVE_REMOVABLE
:
134 if (path
== wxT("a:\\") || path
== wxT("b:\\"))
135 imageId
= wxFileIconsTable::floppy
;
137 imageId
= wxFileIconsTable::removeable
;
140 imageId
= wxFileIconsTable::cdrom
;
145 imageId
= wxFileIconsTable::drive
;
151 icon_ids
.Add(imageId
);
153 while (driveBuffer
[i
] != wxT('\0'))
156 if (driveBuffer
[i
] == wxT('\0'))
159 #elif defined(__OS2__)
161 ULONG ulDriveNum
= 0;
162 ULONG ulDriveMap
= 0;
163 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
168 if (ulDriveMap
& ( 1 << i
))
171 path
.Printf(wxT("%c:\\"), 'A' + i
);
172 name
.Printf(wxT("%c:"), 'A' + i
);
175 if (path
== wxT("A:\\") || path
== wxT("B:\\"))
176 imageId
= wxFileIconsTable::floppy
;
178 imageId
= wxFileIconsTable::drive
;
181 icon_ids
.Add(imageId
);
186 #else // !__WIN32__, !__OS2__
189 /* If we can switch to the drive, it exists. */
190 for( drive
= 1; drive
<= 26; drive
++ )
193 path
.Printf(wxT("%c:\\"), (char) (drive
+ 'a' - 1));
194 name
.Printf(wxT("%c:"), (char) (drive
+ 'A' - 1));
196 if (wxIsDriveAvailable(path
))
200 icon_ids
.Add((drive
<= 2) ? wxFileIconsTable::floppy
: wxFileIconsTable::drive
);
203 #endif // __WIN32__/!__WIN32__
205 #elif defined(__WXMAC__)
208 ItemCount theVolCount
;
209 char thePath
[FILENAME_MAX
];
211 if (FSGetMountedVolumes(&theVolRefs
, &theVolCount
) == noErr
) {
213 ::HLock( (Handle
)theVolRefs
) ;
214 for (index
= 0; index
< theVolCount
; ++index
) {
215 // get the POSIX path associated with the FSRef
216 if ( FSRefMakePath(&((*theVolRefs
)[index
]),
217 (UInt8
*)thePath
, sizeof(thePath
)) != noErr
) {
220 // add path separator at end if necessary
221 wxString
path( thePath
, wxConvLocal
) ;
222 if (path
.Last() != wxFILE_SEP_PATH
) {
223 path
+= wxFILE_SEP_PATH
;
225 // get Mac volume name for display
226 FSVolumeRefNum vRefNum
;
227 HFSUniStr255 volumeName
;
229 if ( FSGetVRefNum(&((*theVolRefs
)[index
]), &vRefNum
) != noErr
) {
232 if ( FSGetVInfo(vRefNum
, &volumeName
, NULL
, NULL
) != noErr
) {
235 // get C string from Unicode HFS name
236 // see: http://developer.apple.com/carbon/tipsandtricks.html
237 CFStringRef cfstr
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
240 // Do something with str
241 char *cstr
= NewPtr(CFStringGetLength(cfstr
) + 1);
242 if (( cstr
== NULL
) ||
243 !CFStringGetCString(cfstr
, cstr
, CFStringGetLength(cfstr
) + 1,
244 kCFStringEncodingMacRoman
))
249 wxString
name( cstr
, wxConvLocal
);
253 GetVolParmsInfoBuffer volParmsInfo
;
255 if ( FSGetVolParms(vRefNum
, sizeof(volParmsInfo
), &volParmsInfo
, &actualSize
) != noErr
) {
262 if ( VolIsEjectable(&volParmsInfo
) )
263 icon_ids
.Add(wxFileIconsTable::cdrom
);
265 icon_ids
.Add(wxFileIconsTable::drive
);
267 ::HUnlock( (Handle
)theVolRefs
);
268 ::DisposeHandle( (Handle
)theVolRefs
);
275 short actualCount
= 0 ;
276 if (OnLine(&volume
, 1, &actualCount
, &index
) != noErr
|| actualCount
==0)
281 wxString name
= wxMacFSSpec2MacFilename( &volume
);
282 paths
.Add(name
+ wxFILE_SEP_PATH
);
284 icon_ids
.Add(wxFileIconsTable::drive
);
288 #elif defined(__UNIX__)
291 icon_ids
.Add(wxFileIconsTable::computer
);
293 #error "Unsupported platform in wxGenericDirCtrl!"
295 return paths
.GetCount();
298 // ----------------------------------------------------------------------------
299 // wxIsDriveAvailable
300 // ----------------------------------------------------------------------------
304 bool wxIsDriveAvailable(const wxString
& dirName
)
306 // FIXME_MGL - this method leads to hang up under Watcom for some reason
308 if ( dirName
.Len() == 3 && dirName
[1u] == wxT(':') )
310 wxString
dirNameLower(dirName
.Lower());
311 // VS: always return TRUE for removable media, since Win95 doesn't
312 // like it when MS-DOS app accesses empty floppy drive
313 return (dirNameLower
[0u] == wxT('a') ||
314 dirNameLower
[0u] == wxT('b') ||
315 wxPathExists(dirNameLower
));
322 #elif defined(__WINDOWS__) || defined(__OS2__)
324 int setdrive(int drive
)
328 #elif defined(__GNUWIN32__) && \
329 (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
330 return _chdrive(drive
);
334 if (drive
< 1 || drive
> 31)
336 newdrive
[0] = (wxChar
)(wxT('A') + drive
- 1);
337 newdrive
[1] = wxT(':');
339 newdrive
[2] = wxT('\\');
340 newdrive
[3] = wxT('\0');
342 newdrive
[2] = wxT('\0');
344 #if defined(__WXMSW__)
345 if (::SetCurrentDirectory(newdrive
))
347 // VA doesn't know what LPSTR is and has its own set
348 if (!DosSetCurrentDir((PSZ
)newdrive
))
356 bool wxIsDriveAvailable(const wxString
& dirName
)
362 UINT errorMode
= SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOOPENFILEERRORBOX
);
366 // Check if this is a root directory and if so,
367 // whether the drive is available.
368 if (dirName
.Len() == 3 && dirName
[(size_t)1] == wxT(':'))
370 wxString
dirNameLower(dirName
.Lower());
371 #if defined(__GNUWIN32__) && !(defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
372 success
= wxPathExists(dirNameLower
);
375 // Avoid changing to drive since no media may be inserted.
376 if (dirNameLower
[(size_t)0] == 'a' || dirNameLower
[(size_t)0] == 'b')
379 int currentDrive
= _getdrive();
380 int thisDrive
= (int) (dirNameLower
[(size_t)0] - 'a' + 1) ;
381 int err
= setdrive( thisDrive
) ;
382 setdrive( currentDrive
);
391 (void) SetErrorMode(errorMode
);
397 #endif // __WINDOWS__ || __OS2__
400 // Function which is called by quick sort. We want to override the default wxArrayString behaviour,
401 // and sort regardless of case.
402 static int wxCMPFUNC_CONV
wxDirCtrlStringCompareFunction(wxString
* strFirst
, wxString
* strSecond
)
404 return strFirst
->CmpNoCase(*strSecond
);
407 //-----------------------------------------------------------------------------
409 //-----------------------------------------------------------------------------
411 wxDirItemData::wxDirItemData(const wxString
& path
, const wxString
& name
,
416 /* Insert logic to detect hidden files here
417 * In UnixLand we just check whether the first char is a dot
418 * For FileNameFromPath read LastDirNameInThisPath ;-) */
419 // m_isHidden = (bool)(wxFileNameFromPath(*m_path)[0] == '.');
421 m_isExpanded
= FALSE
;
425 wxDirItemData::~wxDirItemData()
429 void wxDirItemData::SetNewDirName(const wxString
& path
)
432 m_name
= wxFileNameFromPath(path
);
435 bool wxDirItemData::HasSubDirs() const
437 if (m_path
.IsEmpty())
443 if ( !dir
.Open(m_path
) )
447 return dir
.HasSubDirs();
450 bool wxDirItemData::HasFiles(const wxString
& WXUNUSED(spec
)) const
452 if (m_path
.IsEmpty())
458 if ( !dir
.Open(m_path
) )
462 return dir
.HasFiles();
465 //-----------------------------------------------------------------------------
467 //-----------------------------------------------------------------------------
470 #if wxUSE_EXTENDED_RTTI
471 WX_DEFINE_FLAGS( wxGenericDirCtrlStyle
)
473 wxBEGIN_FLAGS( wxGenericDirCtrlStyle
)
474 // new style border flags, we put them first to
475 // use them for streaming out
476 wxFLAGS_MEMBER(wxBORDER_SIMPLE
)
477 wxFLAGS_MEMBER(wxBORDER_SUNKEN
)
478 wxFLAGS_MEMBER(wxBORDER_DOUBLE
)
479 wxFLAGS_MEMBER(wxBORDER_RAISED
)
480 wxFLAGS_MEMBER(wxBORDER_STATIC
)
481 wxFLAGS_MEMBER(wxBORDER_NONE
)
483 // old style border flags
484 wxFLAGS_MEMBER(wxSIMPLE_BORDER
)
485 wxFLAGS_MEMBER(wxSUNKEN_BORDER
)
486 wxFLAGS_MEMBER(wxDOUBLE_BORDER
)
487 wxFLAGS_MEMBER(wxRAISED_BORDER
)
488 wxFLAGS_MEMBER(wxSTATIC_BORDER
)
489 wxFLAGS_MEMBER(wxBORDER
)
491 // standard window styles
492 wxFLAGS_MEMBER(wxTAB_TRAVERSAL
)
493 wxFLAGS_MEMBER(wxCLIP_CHILDREN
)
494 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW
)
495 wxFLAGS_MEMBER(wxWANTS_CHARS
)
496 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE
)
497 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB
)
498 wxFLAGS_MEMBER(wxVSCROLL
)
499 wxFLAGS_MEMBER(wxHSCROLL
)
501 wxFLAGS_MEMBER(wxDIRCTRL_DIR_ONLY
)
502 wxFLAGS_MEMBER(wxDIRCTRL_3D_INTERNAL
)
503 wxFLAGS_MEMBER(wxDIRCTRL_SELECT_FIRST
)
504 wxFLAGS_MEMBER(wxDIRCTRL_SHOW_FILTERS
)
506 wxEND_FLAGS( wxGenericDirCtrlStyle
)
508 IMPLEMENT_DYNAMIC_CLASS_XTI(wxGenericDirCtrl
, wxControl
,"wx/dirctrl.h")
510 wxBEGIN_PROPERTIES_TABLE(wxGenericDirCtrl
)
511 wxHIDE_PROPERTY( Children
)
512 wxPROPERTY( DefaultPath
, wxString
, SetDefaultPath
, GetDefaultPath
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
513 wxPROPERTY( Filter
, wxString
, SetFilter
, GetFilter
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
514 wxPROPERTY( DefaultFilter
, int , SetFilterIndex
, GetFilterIndex
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
515 wxPROPERTY_FLAGS( WindowStyle
, wxGenericDirCtrlStyle
, long, SetWindowStyleFlag
, GetWindowStyleFlag
, EMPTY_MACROVALUE
, 0, wxT("Helpstring"), wxT("group") )
516 wxEND_PROPERTIES_TABLE()
518 wxBEGIN_HANDLERS_TABLE(wxGenericDirCtrl
)
519 wxEND_HANDLERS_TABLE()
521 wxCONSTRUCTOR_8( wxGenericDirCtrl
, wxWindow
* , Parent
, wxWindowID
, Id
, wxString
, DefaultPath
,
522 wxPoint
, Position
, wxSize
, Size
, long , WindowStyle
, wxString
, Filter
, int , DefaultFilter
)
524 IMPLEMENT_DYNAMIC_CLASS(wxGenericDirCtrl
, wxControl
)
527 BEGIN_EVENT_TABLE(wxGenericDirCtrl
, wxControl
)
528 EVT_TREE_ITEM_EXPANDING (wxID_TREECTRL
, wxGenericDirCtrl::OnExpandItem
)
529 EVT_TREE_ITEM_COLLAPSED (wxID_TREECTRL
, wxGenericDirCtrl::OnCollapseItem
)
530 EVT_TREE_BEGIN_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnBeginEditItem
)
531 EVT_TREE_END_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnEndEditItem
)
532 EVT_SIZE (wxGenericDirCtrl::OnSize
)
535 wxGenericDirCtrl::wxGenericDirCtrl(void)
540 bool wxGenericDirCtrl::Create(wxWindow
*parent
,
546 const wxString
& filter
,
548 const wxString
& name
)
550 if (!wxControl::Create(parent
, id
, pos
, size
, style
, wxDefaultValidator
, name
))
553 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE
));
557 long treeStyle
= wxTR_HAS_BUTTONS
| wxTR_HIDE_ROOT
;
559 if (style
& wxDIRCTRL_EDIT_LABELS
)
560 treeStyle
|= wxTR_EDIT_LABELS
;
562 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
563 treeStyle
|= wxNO_BORDER
;
565 treeStyle
|= wxBORDER_SUNKEN
;
567 long filterStyle
= 0;
568 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
569 filterStyle
|= wxNO_BORDER
;
571 filterStyle
|= wxBORDER_SUNKEN
;
573 m_treeCtrl
= new wxTreeCtrl(this, wxID_TREECTRL
, pos
, size
, treeStyle
);
575 if (!filter
.IsEmpty() && (style
& wxDIRCTRL_SHOW_FILTERS
))
576 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
, wxDefaultPosition
, wxDefaultSize
, filterStyle
);
581 SetFilterIndex(defaultFilter
);
583 if (m_filterListCtrl
)
584 m_filterListCtrl
->FillFilterList(filter
, defaultFilter
);
586 m_treeCtrl
->SetImageList(wxTheFileIconsTable
->GetSmallImageList());
588 m_showHidden
= FALSE
;
589 wxDirItemData
* rootData
= new wxDirItemData(wxT(""), wxT(""), TRUE
);
593 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
594 rootName
= _("Computer");
596 rootName
= _("Sections");
599 m_rootId
= m_treeCtrl
->AddRoot( rootName
, 3, -1, rootData
);
600 m_treeCtrl
->SetItemHasChildren(m_rootId
);
601 ExpandDir(m_rootId
); // automatically expand first level
603 // Expand and select the default path
604 if (!m_defaultPath
.IsEmpty())
605 ExpandPath(m_defaultPath
);
613 wxGenericDirCtrl::~wxGenericDirCtrl()
617 void wxGenericDirCtrl::Init()
619 m_showHidden
= FALSE
;
621 m_currentFilterStr
= wxEmptyString
; // Default: any file
623 m_filterListCtrl
= NULL
;
626 void wxGenericDirCtrl::ShowHidden( bool show
)
630 wxString path
= GetPath();
636 wxGenericDirCtrl::AddSection(const wxString
& path
, const wxString
& name
, int imageId
)
638 wxDirItemData
*dir_item
= new wxDirItemData(path
,name
,TRUE
);
640 wxTreeItemId id
= AppendItem( m_rootId
, name
, imageId
, -1, dir_item
);
642 m_treeCtrl
->SetItemHasChildren(id
);
647 void wxGenericDirCtrl::SetupSections()
649 wxArrayString paths
, names
;
652 size_t n
, count
= wxGetAvailableDrives(paths
, names
, icons
);
654 for (n
= 0; n
< count
; n
++)
656 AddSection(paths
[n
], names
[n
], icons
[n
]);
660 void wxGenericDirCtrl::OnBeginEditItem(wxTreeEvent
&event
)
662 // don't rename the main entry "Sections"
663 if (event
.GetItem() == m_rootId
)
669 // don't rename the individual sections
670 if (m_treeCtrl
->GetItemParent( event
.GetItem() ) == m_rootId
)
677 void wxGenericDirCtrl::OnEndEditItem(wxTreeEvent
&event
)
679 if ((event
.GetLabel().IsEmpty()) ||
680 (event
.GetLabel() == _(".")) ||
681 (event
.GetLabel() == _("..")) ||
682 (event
.GetLabel().Find(wxT('/')) != wxNOT_FOUND
) ||
683 (event
.GetLabel().Find(wxT('\\')) != wxNOT_FOUND
) ||
684 (event
.GetLabel().Find(wxT('|')) != wxNOT_FOUND
))
686 wxMessageDialog
dialog(this, _("Illegal directory name."), _("Error"), wxOK
| wxICON_ERROR
);
692 wxTreeItemId id
= event
.GetItem();
693 wxDirItemData
*data
= (wxDirItemData
*)m_treeCtrl
->GetItemData( id
);
696 wxString
new_name( wxPathOnly( data
->m_path
) );
697 new_name
+= wxString(wxFILE_SEP_PATH
);
698 new_name
+= event
.GetLabel();
702 if (wxFileExists(new_name
))
704 wxMessageDialog
dialog(this, _("File name exists already."), _("Error"), wxOK
| wxICON_ERROR
);
709 if (wxRenameFile(data
->m_path
,new_name
))
711 data
->SetNewDirName( new_name
);
715 wxMessageDialog
dialog(this, _("Operation not permitted."), _("Error"), wxOK
| wxICON_ERROR
);
721 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent
&event
)
723 wxTreeItemId parentId
= event
.GetItem();
725 // VS: this is needed because the event handler is called from wxTreeCtrl
726 // ctor when wxTR_HIDE_ROOT was specified
728 if (!m_rootId
.IsOk())
730 m_rootId
= m_treeCtrl
->GetRootItem();
735 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent
&event
)
737 CollapseDir(event
.GetItem());
740 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId
)
744 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
745 if (!data
->m_isExpanded
)
748 data
->m_isExpanded
= FALSE
;
749 wxTreeItemIdValue cookie
;
750 /* Workaround because DeleteChildren has disapeared (why?) and
751 * CollapseAndReset doesn't work as advertised (deletes parent too) */
752 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
755 m_treeCtrl
->Delete(child
);
756 /* Not GetNextChild below, because the cookie mechanism can't
757 * handle disappearing children! */
758 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
762 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId
)
764 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
766 if (data
->m_isExpanded
)
769 data
->m_isExpanded
= TRUE
;
771 if (parentId
== m_treeCtrl
->GetRootItem())
779 wxString search
,path
,filename
;
781 wxString
dirName(data
->m_path
);
783 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
784 // Check if this is a root directory and if so,
785 // whether the drive is avaiable.
786 if (!wxIsDriveAvailable(dirName
))
788 data
->m_isExpanded
= FALSE
;
789 //wxMessageBox(wxT("Sorry, this drive is not available."));
794 // This may take a longish time. Go to busy cursor
797 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
798 if (dirName
.Last() == ':')
799 dirName
+= wxString(wxFILE_SEP_PATH
);
803 wxArrayString filenames
;
806 wxString eachFilename
;
813 int style
= wxDIR_DIRS
;
814 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
815 if (d
.GetFirst(& eachFilename
, wxEmptyString
, style
))
819 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
821 dirs
.Add(eachFilename
);
824 while (d
.GetNext(&eachFilename
));
827 dirs
.Sort(wxDirCtrlStringCompareFunction
);
829 // Now do the filenames -- but only if we're allowed to
830 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
838 int style
= wxDIR_FILES
;
839 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
840 // Process each filter (ex: "JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg")
841 wxStringTokenizer strTok
;
843 strTok
.SetString(m_currentFilterStr
,wxT(";"));
844 while(strTok
.HasMoreTokens())
846 curFilter
= strTok
.GetNextToken();
847 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, style
))
851 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
853 filenames
.Add(eachFilename
);
856 while (d
.GetNext(& eachFilename
));
860 filenames
.Sort(wxDirCtrlStringCompareFunction
);
863 // Add the sorted dirs
865 for (i
= 0; i
< dirs
.Count(); i
++)
867 wxString
eachFilename(dirs
[i
]);
869 if (!wxEndsWithPathSeparator(path
))
870 path
+= wxString(wxFILE_SEP_PATH
);
871 path
+= eachFilename
;
873 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,TRUE
);
874 wxTreeItemId id
= AppendItem( parentId
, eachFilename
,
875 wxFileIconsTable::folder
, -1, dir_item
);
876 m_treeCtrl
->SetItemImage( id
, wxFileIconsTable::folder_open
,
877 wxTreeItemIcon_Expanded
);
879 // Has this got any children? If so, make it expandable.
880 // (There are two situations when a dir has children: either it
881 // has subdirectories or it contains files that weren't filtered
882 // out. The latter only applies to dirctrl with files.)
883 if ( dir_item
->HasSubDirs() ||
884 (((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0) &&
885 dir_item
->HasFiles(m_currentFilterStr
)) )
887 m_treeCtrl
->SetItemHasChildren(id
);
891 // Add the sorted filenames
892 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
894 for (i
= 0; i
< filenames
.Count(); i
++)
896 wxString
eachFilename(filenames
[i
]);
898 if (!wxEndsWithPathSeparator(path
))
899 path
+= wxString(wxFILE_SEP_PATH
);
900 path
+= eachFilename
;
901 //path = dirName + wxString(wxT("/")) + eachFilename;
902 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,FALSE
);
903 int image_id
= wxFileIconsTable::file
;
904 if (eachFilename
.Find(wxT('.')) != wxNOT_FOUND
)
905 image_id
= wxTheFileIconsTable
->GetIconID(eachFilename
.AfterLast(wxT('.')));
906 (void) AppendItem( parentId
, eachFilename
, image_id
, -1, dir_item
);
911 void wxGenericDirCtrl::ReCreateTree()
913 CollapseDir(m_treeCtrl
->GetRootItem());
914 ExpandDir(m_treeCtrl
->GetRootItem());
917 // Find the child that matches the first part of 'path'.
918 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
919 // then the child for /usr is returned.
920 wxTreeItemId
wxGenericDirCtrl::FindChild(wxTreeItemId parentId
, const wxString
& path
, bool& done
)
922 wxString
path2(path
);
924 // Make sure all separators are as per the current platform
925 path2
.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH
));
926 path2
.Replace(wxT("/"), wxString(wxFILE_SEP_PATH
));
928 // Append a separator to foil bogus substring matching
929 path2
+= wxString(wxFILE_SEP_PATH
);
931 // In MSW or PM, case is not significant
932 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
936 wxTreeItemIdValue cookie
;
937 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
938 while (childId
.IsOk())
940 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
942 if (data
&& !data
->m_path
.IsEmpty())
944 wxString
childPath(data
->m_path
);
945 if (!wxEndsWithPathSeparator(childPath
))
946 childPath
+= wxString(wxFILE_SEP_PATH
);
948 // In MSW and PM, case is not significant
949 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
950 childPath
.MakeLower();
953 if (childPath
.Len() <= path2
.Len())
955 wxString path3
= path2
.Mid(0, childPath
.Len());
956 if (childPath
== path3
)
958 if (path3
.Len() == path2
.Len())
967 childId
= m_treeCtrl
->GetNextChild(parentId
, cookie
);
969 wxTreeItemId invalid
;
973 // Try to expand as much of the given path as possible,
974 // and select the given tree item.
975 bool wxGenericDirCtrl::ExpandPath(const wxString
& path
)
978 wxTreeItemId id
= FindChild(m_rootId
, path
, done
);
979 wxTreeItemId lastId
= id
; // The last non-zero id
980 while (id
.IsOk() && !done
)
984 id
= FindChild(id
, path
, done
);
990 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(lastId
);
993 m_treeCtrl
->Expand(lastId
);
995 if ((GetWindowStyle() & wxDIRCTRL_SELECT_FIRST
) && data
->m_isDir
)
997 // Find the first file in this directory
998 wxTreeItemIdValue cookie
;
999 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(lastId
, cookie
);
1000 bool selectedChild
= FALSE
;
1001 while (childId
.IsOk())
1003 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
1005 if (data
&& data
->m_path
!= wxT("") && !data
->m_isDir
)
1007 m_treeCtrl
->SelectItem(childId
);
1008 m_treeCtrl
->EnsureVisible(childId
);
1009 selectedChild
= TRUE
;
1012 childId
= m_treeCtrl
->GetNextChild(lastId
, cookie
);
1016 m_treeCtrl
->SelectItem(lastId
);
1017 m_treeCtrl
->EnsureVisible(lastId
);
1022 m_treeCtrl
->SelectItem(lastId
);
1023 m_treeCtrl
->EnsureVisible(lastId
);
1032 wxString
wxGenericDirCtrl::GetPath() const
1034 wxTreeItemId id
= m_treeCtrl
->GetSelection();
1037 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1038 return data
->m_path
;
1041 return wxEmptyString
;
1044 wxString
wxGenericDirCtrl::GetFilePath() const
1046 wxTreeItemId id
= m_treeCtrl
->GetSelection();
1049 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1051 return wxEmptyString
;
1053 return data
->m_path
;
1056 return wxEmptyString
;
1059 void wxGenericDirCtrl::SetPath(const wxString
& path
)
1061 m_defaultPath
= path
;
1068 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId id
, int dirFlags
, wxArrayString
& filenames
)
1070 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1072 // This may take a longish time. Go to busy cursor
1077 wxString search
,path
,filename
;
1079 wxString
dirName(data
->m_path
);
1081 #if defined(__WXMSW__) || defined(__OS2__)
1082 if (dirName
.Last() == ':')
1083 dirName
+= wxString(wxFILE_SEP_PATH
);
1087 wxString eachFilename
;
1094 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, dirFlags
))
1098 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
1100 filenames
.Add(eachFilename
);
1103 while (d
.GetNext(& eachFilename
)) ;
1109 void wxGenericDirCtrl::SetFilterIndex(int n
)
1111 m_currentFilter
= n
;
1114 if (ExtractWildcard(m_filter
, n
, f
, d
))
1115 m_currentFilterStr
= f
;
1117 m_currentFilterStr
= wxT("*.*");
1120 void wxGenericDirCtrl::SetFilter(const wxString
& filter
)
1125 if (ExtractWildcard(m_filter
, m_currentFilter
, f
, d
))
1126 m_currentFilterStr
= f
;
1128 m_currentFilterStr
= wxT("*.*");
1131 // Extract description and actual filter from overall filter string
1132 bool wxGenericDirCtrl::ExtractWildcard(const wxString
& filterStr
, int n
, wxString
& filter
, wxString
& description
)
1134 wxArrayString filters
, descriptions
;
1135 int count
= ParseFilter(filterStr
, filters
, descriptions
);
1136 if (count
> 0 && n
< count
)
1138 filter
= filters
[n
];
1139 description
= descriptions
[n
];
1146 // Parses the global filter, returning the number of filters.
1147 // Returns 0 if none or if there's a problem.
1148 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpg"
1150 int wxGenericDirCtrl::ParseFilter(const wxString
& filterStr
, wxArrayString
& filters
, wxArrayString
& descriptions
)
1152 return wxFileDialogBase::ParseWildcard(filterStr
, descriptions
, filters
);
1155 void wxGenericDirCtrl::DoResize()
1157 wxSize sz
= GetClientSize();
1158 int verticalSpacing
= 3;
1162 if (m_filterListCtrl
)
1165 // For some reason, this is required in order for the
1166 // correct control height to always be returned, rather
1167 // than the drop-down list height which is sometimes returned.
1168 wxSize oldSize
= m_filterListCtrl
->GetSize();
1169 m_filterListCtrl
->SetSize(-1, -1, oldSize
.x
+10, -1, wxSIZE_USE_EXISTING
);
1170 m_filterListCtrl
->SetSize(-1, -1, oldSize
.x
, -1, wxSIZE_USE_EXISTING
);
1172 filterSz
= m_filterListCtrl
->GetSize();
1173 sz
.y
-= (filterSz
.y
+ verticalSpacing
);
1175 m_treeCtrl
->SetSize(0, 0, sz
.x
, sz
.y
);
1176 if (m_filterListCtrl
)
1178 m_filterListCtrl
->SetSize(0, sz
.y
+ verticalSpacing
, sz
.x
, filterSz
.y
);
1179 // Don't know why, but this needs refreshing after a resize (wxMSW)
1180 m_filterListCtrl
->Refresh();
1186 void wxGenericDirCtrl::OnSize(wxSizeEvent
& WXUNUSED(event
))
1191 wxTreeItemId
wxGenericDirCtrl::AppendItem (const wxTreeItemId
& parent
,
1192 const wxString
& text
,
1193 int image
, int selectedImage
,
1194 wxTreeItemData
* data
)
1196 wxTreeCtrl
*treeCtrl
= GetTreeCtrl ();
1198 wxASSERT (treeCtrl
);
1202 return treeCtrl
->AppendItem (parent
, text
, image
, selectedImage
, data
);
1206 return wxTreeItemId();
1211 //-----------------------------------------------------------------------------
1212 // wxDirFilterListCtrl
1213 //-----------------------------------------------------------------------------
1215 IMPLEMENT_CLASS(wxDirFilterListCtrl
, wxChoice
)
1217 BEGIN_EVENT_TABLE(wxDirFilterListCtrl
, wxChoice
)
1218 EVT_CHOICE(-1, wxDirFilterListCtrl::OnSelFilter
)
1221 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl
* parent
, const wxWindowID id
,
1227 return wxChoice::Create(parent
, id
, pos
, size
, 0, NULL
, style
);
1230 void wxDirFilterListCtrl::Init()
1235 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent
& WXUNUSED(event
))
1237 int sel
= GetSelection();
1239 wxString currentPath
= m_dirCtrl
->GetPath();
1241 m_dirCtrl
->SetFilterIndex(sel
);
1243 // If the filter has changed, the view is out of date, so
1244 // collapse the tree.
1245 m_dirCtrl
->ReCreateTree();
1247 // Try to restore the selection, or at least the directory
1248 m_dirCtrl
->ExpandPath(currentPath
);
1251 void wxDirFilterListCtrl::FillFilterList(const wxString
& filter
, int defaultFilter
)
1254 wxArrayString descriptions
, filters
;
1255 size_t n
= (size_t) m_dirCtrl
->ParseFilter(filter
, filters
, descriptions
);
1257 if (n
> 0 && defaultFilter
< (int) n
)
1259 for (size_t i
= 0; i
< n
; i
++)
1260 Append(descriptions
[i
]);
1261 SetSelection(defaultFilter
);
1266 // ----------------------------------------------------------------------------
1267 // wxFileIconsTable icons
1268 // ----------------------------------------------------------------------------
1271 static const char * file_icons_tbl_folder_open_xpm
[] = {
1272 /* width height ncolors chars_per_pixel */
1300 static const char * file_icons_tbl_computer_xpm
[] = {
1327 static const char * file_icons_tbl_drive_xpm
[] = {
1354 static const char *file_icons_tbl_cdrom_xpm
[] = {
1384 static const char * file_icons_tbl_floppy_xpm
[] = {
1411 static const char * file_icons_tbl_removeable_xpm
[] = {
1437 // ----------------------------------------------------------------------------
1438 // wxFileIconsTable & friends
1439 // ----------------------------------------------------------------------------
1441 // global instance of a wxFileIconsTable
1442 wxFileIconsTable
* wxTheFileIconsTable
= (wxFileIconsTable
*)NULL
;
1444 // A module to allow icons table cleanup
1446 class wxFileIconsTableModule
: public wxModule
1448 DECLARE_DYNAMIC_CLASS(wxFileIconsTableModule
)
1450 wxFileIconsTableModule() {}
1451 bool OnInit() { wxTheFileIconsTable
= new wxFileIconsTable
; return TRUE
; }
1454 if (wxTheFileIconsTable
)
1456 delete wxTheFileIconsTable
;
1457 wxTheFileIconsTable
= NULL
;
1462 IMPLEMENT_DYNAMIC_CLASS(wxFileIconsTableModule
, wxModule
)
1464 class wxFileIconEntry
: public wxObject
1467 wxFileIconEntry(int i
) { id
= i
; }
1472 wxFileIconsTable::wxFileIconsTable()
1475 m_smallImageList
= NULL
;
1478 wxFileIconsTable::~wxFileIconsTable()
1482 WX_CLEAR_HASH_TABLE(*m_HashTable
);
1485 if (m_smallImageList
) delete m_smallImageList
;
1488 // delayed initialization - wait until first use (wxArtProv not created yet)
1489 void wxFileIconsTable::Create()
1491 wxCHECK_RET(!m_smallImageList
&& !m_HashTable
, wxT("creating icons twice"));
1492 m_HashTable
= new wxHashTable(wxKEY_STRING
);
1493 m_smallImageList
= new wxImageList(16, 16);
1496 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER
, wxART_CMN_DIALOG
));
1498 m_smallImageList
->Add(wxIcon(file_icons_tbl_folder_open_xpm
));
1500 m_smallImageList
->Add(wxIcon(file_icons_tbl_computer_xpm
));
1502 m_smallImageList
->Add(wxIcon(file_icons_tbl_drive_xpm
));
1504 m_smallImageList
->Add(wxIcon(file_icons_tbl_cdrom_xpm
));
1506 m_smallImageList
->Add(wxIcon(file_icons_tbl_floppy_xpm
));
1508 m_smallImageList
->Add(wxIcon(file_icons_tbl_removeable_xpm
));
1510 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE
, wxART_CMN_DIALOG
));
1512 if (GetIconID(wxEmptyString
, _T("application/x-executable")) == file
)
1514 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE
, wxART_CMN_DIALOG
));
1515 delete m_HashTable
->Get(_T("exe"));
1516 m_HashTable
->Delete(_T("exe"));
1517 m_HashTable
->Put(_T("exe"), new wxFileIconEntry(executable
));
1519 /* else put into list by GetIconID
1520 (KDE defines application/x-executable for *.exe and has nice icon)
1524 wxImageList
*wxFileIconsTable::GetSmallImageList()
1526 if (!m_smallImageList
)
1529 return m_smallImageList
;
1532 #if wxUSE_MIMETYPE && wxUSE_IMAGE
1533 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
1534 // one icon and we won't resize it
1536 static wxBitmap
CreateAntialiasedBitmap(const wxImage
& img
)
1538 const unsigned int size
= 16;
1540 wxImage
smallimg (size
, size
);
1541 unsigned char *p1
, *p2
, *ps
;
1542 unsigned char mr
= img
.GetMaskRed(),
1543 mg
= img
.GetMaskGreen(),
1544 mb
= img
.GetMaskBlue();
1547 unsigned sr
, sg
, sb
, smask
;
1549 p1
= img
.GetData(), p2
= img
.GetData() + 3 * size
*2, ps
= smallimg
.GetData();
1550 smallimg
.SetMaskColour(mr
, mr
, mr
);
1552 for (y
= 0; y
< size
; y
++)
1554 for (x
= 0; x
< size
; x
++)
1556 sr
= sg
= sb
= smask
= 0;
1557 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1558 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1561 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1562 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1565 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1566 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1569 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1570 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1575 ps
[0] = ps
[1] = ps
[2] = mr
;
1577 ps
[0] = sr
>> 2, ps
[1] = sg
>> 2, ps
[2] = sb
>> 2;
1580 p1
+= size
*2 * 3, p2
+= size
*2 * 3;
1583 return wxBitmap(smallimg
);
1586 // This function is currently not unused anymore
1588 // finds empty borders and return non-empty area of image:
1589 static wxImage
CutEmptyBorders(const wxImage
& img
)
1591 unsigned char mr
= img
.GetMaskRed(),
1592 mg
= img
.GetMaskGreen(),
1593 mb
= img
.GetMaskBlue();
1594 unsigned char *dt
= img
.GetData(), *dttmp
;
1595 unsigned w
= img
.GetWidth(), h
= img
.GetHeight();
1597 unsigned top
, bottom
, left
, right
, i
;
1600 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
1601 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = FALSE; break;}
1603 for (empt
= TRUE
, top
= 0; empt
&& top
< h
; top
++)
1606 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1609 for (empt
= TRUE
, bottom
= h
-1; empt
&& bottom
> top
; bottom
--)
1611 MK_DTTMP(0, bottom
);
1612 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1615 for (empt
= TRUE
, left
= 0; empt
&& left
< w
; left
++)
1618 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1621 for (empt
= TRUE
, right
= w
-1; empt
&& right
> left
; right
--)
1624 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1627 top
--, left
--, bottom
++, right
++;
1629 return img
.GetSubImage(wxRect(left
, top
, right
- left
+ 1, bottom
- top
+ 1));
1633 #endif // wxUSE_MIMETYPE
1635 int wxFileIconsTable::GetIconID(const wxString
& extension
, const wxString
& mime
)
1637 if (!m_smallImageList
)
1641 if (!extension
.IsEmpty())
1643 wxFileIconEntry
*entry
= (wxFileIconEntry
*) m_HashTable
->Get(extension
);
1644 if (entry
) return (entry
-> id
);
1647 wxFileType
*ft
= (mime
.IsEmpty()) ?
1648 wxTheMimeTypesManager
-> GetFileTypeFromExtension(extension
) :
1649 wxTheMimeTypesManager
-> GetFileTypeFromMimeType(mime
);
1651 wxIconLocation iconLoc
;
1656 if ( ft
&& ft
->GetIcon(&iconLoc
) )
1658 ic
= wxIcon( iconLoc
.GetFileName() );
1667 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1672 bmp
.CopyFromIcon(ic
);
1677 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1681 const unsigned int size
= 16;
1683 int id
= m_smallImageList
->GetImageCount();
1684 if ((bmp
.GetWidth() == (int) size
) && (bmp
.GetHeight() == (int) size
))
1686 m_smallImageList
->Add(bmp
);
1691 wxImage img
= bmp
.ConvertToImage();
1693 if ((img
.GetWidth() != size
*2) || (img
.GetHeight() != size
*2))
1694 // m_smallImageList->Add(CreateAntialiasedBitmap(CutEmptyBorders(img).Rescale(size*2, size*2)));
1695 m_smallImageList
->Add(CreateAntialiasedBitmap(img
.Rescale(size
*2, size
*2)));
1697 m_smallImageList
->Add(CreateAntialiasedBitmap(img
));
1699 #endif // wxUSE_IMAGE
1701 m_HashTable
->Put(extension
, new wxFileIconEntry(id
));
1704 #else // !wxUSE_MIMETYPE
1706 if (extension
== wxT("exe"))
1710 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
1713 #endif // wxUSE_DIRDLG