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 /////////////////////////////////////////////////////////////////////////////
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"
52 #include "wx/statline.h"
55 #if defined(__WXMAC__)
56 #include "wx/mac/private.h" // includes mac headers
62 // FIXME - Mingw32 1.0 has both _getdrive() and _chdrive(). For now, let's assume
63 // older releases don't, but it should be verified and the checks modified
65 #if !defined(__GNUWIN32__) || (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
66 #if !defined(__WXWINCE__)
84 extern bool wxIsDriveAvailable(const wxString
& dirName
);
87 #if defined(__WXMAC__)
89 # include "MoreFilesX.h"
91 # include "MoreFilesExtras.h"
99 // If compiled under Windows, this macro can cause problems
104 // declared in filedlg.h, defined in fldlgcmn.cpp
105 extern int wxParseFileFilter(const wxString
& filterStr
, wxArrayString
& descriptions
, wxArrayString
& filters
);
107 // ----------------------------------------------------------------------------
108 // wxGetAvailableDrives, for WINDOWS, DOS, WXPM, MAC, UNIX (returns "/")
109 // ----------------------------------------------------------------------------
111 size_t wxGetAvailableDrives(wxArrayString
&paths
, wxArrayString
&names
, wxArrayInt
&icon_ids
)
113 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
116 wxChar driveBuffer
[256];
117 size_t n
= (size_t) GetLogicalDriveStrings(255, driveBuffer
);
122 path
.Printf(wxT("%c:\\"), driveBuffer
[i
]);
123 name
.Printf(wxT("%c:"), driveBuffer
[i
]);
125 int imageId
= wxFileIconsTable::drive
;
126 int driveType
= ::GetDriveType(path
);
129 case DRIVE_REMOVABLE
:
130 if (path
== wxT("a:\\") || path
== wxT("b:\\"))
131 imageId
= wxFileIconsTable::floppy
;
133 imageId
= wxFileIconsTable::removeable
;
136 imageId
= wxFileIconsTable::cdrom
;
141 imageId
= wxFileIconsTable::drive
;
147 icon_ids
.Add(imageId
);
149 while (driveBuffer
[i
] != wxT('\0'))
152 if (driveBuffer
[i
] == wxT('\0'))
158 /* If we can switch to the drive, it exists. */
159 for( drive
= 1; drive
<= 26; drive
++ )
162 path
.Printf(wxT("%c:\\"), (char) (drive
+ 'a' - 1));
163 name
.Printf(wxT("%c:"), (char) (drive
+ 'A' - 1));
165 if (wxIsDriveAvailable(path
))
169 icon_ids
.Add((drive
<= 2) ? wxFileIconsTable::floppy
: wxFileIconsTable::drive
);
172 #endif // __WIN32__/!__WIN32__
174 #elif defined(__WXMAC__)
177 ItemCount theVolCount
;
178 char thePath
[FILENAME_MAX
];
180 if (FSGetMountedVolumes(&theVolRefs
, &theVolCount
) == noErr
) {
182 ::HLock( (Handle
)theVolRefs
) ;
183 for (index
= 0; index
< theVolCount
; ++index
) {
184 // get the POSIX path associated with the FSRef
185 if ( FSRefMakePath(&((*theVolRefs
)[index
]),
186 (UInt8
*)thePath
, sizeof(thePath
)) != noErr
) {
189 // add path separator at end if necessary
190 wxString
path( thePath
) ;
191 if (path
.Last() != wxFILE_SEP_PATH
) {
192 path
+= wxFILE_SEP_PATH
;
194 // get Mac volume name for display
195 FSVolumeRefNum vRefNum
;
196 HFSUniStr255 volumeName
;
198 if ( FSGetVRefNum(&((*theVolRefs
)[index
]), &vRefNum
) != noErr
) {
201 if ( FSGetVInfo(vRefNum
, &volumeName
, NULL
, NULL
) != noErr
) {
204 // get C string from Unicode HFS name
205 // see: http://developer.apple.com/carbon/tipsandtricks.html
206 CFStringRef cfstr
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
209 // Do something with str
210 char *cstr
= NewPtr(CFStringGetLength(cfstr
) + 1);
211 if (( cstr
== NULL
) ||
212 !CFStringGetCString(cfstr
, cstr
, CFStringGetLength(cfstr
) + 1,
213 kCFStringEncodingMacRoman
))
218 wxString
name( cstr
);
222 GetVolParmsInfoBuffer volParmsInfo
;
224 if ( FSGetVolParms(vRefNum
, sizeof(volParmsInfo
), &volParmsInfo
, &actualSize
) != noErr
) {
231 if ( VolIsEjectable(&volParmsInfo
) )
232 icon_ids
.Add(wxFileIconsTable::cdrom
);
234 icon_ids
.Add(wxFileIconsTable::drive
);
236 ::HUnlock( (Handle
)theVolRefs
);
237 ::DisposeHandle( (Handle
)theVolRefs
);
244 short actualCount
= 0 ;
245 if (OnLine(&volume
, 1, &actualCount
, &index
) != noErr
|| actualCount
==0)
250 wxString name
= wxMacFSSpec2MacFilename( &volume
);
251 paths
.Add(name
+ wxFILE_SEP_PATH
);
253 icon_ids
.Add(wxFileIconsTable::drive
);
257 #elif defined(__UNIX__)
260 icon_ids
.Add(wxFileIconsTable::computer
);
262 #error "Unsupported platform in wxGenericDirCtrl!"
264 return paths
.GetCount();
267 // ----------------------------------------------------------------------------
268 // wxIsDriveAvailable
269 // ----------------------------------------------------------------------------
273 bool wxIsDriveAvailable(const wxString
& dirName
)
275 // FIXME_MGL - this method leads to hang up under Watcom for some reason
277 if ( dirName
.Len() == 3 && dirName
[1u] == wxT(':') )
279 wxString
dirNameLower(dirName
.Lower());
280 // VS: always return TRUE for removable media, since Win95 doesn't
281 // like it when MS-DOS app accesses empty floppy drive
282 return (dirNameLower
[0u] == wxT('a') ||
283 dirNameLower
[0u] == wxT('b') ||
284 wxPathExists(dirNameLower
));
291 #elif defined(__WINDOWS__) || defined(__WXPM__)
293 int setdrive(int drive
)
295 #if defined(__GNUWIN32__) && \
296 (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
297 return _chdrive(drive
);
301 if (drive
< 1 || drive
> 31)
303 newdrive
[0] = (wxChar
)(wxT('A') + drive
- 1);
304 newdrive
[1] = wxT(':');
305 newdrive
[2] = wxT('\0');
306 #if defined(__WXMSW__)
308 if (wxSetWorkingDirectory(newdrive
))
310 if (::SetCurrentDirectory(newdrive
))
313 // VA doesn't know what LPSTR is and has its own set
314 if (DosSetCurrentDir((PSZ
)newdrive
))
322 bool wxIsDriveAvailable(const wxString
& dirName
)
325 UINT errorMode
= SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOOPENFILEERRORBOX
);
329 // Check if this is a root directory and if so,
330 // whether the drive is available.
331 if (dirName
.Len() == 3 && dirName
[(size_t)1] == wxT(':'))
333 wxString
dirNameLower(dirName
.Lower());
334 #if defined(__GNUWIN32__) && !(defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
335 success
= wxPathExists(dirNameLower
);
337 int currentDrive
= _getdrive();
338 int thisDrive
= (int) (dirNameLower
[(size_t)0] - 'a' + 1) ;
339 int err
= setdrive( thisDrive
) ;
340 setdrive( currentDrive
);
349 (void) SetErrorMode(errorMode
);
354 #endif // __WINDOWS__ || __WXPM__
357 // Function which is called by quick sort. We want to override the default wxArrayString behaviour,
358 // and sort regardless of case.
359 static int LINKAGEMODE
wxDirCtrlStringCompareFunction(wxString
* strFirst
, wxString
* strSecond
)
361 return strFirst
->CmpNoCase(*strSecond
);
364 //-----------------------------------------------------------------------------
366 //-----------------------------------------------------------------------------
368 wxDirItemData::wxDirItemData(const wxString
& path
, const wxString
& name
,
373 /* Insert logic to detect hidden files here
374 * In UnixLand we just check whether the first char is a dot
375 * For FileNameFromPath read LastDirNameInThisPath ;-) */
376 // m_isHidden = (bool)(wxFileNameFromPath(*m_path)[0] == '.');
378 m_isExpanded
= FALSE
;
382 wxDirItemData::~wxDirItemData()
386 void wxDirItemData::SetNewDirName(const wxString
& path
)
389 m_name
= wxFileNameFromPath(path
);
392 bool wxDirItemData::HasSubDirs() const
394 if (m_path
.IsEmpty())
400 if ( !dir
.Open(m_path
) )
404 return dir
.HasSubDirs();
407 bool wxDirItemData::HasFiles(const wxString
& WXUNUSED(spec
)) const
409 if (m_path
.IsEmpty())
415 if ( !dir
.Open(m_path
) )
419 return dir
.HasFiles();
422 //-----------------------------------------------------------------------------
424 //-----------------------------------------------------------------------------
426 IMPLEMENT_DYNAMIC_CLASS(wxGenericDirCtrl
, wxControl
)
428 BEGIN_EVENT_TABLE(wxGenericDirCtrl
, wxControl
)
429 EVT_TREE_ITEM_EXPANDING (-1, wxGenericDirCtrl::OnExpandItem
)
430 EVT_TREE_ITEM_COLLAPSED (-1, wxGenericDirCtrl::OnCollapseItem
)
431 EVT_TREE_BEGIN_LABEL_EDIT (-1, wxGenericDirCtrl::OnBeginEditItem
)
432 EVT_TREE_END_LABEL_EDIT (-1, wxGenericDirCtrl::OnEndEditItem
)
433 EVT_SIZE (wxGenericDirCtrl::OnSize
)
436 wxGenericDirCtrl::wxGenericDirCtrl(void)
441 bool wxGenericDirCtrl::Create(wxWindow
*parent
,
447 const wxString
& filter
,
449 const wxString
& name
)
451 if (!wxControl::Create(parent
, id
, pos
, size
, style
, wxDefaultValidator
, name
))
454 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE
));
458 long treeStyle
= wxTR_HAS_BUTTONS
| wxTR_HIDE_ROOT
;
460 if (style
& wxDIRCTRL_EDIT_LABELS
)
461 treeStyle
|= wxTR_EDIT_LABELS
;
463 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
464 treeStyle
|= wxNO_BORDER
;
466 treeStyle
|= wxBORDER_SUNKEN
;
468 long filterStyle
= 0;
469 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
470 filterStyle
|= wxNO_BORDER
;
472 filterStyle
|= wxBORDER_SUNKEN
;
474 m_treeCtrl
= new wxTreeCtrl(this, wxID_TREECTRL
, pos
, size
, treeStyle
);
476 if (!filter
.IsEmpty() && (style
& wxDIRCTRL_SHOW_FILTERS
))
477 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
, wxDefaultPosition
, wxDefaultSize
, filterStyle
);
482 SetFilterIndex(defaultFilter
);
484 if (m_filterListCtrl
)
485 m_filterListCtrl
->FillFilterList(filter
, defaultFilter
);
487 m_treeCtrl
->SetImageList(wxTheFileIconsTable
->GetSmallImageList());
489 m_showHidden
= FALSE
;
490 wxDirItemData
* rootData
= new wxDirItemData(wxT(""), wxT(""), TRUE
);
494 #if defined(__WINDOWS__) || defined(__WXPM__) || defined(__DOS__)
495 rootName
= _("Computer");
497 rootName
= _("Sections");
500 m_rootId
= m_treeCtrl
->AddRoot( rootName
, 3, -1, rootData
);
501 m_treeCtrl
->SetItemHasChildren(m_rootId
);
502 ExpandDir(m_rootId
); // automatically expand first level
504 // Expand and select the default path
505 if (!m_defaultPath
.IsEmpty())
506 ExpandPath(m_defaultPath
);
513 wxGenericDirCtrl::~wxGenericDirCtrl()
517 void wxGenericDirCtrl::Init()
519 m_showHidden
= FALSE
;
521 m_currentFilterStr
= wxEmptyString
; // Default: any file
523 m_filterListCtrl
= NULL
;
526 void wxGenericDirCtrl::ShowHidden( bool show
)
530 wxString path
= GetPath();
536 wxGenericDirCtrl::AddSection(const wxString
& path
, const wxString
& name
, int imageId
)
538 wxDirItemData
*dir_item
= new wxDirItemData(path
,name
,TRUE
);
540 wxTreeItemId id
= AppendItem( m_rootId
, name
, imageId
, -1, dir_item
);
542 m_treeCtrl
->SetItemHasChildren(id
);
547 void wxGenericDirCtrl::SetupSections()
549 wxArrayString paths
, names
;
552 size_t n
, count
= wxGetAvailableDrives(paths
, names
, icons
);
554 for (n
= 0; n
< count
; n
++)
556 AddSection(paths
[n
], names
[n
], icons
[n
]);
560 void wxGenericDirCtrl::OnBeginEditItem(wxTreeEvent
&event
)
562 // don't rename the main entry "Sections"
563 if (event
.GetItem() == m_rootId
)
569 // don't rename the individual sections
570 if (m_treeCtrl
->GetItemParent( event
.GetItem() ) == m_rootId
)
577 void wxGenericDirCtrl::OnEndEditItem(wxTreeEvent
&event
)
579 if ((event
.GetLabel().IsEmpty()) ||
580 (event
.GetLabel() == _(".")) ||
581 (event
.GetLabel() == _("..")) ||
582 (event
.GetLabel().Find(wxT('/')) != wxNOT_FOUND
) ||
583 (event
.GetLabel().Find(wxT('\\')) != wxNOT_FOUND
) ||
584 (event
.GetLabel().Find(wxT('|')) != wxNOT_FOUND
))
586 wxMessageDialog
dialog(this, _("Illegal directory name."), _("Error"), wxOK
| wxICON_ERROR
);
592 wxTreeItemId id
= event
.GetItem();
593 wxDirItemData
*data
= (wxDirItemData
*)m_treeCtrl
->GetItemData( id
);
596 wxString
new_name( wxPathOnly( data
->m_path
) );
597 new_name
+= wxString(wxFILE_SEP_PATH
);
598 new_name
+= event
.GetLabel();
602 if (wxFileExists(new_name
))
604 wxMessageDialog
dialog(this, _("File name exists already."), _("Error"), wxOK
| wxICON_ERROR
);
609 if (wxRenameFile(data
->m_path
,new_name
))
611 data
->SetNewDirName( new_name
);
615 wxMessageDialog
dialog(this, _("Operation not permitted."), _("Error"), wxOK
| wxICON_ERROR
);
621 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent
&event
)
623 wxTreeItemId parentId
= event
.GetItem();
625 // VS: this is needed because the event handler is called from wxTreeCtrl
626 // ctor when wxTR_HIDE_ROOT was specified
628 if (!m_rootId
.IsOk())
630 m_rootId
= m_treeCtrl
->GetRootItem();
635 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent
&event
)
637 CollapseDir(event
.GetItem());
640 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId
)
644 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
645 if (!data
->m_isExpanded
)
648 data
->m_isExpanded
= FALSE
;
650 /* Workaround because DeleteChildren has disapeared (why?) and
651 * CollapseAndReset doesn't work as advertised (deletes parent too) */
652 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
655 m_treeCtrl
->Delete(child
);
656 /* Not GetNextChild below, because the cookie mechanism can't
657 * handle disappearing children! */
658 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
662 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId
)
664 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
666 if (data
->m_isExpanded
)
669 data
->m_isExpanded
= TRUE
;
671 if (parentId
== m_treeCtrl
->GetRootItem())
679 wxString search
,path
,filename
;
681 wxString
dirName(data
->m_path
);
683 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
684 // Check if this is a root directory and if so,
685 // whether the drive is avaiable.
686 if (!wxIsDriveAvailable(dirName
))
688 data
->m_isExpanded
= FALSE
;
689 //wxMessageBox(wxT("Sorry, this drive is not available."));
694 // This may take a longish time. Go to busy cursor
697 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
698 if (dirName
.Last() == ':')
699 dirName
+= wxString(wxFILE_SEP_PATH
);
703 wxArrayString filenames
;
706 wxString eachFilename
;
713 int style
= wxDIR_DIRS
;
714 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
715 if (d
.GetFirst(& eachFilename
, wxEmptyString
, style
))
719 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
721 dirs
.Add(eachFilename
);
724 while (d
.GetNext(& eachFilename
));
727 dirs
.Sort(wxDirCtrlStringCompareFunction
);
729 // Now do the filenames -- but only if we're allowed to
730 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
738 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, wxDIR_FILES
))
742 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
744 filenames
.Add(eachFilename
);
747 while (d
.GetNext(& eachFilename
));
750 filenames
.Sort(wxDirCtrlStringCompareFunction
);
753 // Add the sorted dirs
755 for (i
= 0; i
< dirs
.Count(); i
++)
757 wxString
eachFilename(dirs
[i
]);
759 if (!wxEndsWithPathSeparator(path
))
760 path
+= wxString(wxFILE_SEP_PATH
);
761 path
+= eachFilename
;
763 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,TRUE
);
764 wxTreeItemId id
= AppendItem( parentId
, eachFilename
,
765 wxFileIconsTable::folder
, -1, dir_item
);
766 m_treeCtrl
->SetItemImage( id
, wxFileIconsTable::folder_open
,
767 wxTreeItemIcon_Expanded
);
769 // Has this got any children? If so, make it expandable.
770 // (There are two situations when a dir has children: either it
771 // has subdirectories or it contains files that weren't filtered
772 // out. The latter only applies to dirctrl with files.)
773 if ( dir_item
->HasSubDirs() ||
774 (((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0) &&
775 dir_item
->HasFiles(m_currentFilterStr
)) )
777 m_treeCtrl
->SetItemHasChildren(id
);
781 // Add the sorted filenames
782 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
784 for (i
= 0; i
< filenames
.Count(); i
++)
786 wxString
eachFilename(filenames
[i
]);
788 if (!wxEndsWithPathSeparator(path
))
789 path
+= wxString(wxFILE_SEP_PATH
);
790 path
+= eachFilename
;
791 //path = dirName + wxString(wxT("/")) + eachFilename;
792 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,FALSE
);
793 int image_id
= wxFileIconsTable::file
;
794 if (eachFilename
.Find(wxT('.')) != wxNOT_FOUND
)
795 image_id
= wxTheFileIconsTable
->GetIconID(eachFilename
.AfterLast(wxT('.')));
796 (void) AppendItem( parentId
, eachFilename
, image_id
, -1, dir_item
);
801 void wxGenericDirCtrl::ReCreateTree()
803 CollapseDir(m_treeCtrl
->GetRootItem());
804 ExpandDir(m_treeCtrl
->GetRootItem());
807 // Find the child that matches the first part of 'path'.
808 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
809 // then the child for /usr is returned.
810 wxTreeItemId
wxGenericDirCtrl::FindChild(wxTreeItemId parentId
, const wxString
& path
, bool& done
)
812 wxString
path2(path
);
814 // Make sure all separators are as per the current platform
815 path2
.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH
));
816 path2
.Replace(wxT("/"), wxString(wxFILE_SEP_PATH
));
818 // Append a separator to foil bogus substring matching
819 path2
+= wxString(wxFILE_SEP_PATH
);
821 // In MSW or PM, case is not significant
822 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
827 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
828 while (childId
.IsOk())
830 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
832 if (data
&& !data
->m_path
.IsEmpty())
834 wxString
childPath(data
->m_path
);
835 if (!wxEndsWithPathSeparator(childPath
))
836 childPath
+= wxString(wxFILE_SEP_PATH
);
838 // In MSW and PM, case is not significant
839 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
840 childPath
.MakeLower();
843 if (childPath
.Len() <= path2
.Len())
845 wxString path3
= path2
.Mid(0, childPath
.Len());
846 if (childPath
== path3
)
848 if (path3
.Len() == path2
.Len())
857 childId
= m_treeCtrl
->GetNextChild(parentId
, cookie
);
859 wxTreeItemId invalid
;
863 // Try to expand as much of the given path as possible,
864 // and select the given tree item.
865 bool wxGenericDirCtrl::ExpandPath(const wxString
& path
)
868 wxTreeItemId id
= FindChild(m_rootId
, path
, done
);
869 wxTreeItemId lastId
= id
; // The last non-zero id
870 while (id
.IsOk() && !done
)
874 id
= FindChild(id
, path
, done
);
880 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(lastId
);
883 m_treeCtrl
->Expand(lastId
);
885 if ((GetWindowStyle() & wxDIRCTRL_SELECT_FIRST
) && data
->m_isDir
)
887 // Find the first file in this directory
889 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(lastId
, cookie
);
890 bool selectedChild
= FALSE
;
891 while (childId
.IsOk())
893 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
895 if (data
&& data
->m_path
!= wxT("") && !data
->m_isDir
)
897 m_treeCtrl
->SelectItem(childId
);
898 m_treeCtrl
->EnsureVisible(childId
);
899 selectedChild
= TRUE
;
902 childId
= m_treeCtrl
->GetNextChild(lastId
, cookie
);
906 m_treeCtrl
->SelectItem(lastId
);
907 m_treeCtrl
->EnsureVisible(lastId
);
912 m_treeCtrl
->SelectItem(lastId
);
913 m_treeCtrl
->EnsureVisible(lastId
);
922 wxString
wxGenericDirCtrl::GetPath() const
924 wxTreeItemId id
= m_treeCtrl
->GetSelection();
927 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
931 return wxEmptyString
;
934 wxString
wxGenericDirCtrl::GetFilePath() const
936 wxTreeItemId id
= m_treeCtrl
->GetSelection();
939 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
941 return wxEmptyString
;
946 return wxEmptyString
;
949 void wxGenericDirCtrl::SetPath(const wxString
& path
)
951 m_defaultPath
= path
;
958 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId id
, int dirFlags
, wxArrayString
& filenames
)
960 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
962 // This may take a longish time. Go to busy cursor
967 wxString search
,path
,filename
;
969 wxString
dirName(data
->m_path
);
971 #if defined(__WXMSW__) || defined(__WXPM__)
972 if (dirName
.Last() == ':')
973 dirName
+= wxString(wxFILE_SEP_PATH
);
977 wxString eachFilename
;
984 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, dirFlags
))
988 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
990 filenames
.Add(eachFilename
);
993 while (d
.GetNext(& eachFilename
)) ;
999 void wxGenericDirCtrl::SetFilterIndex(int n
)
1001 m_currentFilter
= n
;
1004 if (ExtractWildcard(m_filter
, n
, f
, d
))
1005 m_currentFilterStr
= f
;
1007 m_currentFilterStr
= wxT("*.*");
1010 void wxGenericDirCtrl::SetFilter(const wxString
& filter
)
1015 if (ExtractWildcard(m_filter
, m_currentFilter
, f
, d
))
1016 m_currentFilterStr
= f
;
1018 m_currentFilterStr
= wxT("*.*");
1021 // Extract description and actual filter from overall filter string
1022 bool wxGenericDirCtrl::ExtractWildcard(const wxString
& filterStr
, int n
, wxString
& filter
, wxString
& description
)
1024 wxArrayString filters
, descriptions
;
1025 int count
= ParseFilter(filterStr
, filters
, descriptions
);
1026 if (count
> 0 && n
< count
)
1028 filter
= filters
[n
];
1029 description
= descriptions
[n
];
1036 // Parses the global filter, returning the number of filters.
1037 // Returns 0 if none or if there's a problem.
1038 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpg"
1040 int wxGenericDirCtrl::ParseFilter(const wxString
& filterStr
, wxArrayString
& filters
, wxArrayString
& descriptions
)
1042 return wxParseFileFilter(filterStr
, descriptions
, filters
);
1045 void wxGenericDirCtrl::DoResize()
1047 wxSize sz
= GetClientSize();
1048 int verticalSpacing
= 3;
1052 if (m_filterListCtrl
)
1055 // For some reason, this is required in order for the
1056 // correct control height to always be returned, rather
1057 // than the drop-down list height which is sometimes returned.
1058 wxSize oldSize
= m_filterListCtrl
->GetSize();
1059 m_filterListCtrl
->SetSize(-1, -1, oldSize
.x
+10, -1, wxSIZE_USE_EXISTING
);
1060 m_filterListCtrl
->SetSize(-1, -1, oldSize
.x
, -1, wxSIZE_USE_EXISTING
);
1062 filterSz
= m_filterListCtrl
->GetSize();
1063 sz
.y
-= (filterSz
.y
+ verticalSpacing
);
1065 m_treeCtrl
->SetSize(0, 0, sz
.x
, sz
.y
);
1066 if (m_filterListCtrl
)
1068 m_filterListCtrl
->SetSize(0, sz
.y
+ verticalSpacing
, sz
.x
, filterSz
.y
);
1069 // Don't know why, but this needs refreshing after a resize (wxMSW)
1070 m_filterListCtrl
->Refresh();
1076 void wxGenericDirCtrl::OnSize(wxSizeEvent
& WXUNUSED(event
))
1081 wxTreeItemId
wxGenericDirCtrl::AppendItem (const wxTreeItemId
& parent
,
1082 const wxString
& text
,
1083 int image
, int selectedImage
,
1084 wxTreeItemData
* data
)
1086 wxTreeCtrl
*treeCtrl
= GetTreeCtrl ();
1088 wxASSERT (treeCtrl
);
1092 return treeCtrl
->AppendItem (parent
, text
, image
, selectedImage
, data
);
1096 return wxTreeItemId();
1101 //-----------------------------------------------------------------------------
1102 // wxDirFilterListCtrl
1103 //-----------------------------------------------------------------------------
1105 IMPLEMENT_CLASS(wxDirFilterListCtrl
, wxChoice
)
1107 BEGIN_EVENT_TABLE(wxDirFilterListCtrl
, wxChoice
)
1108 EVT_CHOICE(-1, wxDirFilterListCtrl::OnSelFilter
)
1111 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl
* parent
, const wxWindowID id
,
1117 return wxChoice::Create(parent
, id
, pos
, size
, 0, NULL
, style
);
1120 void wxDirFilterListCtrl::Init()
1125 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent
& WXUNUSED(event
))
1127 int sel
= GetSelection();
1129 wxString currentPath
= m_dirCtrl
->GetPath();
1131 m_dirCtrl
->SetFilterIndex(sel
);
1133 // If the filter has changed, the view is out of date, so
1134 // collapse the tree.
1135 m_dirCtrl
->ReCreateTree();
1137 // Try to restore the selection, or at least the directory
1138 m_dirCtrl
->ExpandPath(currentPath
);
1141 void wxDirFilterListCtrl::FillFilterList(const wxString
& filter
, int defaultFilter
)
1144 wxArrayString descriptions
, filters
;
1145 size_t n
= (size_t) m_dirCtrl
->ParseFilter(filter
, filters
, descriptions
);
1147 if (n
> 0 && defaultFilter
< (int) n
)
1150 for (i
= 0; i
< n
; i
++)
1151 Append(descriptions
[i
]);
1152 SetSelection(defaultFilter
);
1157 // ----------------------------------------------------------------------------
1158 // wxFileIconsTable icons
1159 // ----------------------------------------------------------------------------
1162 static const char * file_icons_tbl_folder_open_xpm
[] = {
1163 /* width height ncolors chars_per_pixel */
1191 static const char * file_icons_tbl_computer_xpm
[] = {
1218 static const char * file_icons_tbl_drive_xpm
[] = {
1245 static const char *file_icons_tbl_cdrom_xpm
[] = {
1275 static const char * file_icons_tbl_floppy_xpm
[] = {
1302 static const char * file_icons_tbl_removeable_xpm
[] = {
1328 // ----------------------------------------------------------------------------
1329 // wxFileIconsTable & friends
1330 // ----------------------------------------------------------------------------
1332 // global instance of a wxFileIconsTable
1333 wxFileIconsTable
* wxTheFileIconsTable
= (wxFileIconsTable
*)NULL
;
1335 // A module to allow icons table cleanup
1337 class wxFileIconsTableModule
: public wxModule
1339 DECLARE_DYNAMIC_CLASS(wxFileIconsTableModule
)
1341 wxFileIconsTableModule() {}
1342 bool OnInit() { wxTheFileIconsTable
= new wxFileIconsTable
; return TRUE
; }
1345 if (wxTheFileIconsTable
)
1347 delete wxTheFileIconsTable
;
1348 wxTheFileIconsTable
= NULL
;
1353 IMPLEMENT_DYNAMIC_CLASS(wxFileIconsTableModule
, wxModule
)
1355 class wxFileIconEntry
: public wxObject
1358 wxFileIconEntry(int i
) { id
= i
; }
1363 wxFileIconsTable::wxFileIconsTable()
1366 m_smallImageList
= NULL
;
1369 wxFileIconsTable::~wxFileIconsTable()
1373 WX_CLEAR_HASH_TABLE(*m_HashTable
);
1376 if (m_smallImageList
) delete m_smallImageList
;
1379 // delayed initialization - wait until first use (wxArtProv not created yet)
1380 void wxFileIconsTable::Create()
1382 wxCHECK_RET(!m_smallImageList
&& !m_HashTable
, wxT("creating icons twice"));
1383 m_HashTable
= new wxHashTable(wxKEY_STRING
);
1384 m_smallImageList
= new wxImageList(16, 16);
1387 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER
, wxART_CMN_DIALOG
));
1389 m_smallImageList
->Add(wxIcon(file_icons_tbl_folder_open_xpm
));
1391 m_smallImageList
->Add(wxIcon(file_icons_tbl_computer_xpm
));
1393 m_smallImageList
->Add(wxIcon(file_icons_tbl_drive_xpm
));
1395 m_smallImageList
->Add(wxIcon(file_icons_tbl_cdrom_xpm
));
1397 m_smallImageList
->Add(wxIcon(file_icons_tbl_floppy_xpm
));
1399 m_smallImageList
->Add(wxIcon(file_icons_tbl_removeable_xpm
));
1401 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE
, wxART_CMN_DIALOG
));
1403 if (GetIconID(wxEmptyString
, _T("application/x-executable")) == file
)
1405 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE
, wxART_CMN_DIALOG
));
1406 delete m_HashTable
->Get(_T("exe"));
1407 m_HashTable
->Delete(_T("exe"));
1408 m_HashTable
->Put(_T("exe"), new wxFileIconEntry(executable
));
1410 /* else put into list by GetIconID
1411 (KDE defines application/x-executable for *.exe and has nice icon)
1415 wxImageList
*wxFileIconsTable::GetSmallImageList()
1417 if (!m_smallImageList
)
1420 return m_smallImageList
;
1424 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
1425 // one icon and we won't resize it
1427 static wxBitmap
CreateAntialiasedBitmap(const wxImage
& img
)
1429 wxImage
smallimg (16, 16);
1430 unsigned char *p1
, *p2
, *ps
;
1431 unsigned char mr
= img
.GetMaskRed(),
1432 mg
= img
.GetMaskGreen(),
1433 mb
= img
.GetMaskBlue();
1436 unsigned sr
, sg
, sb
, smask
;
1438 p1
= img
.GetData(), p2
= img
.GetData() + 3 * 32, ps
= smallimg
.GetData();
1439 smallimg
.SetMaskColour(mr
, mr
, mr
);
1441 for (y
= 0; y
< 16; y
++)
1443 for (x
= 0; x
< 16; x
++)
1445 sr
= sg
= sb
= smask
= 0;
1446 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1447 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1450 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1451 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1454 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1455 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1458 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1459 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1464 ps
[0] = ps
[1] = ps
[2] = mr
;
1466 ps
[0] = sr
>> 2, ps
[1] = sg
>> 2, ps
[2] = sb
>> 2;
1469 p1
+= 32 * 3, p2
+= 32 * 3;
1472 return wxBitmap(smallimg
);
1475 // finds empty borders and return non-empty area of image:
1476 static wxImage
CutEmptyBorders(const wxImage
& img
)
1478 unsigned char mr
= img
.GetMaskRed(),
1479 mg
= img
.GetMaskGreen(),
1480 mb
= img
.GetMaskBlue();
1481 unsigned char *dt
= img
.GetData(), *dttmp
;
1482 unsigned w
= img
.GetWidth(), h
= img
.GetHeight();
1484 unsigned top
, bottom
, left
, right
, i
;
1487 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
1488 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = FALSE; break;}
1490 for (empt
= TRUE
, top
= 0; empt
&& top
< h
; top
++)
1493 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1496 for (empt
= TRUE
, bottom
= h
-1; empt
&& bottom
> top
; bottom
--)
1498 MK_DTTMP(0, bottom
);
1499 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1502 for (empt
= TRUE
, left
= 0; empt
&& left
< w
; left
++)
1505 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1508 for (empt
= TRUE
, right
= w
-1; empt
&& right
> left
; right
--)
1511 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1514 top
--, left
--, bottom
++, right
++;
1516 return img
.GetSubImage(wxRect(left
, top
, right
- left
+ 1, bottom
- top
+ 1));
1518 #endif // wxUSE_MIMETYPE
1520 int wxFileIconsTable::GetIconID(const wxString
& extension
, const wxString
& mime
)
1522 if (!m_smallImageList
)
1526 if (!extension
.IsEmpty())
1528 wxFileIconEntry
*entry
= (wxFileIconEntry
*) m_HashTable
->Get(extension
);
1529 if (entry
) return (entry
-> id
);
1532 wxFileType
*ft
= (mime
.IsEmpty()) ?
1533 wxTheMimeTypesManager
-> GetFileTypeFromExtension(extension
) :
1534 wxTheMimeTypesManager
-> GetFileTypeFromMimeType(mime
);
1536 wxIconLocation iconLoc
;
1538 if ( ft
&& ft
->GetIcon(&iconLoc
) )
1540 ic
= wxIcon(iconLoc
);
1548 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1553 tmpBmp
.CopyFromIcon(ic
);
1554 wxImage img
= tmpBmp
.ConvertToImage();
1556 int id
= m_smallImageList
->GetImageCount();
1557 if (img
.GetWidth() == 16 && img
.GetHeight() == 16)
1558 m_smallImageList
->Add(wxBitmap(img
));
1561 if (img
.GetWidth() != 32 || img
.GetHeight() != 32)
1562 m_smallImageList
->Add(CreateAntialiasedBitmap(CutEmptyBorders(img
).Rescale(32, 32)));
1564 m_smallImageList
->Add(CreateAntialiasedBitmap(img
));
1566 m_HashTable
->Put(extension
, new wxFileIconEntry(id
));
1569 #else // !wxUSE_MIMETYPE
1571 if (extension
== wxT("exe"))
1575 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
1578 #endif // wxUSE_DIRDLG