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__)
85 extern bool wxIsDriveAvailable(const wxString
& dirName
);
88 #if defined(__WXMAC__)
90 # include "MoreFilesX.h"
92 # include "MoreFilesExtras.h"
100 // If compiled under Windows, this macro can cause problems
105 // ----------------------------------------------------------------------------
106 // wxGetAvailableDrives, for WINDOWS, DOS, WXPM, MAC, UNIX (returns "/")
107 // ----------------------------------------------------------------------------
109 size_t wxGetAvailableDrives(wxArrayString
&paths
, wxArrayString
&names
, wxArrayInt
&icon_ids
)
111 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
114 // No logical drives; return "\"
115 paths
.Add(wxT("\\"));
116 names
.Add(wxT("\\"));
118 #elif defined(__WIN32__)
119 wxChar driveBuffer
[256];
120 size_t n
= (size_t) GetLogicalDriveStrings(255, driveBuffer
);
125 path
.Printf(wxT("%c:\\"), driveBuffer
[i
]);
126 name
.Printf(wxT("%c:"), driveBuffer
[i
]);
128 int imageId
= wxFileIconsTable::drive
;
129 int driveType
= ::GetDriveType(path
);
132 case DRIVE_REMOVABLE
:
133 if (path
== wxT("a:\\") || path
== wxT("b:\\"))
134 imageId
= wxFileIconsTable::floppy
;
136 imageId
= wxFileIconsTable::removeable
;
139 imageId
= wxFileIconsTable::cdrom
;
144 imageId
= wxFileIconsTable::drive
;
150 icon_ids
.Add(imageId
);
152 while (driveBuffer
[i
] != wxT('\0'))
155 if (driveBuffer
[i
] == wxT('\0'))
161 /* If we can switch to the drive, it exists. */
162 for( drive
= 1; drive
<= 26; drive
++ )
165 path
.Printf(wxT("%c:\\"), (char) (drive
+ 'a' - 1));
166 name
.Printf(wxT("%c:"), (char) (drive
+ 'A' - 1));
168 if (wxIsDriveAvailable(path
))
172 icon_ids
.Add((drive
<= 2) ? wxFileIconsTable::floppy
: wxFileIconsTable::drive
);
175 #endif // __WIN32__/!__WIN32__
177 #elif defined(__WXMAC__)
180 ItemCount theVolCount
;
181 char thePath
[FILENAME_MAX
];
183 if (FSGetMountedVolumes(&theVolRefs
, &theVolCount
) == noErr
) {
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
) {
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
;
197 // get Mac volume name for display
198 FSVolumeRefNum vRefNum
;
199 HFSUniStr255 volumeName
;
201 if ( FSGetVRefNum(&((*theVolRefs
)[index
]), &vRefNum
) != noErr
) {
204 if ( FSGetVInfo(vRefNum
, &volumeName
, NULL
, NULL
) != noErr
) {
207 // get C string from Unicode HFS name
208 // see: http://developer.apple.com/carbon/tipsandtricks.html
209 CFStringRef cfstr
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
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
))
221 wxString
name( cstr
, wxConvLocal
);
225 GetVolParmsInfoBuffer volParmsInfo
;
227 if ( FSGetVolParms(vRefNum
, sizeof(volParmsInfo
), &volParmsInfo
, &actualSize
) != noErr
) {
234 if ( VolIsEjectable(&volParmsInfo
) )
235 icon_ids
.Add(wxFileIconsTable::cdrom
);
237 icon_ids
.Add(wxFileIconsTable::drive
);
239 ::HUnlock( (Handle
)theVolRefs
);
240 ::DisposeHandle( (Handle
)theVolRefs
);
247 short actualCount
= 0 ;
248 if (OnLine(&volume
, 1, &actualCount
, &index
) != noErr
|| actualCount
==0)
253 wxString name
= wxMacFSSpec2MacFilename( &volume
);
254 paths
.Add(name
+ wxFILE_SEP_PATH
);
256 icon_ids
.Add(wxFileIconsTable::drive
);
260 #elif defined(__UNIX__)
263 icon_ids
.Add(wxFileIconsTable::computer
);
265 #error "Unsupported platform in wxGenericDirCtrl!"
267 return paths
.GetCount();
270 // ----------------------------------------------------------------------------
271 // wxIsDriveAvailable
272 // ----------------------------------------------------------------------------
276 bool wxIsDriveAvailable(const wxString
& dirName
)
278 // FIXME_MGL - this method leads to hang up under Watcom for some reason
280 if ( dirName
.Len() == 3 && dirName
[1u] == wxT(':') )
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
));
294 #elif defined(__WINDOWS__) || defined(__WXPM__)
296 int setdrive(int drive
)
300 #elif defined(__GNUWIN32__) && \
301 (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
302 return _chdrive(drive
);
306 if (drive
< 1 || drive
> 31)
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
))
314 // VA doesn't know what LPSTR is and has its own set
315 if (DosSetCurrentDir((PSZ
)newdrive
))
323 bool wxIsDriveAvailable(const wxString
& dirName
)
329 UINT errorMode
= SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOOPENFILEERRORBOX
);
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(':'))
337 wxString
dirNameLower(dirName
.Lower());
338 #if defined(__GNUWIN32__) && !(defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
339 success
= wxPathExists(dirNameLower
);
341 int currentDrive
= _getdrive();
342 int thisDrive
= (int) (dirNameLower
[(size_t)0] - 'a' + 1) ;
343 int err
= setdrive( thisDrive
) ;
344 setdrive( currentDrive
);
353 (void) SetErrorMode(errorMode
);
359 #endif // __WINDOWS__ || __WXPM__
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
)
366 return strFirst
->CmpNoCase(*strSecond
);
369 //-----------------------------------------------------------------------------
371 //-----------------------------------------------------------------------------
373 wxDirItemData::wxDirItemData(const wxString
& path
, const wxString
& 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] == '.');
383 m_isExpanded
= FALSE
;
387 wxDirItemData::~wxDirItemData()
391 void wxDirItemData::SetNewDirName(const wxString
& path
)
394 m_name
= wxFileNameFromPath(path
);
397 bool wxDirItemData::HasSubDirs() const
399 if (m_path
.IsEmpty())
405 if ( !dir
.Open(m_path
) )
409 return dir
.HasSubDirs();
412 bool wxDirItemData::HasFiles(const wxString
& WXUNUSED(spec
)) const
414 if (m_path
.IsEmpty())
420 if ( !dir
.Open(m_path
) )
424 return dir
.HasFiles();
427 //-----------------------------------------------------------------------------
429 //-----------------------------------------------------------------------------
432 #if wxUSE_EXTENDED_RTTI
433 IMPLEMENT_DYNAMIC_CLASS_XTI(wxGenericDirCtrl
, wxControl
,"wx/dirctrl.h")
435 WX_BEGIN_PROPERTIES_TABLE(wxGenericDirCtrl
)
436 WX_PROPERTY( DefaultPath
, wxString
, SetDefaultPath
, GetDefaultPath
, )
437 WX_PROPERTY( Filter
, wxString
, SetFilter
, GetFilter
, )
438 WX_PROPERTY( DefaultFilter
, int , SetFilterIndex
, GetFilterIndex
, )
439 WX_END_PROPERTIES_TABLE()
441 WX_BEGIN_HANDLERS_TABLE(wxGenericDirCtrl
)
442 WX_END_HANDLERS_TABLE()
444 WX_CONSTRUCTOR_8( wxGenericDirCtrl
, wxWindow
* , Parent
, wxWindowID
, Id
, wxString
, DefaultPath
,
445 wxPoint
, Position
, wxSize
, Size
, long , WindowStyle
, wxString
, Filter
, int , DefaultFilter
)
447 IMPLEMENT_DYNAMIC_CLASS(wxGenericDirCtrl
, wxControl
)
450 BEGIN_EVENT_TABLE(wxGenericDirCtrl
, wxControl
)
451 EVT_TREE_ITEM_EXPANDING (-1, wxGenericDirCtrl::OnExpandItem
)
452 EVT_TREE_ITEM_COLLAPSED (-1, wxGenericDirCtrl::OnCollapseItem
)
453 EVT_TREE_BEGIN_LABEL_EDIT (-1, wxGenericDirCtrl::OnBeginEditItem
)
454 EVT_TREE_END_LABEL_EDIT (-1, wxGenericDirCtrl::OnEndEditItem
)
455 EVT_SIZE (wxGenericDirCtrl::OnSize
)
458 wxGenericDirCtrl::wxGenericDirCtrl(void)
463 bool wxGenericDirCtrl::Create(wxWindow
*parent
,
469 const wxString
& filter
,
471 const wxString
& name
)
473 if (!wxControl::Create(parent
, id
, pos
, size
, style
, wxDefaultValidator
, name
))
476 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE
));
480 long treeStyle
= wxTR_HAS_BUTTONS
| wxTR_HIDE_ROOT
;
482 if (style
& wxDIRCTRL_EDIT_LABELS
)
483 treeStyle
|= wxTR_EDIT_LABELS
;
485 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
486 treeStyle
|= wxNO_BORDER
;
488 treeStyle
|= wxBORDER_SUNKEN
;
490 long filterStyle
= 0;
491 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
492 filterStyle
|= wxNO_BORDER
;
494 filterStyle
|= wxBORDER_SUNKEN
;
496 m_treeCtrl
= new wxTreeCtrl(this, wxID_TREECTRL
, pos
, size
, treeStyle
);
498 if (!filter
.IsEmpty() && (style
& wxDIRCTRL_SHOW_FILTERS
))
499 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
, wxDefaultPosition
, wxDefaultSize
, filterStyle
);
504 SetFilterIndex(defaultFilter
);
506 if (m_filterListCtrl
)
507 m_filterListCtrl
->FillFilterList(filter
, defaultFilter
);
509 m_treeCtrl
->SetImageList(wxTheFileIconsTable
->GetSmallImageList());
511 m_showHidden
= FALSE
;
512 wxDirItemData
* rootData
= new wxDirItemData(wxT(""), wxT(""), TRUE
);
516 #if defined(__WINDOWS__) || defined(__WXPM__) || defined(__DOS__)
517 rootName
= _("Computer");
519 rootName
= _("Sections");
522 m_rootId
= m_treeCtrl
->AddRoot( rootName
, 3, -1, rootData
);
523 m_treeCtrl
->SetItemHasChildren(m_rootId
);
524 ExpandDir(m_rootId
); // automatically expand first level
526 // Expand and select the default path
527 if (!m_defaultPath
.IsEmpty())
528 ExpandPath(m_defaultPath
);
535 wxGenericDirCtrl::~wxGenericDirCtrl()
539 void wxGenericDirCtrl::Init()
541 m_showHidden
= FALSE
;
543 m_currentFilterStr
= wxEmptyString
; // Default: any file
545 m_filterListCtrl
= NULL
;
548 void wxGenericDirCtrl::ShowHidden( bool show
)
552 wxString path
= GetPath();
558 wxGenericDirCtrl::AddSection(const wxString
& path
, const wxString
& name
, int imageId
)
560 wxDirItemData
*dir_item
= new wxDirItemData(path
,name
,TRUE
);
562 wxTreeItemId id
= AppendItem( m_rootId
, name
, imageId
, -1, dir_item
);
564 m_treeCtrl
->SetItemHasChildren(id
);
569 void wxGenericDirCtrl::SetupSections()
571 wxArrayString paths
, names
;
574 size_t n
, count
= wxGetAvailableDrives(paths
, names
, icons
);
576 for (n
= 0; n
< count
; n
++)
578 AddSection(paths
[n
], names
[n
], icons
[n
]);
582 void wxGenericDirCtrl::OnBeginEditItem(wxTreeEvent
&event
)
584 // don't rename the main entry "Sections"
585 if (event
.GetItem() == m_rootId
)
591 // don't rename the individual sections
592 if (m_treeCtrl
->GetItemParent( event
.GetItem() ) == m_rootId
)
599 void wxGenericDirCtrl::OnEndEditItem(wxTreeEvent
&event
)
601 if ((event
.GetLabel().IsEmpty()) ||
602 (event
.GetLabel() == _(".")) ||
603 (event
.GetLabel() == _("..")) ||
604 (event
.GetLabel().Find(wxT('/')) != wxNOT_FOUND
) ||
605 (event
.GetLabel().Find(wxT('\\')) != wxNOT_FOUND
) ||
606 (event
.GetLabel().Find(wxT('|')) != wxNOT_FOUND
))
608 wxMessageDialog
dialog(this, _("Illegal directory name."), _("Error"), wxOK
| wxICON_ERROR
);
614 wxTreeItemId id
= event
.GetItem();
615 wxDirItemData
*data
= (wxDirItemData
*)m_treeCtrl
->GetItemData( id
);
618 wxString
new_name( wxPathOnly( data
->m_path
) );
619 new_name
+= wxString(wxFILE_SEP_PATH
);
620 new_name
+= event
.GetLabel();
624 if (wxFileExists(new_name
))
626 wxMessageDialog
dialog(this, _("File name exists already."), _("Error"), wxOK
| wxICON_ERROR
);
631 if (wxRenameFile(data
->m_path
,new_name
))
633 data
->SetNewDirName( new_name
);
637 wxMessageDialog
dialog(this, _("Operation not permitted."), _("Error"), wxOK
| wxICON_ERROR
);
643 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent
&event
)
645 wxTreeItemId parentId
= event
.GetItem();
647 // VS: this is needed because the event handler is called from wxTreeCtrl
648 // ctor when wxTR_HIDE_ROOT was specified
650 if (!m_rootId
.IsOk())
652 m_rootId
= m_treeCtrl
->GetRootItem();
657 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent
&event
)
659 CollapseDir(event
.GetItem());
662 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId
)
666 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
667 if (!data
->m_isExpanded
)
670 data
->m_isExpanded
= FALSE
;
671 wxTreeItemIdValue cookie
;
672 /* Workaround because DeleteChildren has disapeared (why?) and
673 * CollapseAndReset doesn't work as advertised (deletes parent too) */
674 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
677 m_treeCtrl
->Delete(child
);
678 /* Not GetNextChild below, because the cookie mechanism can't
679 * handle disappearing children! */
680 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
684 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId
)
686 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
688 if (data
->m_isExpanded
)
691 data
->m_isExpanded
= TRUE
;
693 if (parentId
== m_treeCtrl
->GetRootItem())
701 wxString search
,path
,filename
;
703 wxString
dirName(data
->m_path
);
705 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
706 // Check if this is a root directory and if so,
707 // whether the drive is avaiable.
708 if (!wxIsDriveAvailable(dirName
))
710 data
->m_isExpanded
= FALSE
;
711 //wxMessageBox(wxT("Sorry, this drive is not available."));
716 // This may take a longish time. Go to busy cursor
719 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
720 if (dirName
.Last() == ':')
721 dirName
+= wxString(wxFILE_SEP_PATH
);
725 wxArrayString filenames
;
728 wxString eachFilename
;
735 int style
= wxDIR_DIRS
;
736 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
737 if (d
.GetFirst(& eachFilename
, wxEmptyString
, style
))
741 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
743 dirs
.Add(eachFilename
);
746 while (d
.GetNext(& eachFilename
));
749 dirs
.Sort(wxDirCtrlStringCompareFunction
);
751 // Now do the filenames -- but only if we're allowed to
752 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
760 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, wxDIR_FILES
))
764 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
766 filenames
.Add(eachFilename
);
769 while (d
.GetNext(& eachFilename
));
772 filenames
.Sort(wxDirCtrlStringCompareFunction
);
775 // Add the sorted dirs
777 for (i
= 0; i
< dirs
.Count(); i
++)
779 wxString
eachFilename(dirs
[i
]);
781 if (!wxEndsWithPathSeparator(path
))
782 path
+= wxString(wxFILE_SEP_PATH
);
783 path
+= eachFilename
;
785 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,TRUE
);
786 wxTreeItemId id
= AppendItem( parentId
, eachFilename
,
787 wxFileIconsTable::folder
, -1, dir_item
);
788 m_treeCtrl
->SetItemImage( id
, wxFileIconsTable::folder_open
,
789 wxTreeItemIcon_Expanded
);
791 // Has this got any children? If so, make it expandable.
792 // (There are two situations when a dir has children: either it
793 // has subdirectories or it contains files that weren't filtered
794 // out. The latter only applies to dirctrl with files.)
795 if ( dir_item
->HasSubDirs() ||
796 (((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0) &&
797 dir_item
->HasFiles(m_currentFilterStr
)) )
799 m_treeCtrl
->SetItemHasChildren(id
);
803 // Add the sorted filenames
804 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
806 for (i
= 0; i
< filenames
.Count(); i
++)
808 wxString
eachFilename(filenames
[i
]);
810 if (!wxEndsWithPathSeparator(path
))
811 path
+= wxString(wxFILE_SEP_PATH
);
812 path
+= eachFilename
;
813 //path = dirName + wxString(wxT("/")) + eachFilename;
814 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,FALSE
);
815 int image_id
= wxFileIconsTable::file
;
816 if (eachFilename
.Find(wxT('.')) != wxNOT_FOUND
)
817 image_id
= wxTheFileIconsTable
->GetIconID(eachFilename
.AfterLast(wxT('.')));
818 (void) AppendItem( parentId
, eachFilename
, image_id
, -1, dir_item
);
823 void wxGenericDirCtrl::ReCreateTree()
825 CollapseDir(m_treeCtrl
->GetRootItem());
826 ExpandDir(m_treeCtrl
->GetRootItem());
829 // Find the child that matches the first part of 'path'.
830 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
831 // then the child for /usr is returned.
832 wxTreeItemId
wxGenericDirCtrl::FindChild(wxTreeItemId parentId
, const wxString
& path
, bool& done
)
834 wxString
path2(path
);
836 // Make sure all separators are as per the current platform
837 path2
.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH
));
838 path2
.Replace(wxT("/"), wxString(wxFILE_SEP_PATH
));
840 // Append a separator to foil bogus substring matching
841 path2
+= wxString(wxFILE_SEP_PATH
);
843 // In MSW or PM, case is not significant
844 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
848 wxTreeItemIdValue cookie
;
849 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
850 while (childId
.IsOk())
852 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
854 if (data
&& !data
->m_path
.IsEmpty())
856 wxString
childPath(data
->m_path
);
857 if (!wxEndsWithPathSeparator(childPath
))
858 childPath
+= wxString(wxFILE_SEP_PATH
);
860 // In MSW and PM, case is not significant
861 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
862 childPath
.MakeLower();
865 if (childPath
.Len() <= path2
.Len())
867 wxString path3
= path2
.Mid(0, childPath
.Len());
868 if (childPath
== path3
)
870 if (path3
.Len() == path2
.Len())
879 childId
= m_treeCtrl
->GetNextChild(parentId
, cookie
);
881 wxTreeItemId invalid
;
885 // Try to expand as much of the given path as possible,
886 // and select the given tree item.
887 bool wxGenericDirCtrl::ExpandPath(const wxString
& path
)
890 wxTreeItemId id
= FindChild(m_rootId
, path
, done
);
891 wxTreeItemId lastId
= id
; // The last non-zero id
892 while (id
.IsOk() && !done
)
896 id
= FindChild(id
, path
, done
);
902 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(lastId
);
905 m_treeCtrl
->Expand(lastId
);
907 if ((GetWindowStyle() & wxDIRCTRL_SELECT_FIRST
) && data
->m_isDir
)
909 // Find the first file in this directory
910 wxTreeItemIdValue cookie
;
911 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(lastId
, cookie
);
912 bool selectedChild
= FALSE
;
913 while (childId
.IsOk())
915 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
917 if (data
&& data
->m_path
!= wxT("") && !data
->m_isDir
)
919 m_treeCtrl
->SelectItem(childId
);
920 m_treeCtrl
->EnsureVisible(childId
);
921 selectedChild
= TRUE
;
924 childId
= m_treeCtrl
->GetNextChild(lastId
, cookie
);
928 m_treeCtrl
->SelectItem(lastId
);
929 m_treeCtrl
->EnsureVisible(lastId
);
934 m_treeCtrl
->SelectItem(lastId
);
935 m_treeCtrl
->EnsureVisible(lastId
);
944 wxString
wxGenericDirCtrl::GetPath() const
946 wxTreeItemId id
= m_treeCtrl
->GetSelection();
949 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
953 return wxEmptyString
;
956 wxString
wxGenericDirCtrl::GetFilePath() const
958 wxTreeItemId id
= m_treeCtrl
->GetSelection();
961 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
963 return wxEmptyString
;
968 return wxEmptyString
;
971 void wxGenericDirCtrl::SetPath(const wxString
& path
)
973 m_defaultPath
= path
;
980 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId id
, int dirFlags
, wxArrayString
& filenames
)
982 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
984 // This may take a longish time. Go to busy cursor
989 wxString search
,path
,filename
;
991 wxString
dirName(data
->m_path
);
993 #if defined(__WXMSW__) || defined(__WXPM__)
994 if (dirName
.Last() == ':')
995 dirName
+= wxString(wxFILE_SEP_PATH
);
999 wxString eachFilename
;
1006 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, dirFlags
))
1010 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
1012 filenames
.Add(eachFilename
);
1015 while (d
.GetNext(& eachFilename
)) ;
1021 void wxGenericDirCtrl::SetFilterIndex(int n
)
1023 m_currentFilter
= n
;
1026 if (ExtractWildcard(m_filter
, n
, f
, d
))
1027 m_currentFilterStr
= f
;
1029 m_currentFilterStr
= wxT("*.*");
1032 void wxGenericDirCtrl::SetFilter(const wxString
& filter
)
1037 if (ExtractWildcard(m_filter
, m_currentFilter
, f
, d
))
1038 m_currentFilterStr
= f
;
1040 m_currentFilterStr
= wxT("*.*");
1043 // Extract description and actual filter from overall filter string
1044 bool wxGenericDirCtrl::ExtractWildcard(const wxString
& filterStr
, int n
, wxString
& filter
, wxString
& description
)
1046 wxArrayString filters
, descriptions
;
1047 int count
= ParseFilter(filterStr
, filters
, descriptions
);
1048 if (count
> 0 && n
< count
)
1050 filter
= filters
[n
];
1051 description
= descriptions
[n
];
1058 // Parses the global filter, returning the number of filters.
1059 // Returns 0 if none or if there's a problem.
1060 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpg"
1062 int wxGenericDirCtrl::ParseFilter(const wxString
& filterStr
, wxArrayString
& filters
, wxArrayString
& descriptions
)
1064 return wxFileDialogBase::ParseWildcard(filterStr
, descriptions
, filters
);
1067 void wxGenericDirCtrl::DoResize()
1069 wxSize sz
= GetClientSize();
1070 int verticalSpacing
= 3;
1074 if (m_filterListCtrl
)
1077 // For some reason, this is required in order for the
1078 // correct control height to always be returned, rather
1079 // than the drop-down list height which is sometimes returned.
1080 wxSize oldSize
= m_filterListCtrl
->GetSize();
1081 m_filterListCtrl
->SetSize(-1, -1, oldSize
.x
+10, -1, wxSIZE_USE_EXISTING
);
1082 m_filterListCtrl
->SetSize(-1, -1, oldSize
.x
, -1, wxSIZE_USE_EXISTING
);
1084 filterSz
= m_filterListCtrl
->GetSize();
1085 sz
.y
-= (filterSz
.y
+ verticalSpacing
);
1087 m_treeCtrl
->SetSize(0, 0, sz
.x
, sz
.y
);
1088 if (m_filterListCtrl
)
1090 m_filterListCtrl
->SetSize(0, sz
.y
+ verticalSpacing
, sz
.x
, filterSz
.y
);
1091 // Don't know why, but this needs refreshing after a resize (wxMSW)
1092 m_filterListCtrl
->Refresh();
1098 void wxGenericDirCtrl::OnSize(wxSizeEvent
& WXUNUSED(event
))
1103 wxTreeItemId
wxGenericDirCtrl::AppendItem (const wxTreeItemId
& parent
,
1104 const wxString
& text
,
1105 int image
, int selectedImage
,
1106 wxTreeItemData
* data
)
1108 wxTreeCtrl
*treeCtrl
= GetTreeCtrl ();
1110 wxASSERT (treeCtrl
);
1114 return treeCtrl
->AppendItem (parent
, text
, image
, selectedImage
, data
);
1118 return wxTreeItemId();
1123 //-----------------------------------------------------------------------------
1124 // wxDirFilterListCtrl
1125 //-----------------------------------------------------------------------------
1127 IMPLEMENT_CLASS(wxDirFilterListCtrl
, wxChoice
)
1129 BEGIN_EVENT_TABLE(wxDirFilterListCtrl
, wxChoice
)
1130 EVT_CHOICE(-1, wxDirFilterListCtrl::OnSelFilter
)
1133 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl
* parent
, const wxWindowID id
,
1139 return wxChoice::Create(parent
, id
, pos
, size
, 0, NULL
, style
);
1142 void wxDirFilterListCtrl::Init()
1147 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent
& WXUNUSED(event
))
1149 int sel
= GetSelection();
1151 wxString currentPath
= m_dirCtrl
->GetPath();
1153 m_dirCtrl
->SetFilterIndex(sel
);
1155 // If the filter has changed, the view is out of date, so
1156 // collapse the tree.
1157 m_dirCtrl
->ReCreateTree();
1159 // Try to restore the selection, or at least the directory
1160 m_dirCtrl
->ExpandPath(currentPath
);
1163 void wxDirFilterListCtrl::FillFilterList(const wxString
& filter
, int defaultFilter
)
1166 wxArrayString descriptions
, filters
;
1167 size_t n
= (size_t) m_dirCtrl
->ParseFilter(filter
, filters
, descriptions
);
1169 if (n
> 0 && defaultFilter
< (int) n
)
1172 for (i
= 0; i
< n
; i
++)
1173 Append(descriptions
[i
]);
1174 SetSelection(defaultFilter
);
1179 // ----------------------------------------------------------------------------
1180 // wxFileIconsTable icons
1181 // ----------------------------------------------------------------------------
1184 static const char * file_icons_tbl_folder_open_xpm
[] = {
1185 /* width height ncolors chars_per_pixel */
1213 static const char * file_icons_tbl_computer_xpm
[] = {
1240 static const char * file_icons_tbl_drive_xpm
[] = {
1267 static const char *file_icons_tbl_cdrom_xpm
[] = {
1297 static const char * file_icons_tbl_floppy_xpm
[] = {
1324 static const char * file_icons_tbl_removeable_xpm
[] = {
1350 // ----------------------------------------------------------------------------
1351 // wxFileIconsTable & friends
1352 // ----------------------------------------------------------------------------
1354 // global instance of a wxFileIconsTable
1355 wxFileIconsTable
* wxTheFileIconsTable
= (wxFileIconsTable
*)NULL
;
1357 // A module to allow icons table cleanup
1359 class wxFileIconsTableModule
: public wxModule
1361 DECLARE_DYNAMIC_CLASS(wxFileIconsTableModule
)
1363 wxFileIconsTableModule() {}
1364 bool OnInit() { wxTheFileIconsTable
= new wxFileIconsTable
; return TRUE
; }
1367 if (wxTheFileIconsTable
)
1369 delete wxTheFileIconsTable
;
1370 wxTheFileIconsTable
= NULL
;
1375 IMPLEMENT_DYNAMIC_CLASS(wxFileIconsTableModule
, wxModule
)
1377 class wxFileIconEntry
: public wxObject
1380 wxFileIconEntry(int i
) { id
= i
; }
1385 wxFileIconsTable::wxFileIconsTable()
1388 m_smallImageList
= NULL
;
1391 wxFileIconsTable::~wxFileIconsTable()
1395 WX_CLEAR_HASH_TABLE(*m_HashTable
);
1398 if (m_smallImageList
) delete m_smallImageList
;
1401 // delayed initialization - wait until first use (wxArtProv not created yet)
1402 void wxFileIconsTable::Create()
1404 wxCHECK_RET(!m_smallImageList
&& !m_HashTable
, wxT("creating icons twice"));
1405 m_HashTable
= new wxHashTable(wxKEY_STRING
);
1406 m_smallImageList
= new wxImageList(16, 16);
1409 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER
, wxART_CMN_DIALOG
));
1411 m_smallImageList
->Add(wxIcon(file_icons_tbl_folder_open_xpm
));
1413 m_smallImageList
->Add(wxIcon(file_icons_tbl_computer_xpm
));
1415 m_smallImageList
->Add(wxIcon(file_icons_tbl_drive_xpm
));
1417 m_smallImageList
->Add(wxIcon(file_icons_tbl_cdrom_xpm
));
1419 m_smallImageList
->Add(wxIcon(file_icons_tbl_floppy_xpm
));
1421 m_smallImageList
->Add(wxIcon(file_icons_tbl_removeable_xpm
));
1423 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE
, wxART_CMN_DIALOG
));
1425 if (GetIconID(wxEmptyString
, _T("application/x-executable")) == file
)
1427 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE
, wxART_CMN_DIALOG
));
1428 delete m_HashTable
->Get(_T("exe"));
1429 m_HashTable
->Delete(_T("exe"));
1430 m_HashTable
->Put(_T("exe"), new wxFileIconEntry(executable
));
1432 /* else put into list by GetIconID
1433 (KDE defines application/x-executable for *.exe and has nice icon)
1437 wxImageList
*wxFileIconsTable::GetSmallImageList()
1439 if (!m_smallImageList
)
1442 return m_smallImageList
;
1446 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
1447 // one icon and we won't resize it
1449 static wxBitmap
CreateAntialiasedBitmap(const wxImage
& img
)
1451 wxImage
smallimg (16, 16);
1452 unsigned char *p1
, *p2
, *ps
;
1453 unsigned char mr
= img
.GetMaskRed(),
1454 mg
= img
.GetMaskGreen(),
1455 mb
= img
.GetMaskBlue();
1458 unsigned sr
, sg
, sb
, smask
;
1460 p1
= img
.GetData(), p2
= img
.GetData() + 3 * 32, ps
= smallimg
.GetData();
1461 smallimg
.SetMaskColour(mr
, mr
, mr
);
1463 for (y
= 0; y
< 16; y
++)
1465 for (x
= 0; x
< 16; x
++)
1467 sr
= sg
= sb
= smask
= 0;
1468 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1469 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1472 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1473 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1476 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1477 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1480 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1481 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1486 ps
[0] = ps
[1] = ps
[2] = mr
;
1488 ps
[0] = sr
>> 2, ps
[1] = sg
>> 2, ps
[2] = sb
>> 2;
1491 p1
+= 32 * 3, p2
+= 32 * 3;
1494 return wxBitmap(smallimg
);
1497 // finds empty borders and return non-empty area of image:
1498 static wxImage
CutEmptyBorders(const wxImage
& img
)
1500 unsigned char mr
= img
.GetMaskRed(),
1501 mg
= img
.GetMaskGreen(),
1502 mb
= img
.GetMaskBlue();
1503 unsigned char *dt
= img
.GetData(), *dttmp
;
1504 unsigned w
= img
.GetWidth(), h
= img
.GetHeight();
1506 unsigned top
, bottom
, left
, right
, i
;
1509 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
1510 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = FALSE; break;}
1512 for (empt
= TRUE
, top
= 0; empt
&& top
< h
; top
++)
1515 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1518 for (empt
= TRUE
, bottom
= h
-1; empt
&& bottom
> top
; bottom
--)
1520 MK_DTTMP(0, bottom
);
1521 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1524 for (empt
= TRUE
, left
= 0; empt
&& left
< w
; left
++)
1527 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1530 for (empt
= TRUE
, right
= w
-1; empt
&& right
> left
; right
--)
1533 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1536 top
--, left
--, bottom
++, right
++;
1538 return img
.GetSubImage(wxRect(left
, top
, right
- left
+ 1, bottom
- top
+ 1));
1540 #endif // wxUSE_MIMETYPE
1542 int wxFileIconsTable::GetIconID(const wxString
& extension
, const wxString
& mime
)
1544 if (!m_smallImageList
)
1548 if (!extension
.IsEmpty())
1550 wxFileIconEntry
*entry
= (wxFileIconEntry
*) m_HashTable
->Get(extension
);
1551 if (entry
) return (entry
-> id
);
1554 wxFileType
*ft
= (mime
.IsEmpty()) ?
1555 wxTheMimeTypesManager
-> GetFileTypeFromExtension(extension
) :
1556 wxTheMimeTypesManager
-> GetFileTypeFromMimeType(mime
);
1558 wxIconLocation iconLoc
;
1560 if ( ft
&& ft
->GetIcon(&iconLoc
) )
1562 ic
= wxIcon(iconLoc
);
1570 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1575 tmpBmp
.CopyFromIcon(ic
);
1576 wxImage img
= tmpBmp
.ConvertToImage();
1578 int id
= m_smallImageList
->GetImageCount();
1579 if (img
.GetWidth() == 16 && img
.GetHeight() == 16)
1580 m_smallImageList
->Add(wxBitmap(img
));
1583 if (img
.GetWidth() != 32 || img
.GetHeight() != 32)
1584 m_smallImageList
->Add(CreateAntialiasedBitmap(CutEmptyBorders(img
).Rescale(32, 32)));
1586 m_smallImageList
->Add(CreateAntialiasedBitmap(img
));
1588 m_HashTable
->Put(extension
, new wxFileIconEntry(id
));
1591 #else // !wxUSE_MIMETYPE
1593 if (extension
== wxT("exe"))
1597 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
1600 #endif // wxUSE_DIRDLG