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"
23 #if wxUSE_DIRDLG || wxUSE_FILEDLG
25 #include "wx/generic/dirctrlg.h"
26 #include "wx/module.h"
28 #include "wx/button.h"
29 #include "wx/layout.h"
30 #include "wx/msgdlg.h"
31 #include "wx/textctrl.h"
32 #include "wx/textdlg.h"
33 #include "wx/filefn.h"
34 #include "wx/cmndata.h"
35 #include "wx/gdicmn.h"
37 #include "wx/imaglist.h"
41 #include "wx/tokenzr.h"
43 #include "wx/settings.h"
44 #include "wx/artprov.h"
46 #include "wx/mimetype.h"
48 #include "wx/choice.h"
51 #include "wx/statline.h"
54 #if defined(__WXMAC__)
55 #include "wx/mac/private.h" // includes mac headers
61 // FIXME - Mingw32 1.0 has both _getdrive() and _chdrive(). For now, let's assume
62 // older releases don't, but it should be verified and the checks modified
64 #if !defined(__GNUWIN32__) || (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
65 #if !defined(__WXWINCE__)
74 #if defined(__OS2__) || defined(__DOS__)
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 // ----------------------------------------------------------------------------
105 // wxGetAvailableDrives, for WINDOWS, DOS, OS2, MAC, UNIX (returns "/")
106 // ----------------------------------------------------------------------------
108 size_t wxGetAvailableDrives(wxArrayString
&paths
, wxArrayString
&names
, wxArrayInt
&icon_ids
)
110 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
113 // No logical drives; return "\"
114 paths
.Add(wxT("\\"));
115 names
.Add(wxT("\\"));
116 icon_ids
.Add(wxFileIconsTable::computer
);
117 #elif defined(__WIN32__)
118 wxChar driveBuffer
[256];
119 size_t n
= (size_t) GetLogicalDriveStrings(255, driveBuffer
);
124 path
.Printf(wxT("%c:\\"), driveBuffer
[i
]);
125 name
.Printf(wxT("%c:"), driveBuffer
[i
]);
128 int driveType
= ::GetDriveType(path
);
131 case DRIVE_REMOVABLE
:
132 if (path
== wxT("a:\\") || path
== wxT("b:\\"))
133 imageId
= wxFileIconsTable::floppy
;
135 imageId
= wxFileIconsTable::removeable
;
138 imageId
= wxFileIconsTable::cdrom
;
143 imageId
= wxFileIconsTable::drive
;
149 icon_ids
.Add(imageId
);
151 while (driveBuffer
[i
] != wxT('\0'))
154 if (driveBuffer
[i
] == wxT('\0'))
157 #elif defined(__OS2__)
159 ULONG ulDriveNum
= 0;
160 ULONG ulDriveMap
= 0;
161 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
167 if (ulDriveMap
& ( 1 << i
))
170 path
.Printf(wxT("%c:\\"), 'A' + i
);
171 name
.Printf(wxT("%c:"), 'A' + i
);
174 if (path
== wxT("A:\\") || path
== wxT("B:\\"))
175 imageId
= wxFileIconsTable::floppy
;
177 imageId
= wxFileIconsTable::drive
;
180 icon_ids
.Add(imageId
);
185 #else // !__WIN32__, !__OS2__
188 /* If we can switch to the drive, it exists. */
189 for( drive
= 1; drive
<= 26; drive
++ )
192 path
.Printf(wxT("%c:\\"), (char) (drive
+ 'a' - 1));
193 name
.Printf(wxT("%c:"), (char) (drive
+ 'A' - 1));
195 if (wxIsDriveAvailable(path
))
199 icon_ids
.Add((drive
<= 2) ? wxFileIconsTable::floppy
: wxFileIconsTable::drive
);
202 #endif // __WIN32__/!__WIN32__
204 #elif defined(__WXMAC__)
207 ItemCount theVolCount
;
208 char thePath
[FILENAME_MAX
];
210 if (FSGetMountedVolumes(&theVolRefs
, &theVolCount
) == noErr
) {
212 ::HLock( (Handle
)theVolRefs
) ;
213 for (index
= 0; index
< theVolCount
; ++index
) {
214 // get the POSIX path associated with the FSRef
215 if ( FSRefMakePath(&((*theVolRefs
)[index
]),
216 (UInt8
*)thePath
, sizeof(thePath
)) != noErr
) {
219 // add path separator at end if necessary
220 wxString
path( thePath
, wxConvLocal
) ;
221 if (path
.Last() != wxFILE_SEP_PATH
) {
222 path
+= wxFILE_SEP_PATH
;
224 // get Mac volume name for display
225 FSVolumeRefNum vRefNum
;
226 HFSUniStr255 volumeName
;
228 if ( FSGetVRefNum(&((*theVolRefs
)[index
]), &vRefNum
) != noErr
) {
231 if ( FSGetVInfo(vRefNum
, &volumeName
, NULL
, NULL
) != noErr
) {
234 // get C string from Unicode HFS name
235 // see: http://developer.apple.com/carbon/tipsandtricks.html
236 CFStringRef cfstr
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
239 // Do something with str
240 char *cstr
= NewPtr(CFStringGetLength(cfstr
) + 1);
241 if (( cstr
== NULL
) ||
242 !CFStringGetCString(cfstr
, cstr
, CFStringGetLength(cfstr
) + 1,
243 kCFStringEncodingMacRoman
))
248 wxString
name( cstr
, wxConvLocal
);
252 GetVolParmsInfoBuffer volParmsInfo
;
254 if ( FSGetVolParms(vRefNum
, sizeof(volParmsInfo
), &volParmsInfo
, &actualSize
) != noErr
) {
261 if ( VolIsEjectable(&volParmsInfo
) )
262 icon_ids
.Add(wxFileIconsTable::cdrom
);
264 icon_ids
.Add(wxFileIconsTable::drive
);
266 ::HUnlock( (Handle
)theVolRefs
);
267 ::DisposeHandle( (Handle
)theVolRefs
);
274 short actualCount
= 0 ;
275 if (OnLine(&volume
, 1, &actualCount
, &index
) != noErr
|| actualCount
==0)
280 wxString name
= wxMacFSSpec2MacFilename( &volume
);
281 paths
.Add(name
+ wxFILE_SEP_PATH
);
283 icon_ids
.Add(wxFileIconsTable::drive
);
287 #elif defined(__UNIX__)
290 icon_ids
.Add(wxFileIconsTable::computer
);
292 #error "Unsupported platform in wxGenericDirCtrl!"
294 wxASSERT_MSG( (paths
.GetCount() == names
.GetCount()), wxT("The number of paths and their human readable names should be equal in number."));
295 wxASSERT_MSG( (paths
.GetCount() == icon_ids
.GetCount()), wxT("Wrong number of icons for available drives."));
296 return paths
.GetCount();
299 // ----------------------------------------------------------------------------
300 // wxIsDriveAvailable
301 // ----------------------------------------------------------------------------
305 bool wxIsDriveAvailable(const wxString
& dirName
)
307 // FIXME_MGL - this method leads to hang up under Watcom for some reason
309 if ( dirName
.Len() == 3 && dirName
[1u] == wxT(':') )
311 wxString
dirNameLower(dirName
.Lower());
312 // VS: always return true for removable media, since Win95 doesn't
313 // like it when MS-DOS app accesses empty floppy drive
314 return (dirNameLower
[0u] == wxT('a') ||
315 dirNameLower
[0u] == wxT('b') ||
316 wxPathExists(dirNameLower
));
323 #elif defined(__WINDOWS__) || defined(__OS2__)
325 int setdrive(int drive
)
330 #elif defined(__GNUWIN32__) && \
331 (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
332 return _chdrive(drive
);
336 if (drive
< 1 || drive
> 31)
338 newdrive
[0] = (wxChar
)(wxT('A') + drive
- 1);
339 newdrive
[1] = wxT(':');
341 newdrive
[2] = wxT('\\');
342 newdrive
[3] = wxT('\0');
344 newdrive
[2] = wxT('\0');
346 #if defined(__WXMSW__)
347 if (::SetCurrentDirectory(newdrive
))
349 // VA doesn't know what LPSTR is and has its own set
350 if (!DosSetCurrentDir((PSZ
)newdrive
))
358 bool wxIsDriveAvailable(const wxString
& dirName
)
361 wxUnusedVar(dirName
);
365 UINT errorMode
= SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOOPENFILEERRORBOX
);
369 // Check if this is a root directory and if so,
370 // whether the drive is available.
371 if (dirName
.Len() == 3 && dirName
[(size_t)1] == wxT(':'))
373 wxString
dirNameLower(dirName
.Lower());
374 #if defined(__GNUWIN32__) && !(defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
375 success
= wxPathExists(dirNameLower
);
378 // Avoid changing to drive since no media may be inserted.
379 if (dirNameLower
[(size_t)0] == 'a' || dirNameLower
[(size_t)0] == 'b')
382 int currentDrive
= _getdrive();
383 int thisDrive
= (int) (dirNameLower
[(size_t)0] - 'a' + 1) ;
384 int err
= setdrive( thisDrive
) ;
385 setdrive( currentDrive
);
394 (void) SetErrorMode(errorMode
);
400 #endif // __WINDOWS__ || __OS2__
402 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG
408 // Function which is called by quick sort. We want to override the default wxArrayString behaviour,
409 // and sort regardless of case.
410 static int wxCMPFUNC_CONV
wxDirCtrlStringCompareFunction(wxString
* strFirst
, wxString
* strSecond
)
412 return strFirst
->CmpNoCase(*strSecond
);
415 //-----------------------------------------------------------------------------
417 //-----------------------------------------------------------------------------
419 wxDirItemData::wxDirItemData(const wxString
& path
, const wxString
& name
,
424 /* Insert logic to detect hidden files here
425 * In UnixLand we just check whether the first char is a dot
426 * For FileNameFromPath read LastDirNameInThisPath ;-) */
427 // m_isHidden = (bool)(wxFileNameFromPath(*m_path)[0] == '.');
429 m_isExpanded
= false;
433 wxDirItemData::~wxDirItemData()
437 void wxDirItemData::SetNewDirName(const wxString
& path
)
440 m_name
= wxFileNameFromPath(path
);
443 bool wxDirItemData::HasSubDirs() const
445 if (m_path
.IsEmpty())
451 if ( !dir
.Open(m_path
) )
455 return dir
.HasSubDirs();
458 bool wxDirItemData::HasFiles(const wxString
& WXUNUSED(spec
)) const
460 if (m_path
.IsEmpty())
466 if ( !dir
.Open(m_path
) )
470 return dir
.HasFiles();
473 //-----------------------------------------------------------------------------
475 //-----------------------------------------------------------------------------
478 #if wxUSE_EXTENDED_RTTI
479 WX_DEFINE_FLAGS( wxGenericDirCtrlStyle
)
481 wxBEGIN_FLAGS( wxGenericDirCtrlStyle
)
482 // new style border flags, we put them first to
483 // use them for streaming out
484 wxFLAGS_MEMBER(wxBORDER_SIMPLE
)
485 wxFLAGS_MEMBER(wxBORDER_SUNKEN
)
486 wxFLAGS_MEMBER(wxBORDER_DOUBLE
)
487 wxFLAGS_MEMBER(wxBORDER_RAISED
)
488 wxFLAGS_MEMBER(wxBORDER_STATIC
)
489 wxFLAGS_MEMBER(wxBORDER_NONE
)
491 // old style border flags
492 wxFLAGS_MEMBER(wxSIMPLE_BORDER
)
493 wxFLAGS_MEMBER(wxSUNKEN_BORDER
)
494 wxFLAGS_MEMBER(wxDOUBLE_BORDER
)
495 wxFLAGS_MEMBER(wxRAISED_BORDER
)
496 wxFLAGS_MEMBER(wxSTATIC_BORDER
)
497 wxFLAGS_MEMBER(wxBORDER
)
499 // standard window styles
500 wxFLAGS_MEMBER(wxTAB_TRAVERSAL
)
501 wxFLAGS_MEMBER(wxCLIP_CHILDREN
)
502 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW
)
503 wxFLAGS_MEMBER(wxWANTS_CHARS
)
504 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE
)
505 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB
)
506 wxFLAGS_MEMBER(wxVSCROLL
)
507 wxFLAGS_MEMBER(wxHSCROLL
)
509 wxFLAGS_MEMBER(wxDIRCTRL_DIR_ONLY
)
510 wxFLAGS_MEMBER(wxDIRCTRL_3D_INTERNAL
)
511 wxFLAGS_MEMBER(wxDIRCTRL_SELECT_FIRST
)
512 wxFLAGS_MEMBER(wxDIRCTRL_SHOW_FILTERS
)
514 wxEND_FLAGS( wxGenericDirCtrlStyle
)
516 IMPLEMENT_DYNAMIC_CLASS_XTI(wxGenericDirCtrl
, wxControl
,"wx/dirctrl.h")
518 wxBEGIN_PROPERTIES_TABLE(wxGenericDirCtrl
)
519 wxHIDE_PROPERTY( Children
)
520 wxPROPERTY( DefaultPath
, wxString
, SetDefaultPath
, GetDefaultPath
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
521 wxPROPERTY( Filter
, wxString
, SetFilter
, GetFilter
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
522 wxPROPERTY( DefaultFilter
, int , SetFilterIndex
, GetFilterIndex
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
523 wxPROPERTY_FLAGS( WindowStyle
, wxGenericDirCtrlStyle
, long, SetWindowStyleFlag
, GetWindowStyleFlag
, EMPTY_MACROVALUE
, 0, wxT("Helpstring"), wxT("group") )
524 wxEND_PROPERTIES_TABLE()
526 wxBEGIN_HANDLERS_TABLE(wxGenericDirCtrl
)
527 wxEND_HANDLERS_TABLE()
529 wxCONSTRUCTOR_8( wxGenericDirCtrl
, wxWindow
* , Parent
, wxWindowID
, Id
, wxString
, DefaultPath
,
530 wxPoint
, Position
, wxSize
, Size
, long , WindowStyle
, wxString
, Filter
, int , DefaultFilter
)
532 IMPLEMENT_DYNAMIC_CLASS(wxGenericDirCtrl
, wxControl
)
535 BEGIN_EVENT_TABLE(wxGenericDirCtrl
, wxControl
)
536 EVT_TREE_ITEM_EXPANDING (wxID_TREECTRL
, wxGenericDirCtrl::OnExpandItem
)
537 EVT_TREE_ITEM_COLLAPSED (wxID_TREECTRL
, wxGenericDirCtrl::OnCollapseItem
)
538 EVT_TREE_BEGIN_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnBeginEditItem
)
539 EVT_TREE_END_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnEndEditItem
)
540 EVT_SIZE (wxGenericDirCtrl::OnSize
)
543 wxGenericDirCtrl::wxGenericDirCtrl(void)
548 bool wxGenericDirCtrl::Create(wxWindow
*parent
,
554 const wxString
& filter
,
556 const wxString
& name
)
558 if (!wxControl::Create(parent
, id
, pos
, size
, style
, wxDefaultValidator
, name
))
561 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE
));
565 long treeStyle
= wxTR_HAS_BUTTONS
| wxTR_HIDE_ROOT
;
567 if (style
& wxDIRCTRL_EDIT_LABELS
)
568 treeStyle
|= wxTR_EDIT_LABELS
;
570 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
571 treeStyle
|= wxNO_BORDER
;
573 treeStyle
|= wxBORDER_SUNKEN
;
575 long filterStyle
= 0;
576 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
577 filterStyle
|= wxNO_BORDER
;
579 filterStyle
|= wxBORDER_SUNKEN
;
581 m_treeCtrl
= new wxTreeCtrl(this, wxID_TREECTRL
,
582 wxPoint(0,0), GetClientSize(), treeStyle
);
584 if (!filter
.IsEmpty() && (style
& wxDIRCTRL_SHOW_FILTERS
))
585 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
, wxDefaultPosition
, wxDefaultSize
, filterStyle
);
590 SetFilterIndex(defaultFilter
);
592 if (m_filterListCtrl
)
593 m_filterListCtrl
->FillFilterList(filter
, defaultFilter
);
595 m_treeCtrl
->SetImageList(wxTheFileIconsTable
->GetSmallImageList());
597 m_showHidden
= false;
598 wxDirItemData
* rootData
= new wxDirItemData(wxEmptyString
, wxEmptyString
, true);
602 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
603 rootName
= _("Computer");
605 rootName
= _("Sections");
608 m_rootId
= m_treeCtrl
->AddRoot( rootName
, 3, -1, rootData
);
609 m_treeCtrl
->SetItemHasChildren(m_rootId
);
610 ExpandDir(m_rootId
); // automatically expand first level
612 // Expand and select the default path
613 if (!m_defaultPath
.IsEmpty())
614 ExpandPath(m_defaultPath
);
622 wxGenericDirCtrl::~wxGenericDirCtrl()
626 void wxGenericDirCtrl::Init()
628 m_showHidden
= false;
630 m_currentFilterStr
= wxEmptyString
; // Default: any file
632 m_filterListCtrl
= NULL
;
635 void wxGenericDirCtrl::ShowHidden( bool show
)
639 wxString path
= GetPath();
645 wxGenericDirCtrl::AddSection(const wxString
& path
, const wxString
& name
, int imageId
)
647 wxDirItemData
*dir_item
= new wxDirItemData(path
,name
,true);
649 wxTreeItemId id
= AppendItem( m_rootId
, name
, imageId
, -1, dir_item
);
651 m_treeCtrl
->SetItemHasChildren(id
);
656 void wxGenericDirCtrl::SetupSections()
658 wxArrayString paths
, names
;
661 size_t n
, count
= wxGetAvailableDrives(paths
, names
, icons
);
663 for (n
= 0; n
< count
; n
++)
665 AddSection(paths
[n
], names
[n
], icons
[n
]);
669 void wxGenericDirCtrl::OnBeginEditItem(wxTreeEvent
&event
)
671 // don't rename the main entry "Sections"
672 if (event
.GetItem() == m_rootId
)
678 // don't rename the individual sections
679 if (m_treeCtrl
->GetItemParent( event
.GetItem() ) == m_rootId
)
686 void wxGenericDirCtrl::OnEndEditItem(wxTreeEvent
&event
)
688 if ((event
.GetLabel().IsEmpty()) ||
689 (event
.GetLabel() == _(".")) ||
690 (event
.GetLabel() == _("..")) ||
691 (event
.GetLabel().Find(wxT('/')) != wxNOT_FOUND
) ||
692 (event
.GetLabel().Find(wxT('\\')) != wxNOT_FOUND
) ||
693 (event
.GetLabel().Find(wxT('|')) != wxNOT_FOUND
))
695 wxMessageDialog
dialog(this, _("Illegal directory name."), _("Error"), wxOK
| wxICON_ERROR
);
701 wxTreeItemId id
= event
.GetItem();
702 wxDirItemData
*data
= (wxDirItemData
*)m_treeCtrl
->GetItemData( id
);
705 wxString
new_name( wxPathOnly( data
->m_path
) );
706 new_name
+= wxString(wxFILE_SEP_PATH
);
707 new_name
+= event
.GetLabel();
711 if (wxFileExists(new_name
))
713 wxMessageDialog
dialog(this, _("File name exists already."), _("Error"), wxOK
| wxICON_ERROR
);
718 if (wxRenameFile(data
->m_path
,new_name
))
720 data
->SetNewDirName( new_name
);
724 wxMessageDialog
dialog(this, _("Operation not permitted."), _("Error"), wxOK
| wxICON_ERROR
);
730 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent
&event
)
732 wxTreeItemId parentId
= event
.GetItem();
734 // VS: this is needed because the event handler is called from wxTreeCtrl
735 // ctor when wxTR_HIDE_ROOT was specified
737 if (!m_rootId
.IsOk())
739 m_rootId
= m_treeCtrl
->GetRootItem();
744 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent
&event
)
746 CollapseDir(event
.GetItem());
749 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId
)
753 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
754 if (!data
->m_isExpanded
)
757 data
->m_isExpanded
= false;
758 wxTreeItemIdValue cookie
;
759 /* Workaround because DeleteChildren has disapeared (why?) and
760 * CollapseAndReset doesn't work as advertised (deletes parent too) */
761 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
764 m_treeCtrl
->Delete(child
);
765 /* Not GetNextChild below, because the cookie mechanism can't
766 * handle disappearing children! */
767 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
771 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId
)
773 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
775 if (data
->m_isExpanded
)
778 data
->m_isExpanded
= true;
780 if (parentId
== m_treeCtrl
->GetRootItem())
788 wxString search
,path
,filename
;
790 wxString
dirName(data
->m_path
);
792 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
793 // Check if this is a root directory and if so,
794 // whether the drive is avaiable.
795 if (!wxIsDriveAvailable(dirName
))
797 data
->m_isExpanded
= false;
798 //wxMessageBox(wxT("Sorry, this drive is not available."));
803 // This may take a longish time. Go to busy cursor
806 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
807 if (dirName
.Last() == ':')
808 dirName
+= wxString(wxFILE_SEP_PATH
);
812 wxArrayString filenames
;
815 wxString eachFilename
;
822 int style
= wxDIR_DIRS
;
823 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
824 if (d
.GetFirst(& eachFilename
, wxEmptyString
, style
))
828 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
830 dirs
.Add(eachFilename
);
833 while (d
.GetNext(&eachFilename
));
836 dirs
.Sort(wxDirCtrlStringCompareFunction
);
838 // Now do the filenames -- but only if we're allowed to
839 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
847 int style
= wxDIR_FILES
;
848 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
849 // Process each filter (ex: "JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg")
850 wxStringTokenizer strTok
;
852 strTok
.SetString(m_currentFilterStr
,wxT(";"));
853 while(strTok
.HasMoreTokens())
855 curFilter
= strTok
.GetNextToken();
856 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, style
))
860 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
862 filenames
.Add(eachFilename
);
865 while (d
.GetNext(& eachFilename
));
869 filenames
.Sort(wxDirCtrlStringCompareFunction
);
872 // Add the sorted dirs
874 for (i
= 0; i
< dirs
.Count(); i
++)
876 wxString
eachFilename(dirs
[i
]);
878 if (!wxEndsWithPathSeparator(path
))
879 path
+= wxString(wxFILE_SEP_PATH
);
880 path
+= eachFilename
;
882 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,true);
883 wxTreeItemId id
= AppendItem( parentId
, eachFilename
,
884 wxFileIconsTable::folder
, -1, dir_item
);
885 m_treeCtrl
->SetItemImage( id
, wxFileIconsTable::folder_open
,
886 wxTreeItemIcon_Expanded
);
888 // Has this got any children? If so, make it expandable.
889 // (There are two situations when a dir has children: either it
890 // has subdirectories or it contains files that weren't filtered
891 // out. The latter only applies to dirctrl with files.)
892 if ( dir_item
->HasSubDirs() ||
893 (((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0) &&
894 dir_item
->HasFiles(m_currentFilterStr
)) )
896 m_treeCtrl
->SetItemHasChildren(id
);
900 // Add the sorted filenames
901 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
903 for (i
= 0; i
< filenames
.Count(); i
++)
905 wxString
eachFilename(filenames
[i
]);
907 if (!wxEndsWithPathSeparator(path
))
908 path
+= wxString(wxFILE_SEP_PATH
);
909 path
+= eachFilename
;
910 //path = dirName + wxString(wxT("/")) + eachFilename;
911 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,false);
912 int image_id
= wxFileIconsTable::file
;
913 if (eachFilename
.Find(wxT('.')) != wxNOT_FOUND
)
914 image_id
= wxTheFileIconsTable
->GetIconID(eachFilename
.AfterLast(wxT('.')));
915 (void) AppendItem( parentId
, eachFilename
, image_id
, -1, dir_item
);
920 void wxGenericDirCtrl::ReCreateTree()
922 CollapseDir(m_treeCtrl
->GetRootItem());
923 ExpandDir(m_treeCtrl
->GetRootItem());
926 // Find the child that matches the first part of 'path'.
927 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
928 // then the child for /usr is returned.
929 wxTreeItemId
wxGenericDirCtrl::FindChild(wxTreeItemId parentId
, const wxString
& path
, bool& done
)
931 wxString
path2(path
);
933 // Make sure all separators are as per the current platform
934 path2
.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH
));
935 path2
.Replace(wxT("/"), wxString(wxFILE_SEP_PATH
));
937 // Append a separator to foil bogus substring matching
938 path2
+= wxString(wxFILE_SEP_PATH
);
940 // In MSW or PM, case is not significant
941 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
945 wxTreeItemIdValue cookie
;
946 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
947 while (childId
.IsOk())
949 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
951 if (data
&& !data
->m_path
.IsEmpty())
953 wxString
childPath(data
->m_path
);
954 if (!wxEndsWithPathSeparator(childPath
))
955 childPath
+= wxString(wxFILE_SEP_PATH
);
957 // In MSW and PM, case is not significant
958 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
959 childPath
.MakeLower();
962 if (childPath
.Len() <= path2
.Len())
964 wxString path3
= path2
.Mid(0, childPath
.Len());
965 if (childPath
== path3
)
967 if (path3
.Len() == path2
.Len())
976 childId
= m_treeCtrl
->GetNextChild(parentId
, cookie
);
978 wxTreeItemId invalid
;
982 // Try to expand as much of the given path as possible,
983 // and select the given tree item.
984 bool wxGenericDirCtrl::ExpandPath(const wxString
& path
)
987 wxTreeItemId id
= FindChild(m_rootId
, path
, done
);
988 wxTreeItemId lastId
= id
; // The last non-zero id
989 while (id
.IsOk() && !done
)
993 id
= FindChild(id
, path
, done
);
999 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(lastId
);
1002 m_treeCtrl
->Expand(lastId
);
1004 if ((GetWindowStyle() & wxDIRCTRL_SELECT_FIRST
) && data
->m_isDir
)
1006 // Find the first file in this directory
1007 wxTreeItemIdValue cookie
;
1008 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(lastId
, cookie
);
1009 bool selectedChild
= false;
1010 while (childId
.IsOk())
1012 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
1014 if (data
&& data
->m_path
!= wxEmptyString
&& !data
->m_isDir
)
1016 m_treeCtrl
->SelectItem(childId
);
1017 m_treeCtrl
->EnsureVisible(childId
);
1018 selectedChild
= true;
1021 childId
= m_treeCtrl
->GetNextChild(lastId
, cookie
);
1025 m_treeCtrl
->SelectItem(lastId
);
1026 m_treeCtrl
->EnsureVisible(lastId
);
1031 m_treeCtrl
->SelectItem(lastId
);
1032 m_treeCtrl
->EnsureVisible(lastId
);
1041 wxString
wxGenericDirCtrl::GetPath() const
1043 wxTreeItemId id
= m_treeCtrl
->GetSelection();
1046 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1047 return data
->m_path
;
1050 return wxEmptyString
;
1053 wxString
wxGenericDirCtrl::GetFilePath() const
1055 wxTreeItemId id
= m_treeCtrl
->GetSelection();
1058 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1060 return wxEmptyString
;
1062 return data
->m_path
;
1065 return wxEmptyString
;
1068 void wxGenericDirCtrl::SetPath(const wxString
& path
)
1070 m_defaultPath
= path
;
1077 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId id
, int dirFlags
, wxArrayString
& filenames
)
1079 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1081 // This may take a longish time. Go to busy cursor
1086 wxString search
,path
,filename
;
1088 wxString
dirName(data
->m_path
);
1090 #if defined(__WXMSW__) || defined(__OS2__)
1091 if (dirName
.Last() == ':')
1092 dirName
+= wxString(wxFILE_SEP_PATH
);
1096 wxString eachFilename
;
1103 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, dirFlags
))
1107 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
1109 filenames
.Add(eachFilename
);
1112 while (d
.GetNext(& eachFilename
)) ;
1118 void wxGenericDirCtrl::SetFilterIndex(int n
)
1120 m_currentFilter
= n
;
1123 if (ExtractWildcard(m_filter
, n
, f
, d
))
1124 m_currentFilterStr
= f
;
1126 m_currentFilterStr
= wxT("*.*");
1129 void wxGenericDirCtrl::SetFilter(const wxString
& filter
)
1134 if (ExtractWildcard(m_filter
, m_currentFilter
, f
, d
))
1135 m_currentFilterStr
= f
;
1137 m_currentFilterStr
= wxT("*.*");
1140 // Extract description and actual filter from overall filter string
1141 bool wxGenericDirCtrl::ExtractWildcard(const wxString
& filterStr
, int n
, wxString
& filter
, wxString
& description
)
1143 wxArrayString filters
, descriptions
;
1144 int count
= wxParseCommonDialogsFilter(filterStr
, descriptions
, filters
);
1145 if (count
> 0 && n
< count
)
1147 filter
= filters
[n
];
1148 description
= descriptions
[n
];
1155 #if WXWIN_COMPATIBILITY_2_4
1156 // Parses the global filter, returning the number of filters.
1157 // Returns 0 if none or if there's a problem.
1158 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpg"
1159 int wxGenericDirCtrl::ParseFilter(const wxString
& filterStr
, wxArrayString
& filters
, wxArrayString
& descriptions
)
1161 return wxParseCommonDialogsFilter(filterStr
, descriptions
, filters
);
1163 #endif // WXWIN_COMPATIBILITY_2_4
1165 void wxGenericDirCtrl::DoResize()
1167 wxSize sz
= GetClientSize();
1168 int verticalSpacing
= 3;
1172 if (m_filterListCtrl
)
1175 // For some reason, this is required in order for the
1176 // correct control height to always be returned, rather
1177 // than the drop-down list height which is sometimes returned.
1178 wxSize oldSize
= m_filterListCtrl
->GetSize();
1179 m_filterListCtrl
->SetSize(wxDefaultCoord
,
1183 wxSIZE_USE_EXISTING
);
1184 m_filterListCtrl
->SetSize(wxDefaultCoord
,
1188 wxSIZE_USE_EXISTING
);
1190 filterSz
= m_filterListCtrl
->GetSize();
1191 sz
.y
-= (filterSz
.y
+ verticalSpacing
);
1193 m_treeCtrl
->SetSize(0, 0, sz
.x
, sz
.y
);
1194 if (m_filterListCtrl
)
1196 m_filterListCtrl
->SetSize(0, sz
.y
+ verticalSpacing
, sz
.x
, filterSz
.y
);
1197 // Don't know why, but this needs refreshing after a resize (wxMSW)
1198 m_filterListCtrl
->Refresh();
1204 void wxGenericDirCtrl::OnSize(wxSizeEvent
& WXUNUSED(event
))
1209 wxTreeItemId
wxGenericDirCtrl::AppendItem (const wxTreeItemId
& parent
,
1210 const wxString
& text
,
1211 int image
, int selectedImage
,
1212 wxTreeItemData
* data
)
1214 wxTreeCtrl
*treeCtrl
= GetTreeCtrl ();
1216 wxASSERT (treeCtrl
);
1220 return treeCtrl
->AppendItem (parent
, text
, image
, selectedImage
, data
);
1224 return wxTreeItemId();
1229 //-----------------------------------------------------------------------------
1230 // wxDirFilterListCtrl
1231 //-----------------------------------------------------------------------------
1233 IMPLEMENT_CLASS(wxDirFilterListCtrl
, wxChoice
)
1235 BEGIN_EVENT_TABLE(wxDirFilterListCtrl
, wxChoice
)
1236 EVT_CHOICE(wxID_ANY
, wxDirFilterListCtrl::OnSelFilter
)
1239 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl
* parent
, const wxWindowID id
,
1245 return wxChoice::Create(parent
, id
, pos
, size
, 0, NULL
, style
);
1248 void wxDirFilterListCtrl::Init()
1253 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent
& WXUNUSED(event
))
1255 int sel
= GetSelection();
1257 wxString currentPath
= m_dirCtrl
->GetPath();
1259 m_dirCtrl
->SetFilterIndex(sel
);
1261 // If the filter has changed, the view is out of date, so
1262 // collapse the tree.
1263 m_dirCtrl
->ReCreateTree();
1265 // Try to restore the selection, or at least the directory
1266 m_dirCtrl
->ExpandPath(currentPath
);
1269 void wxDirFilterListCtrl::FillFilterList(const wxString
& filter
, int defaultFilter
)
1272 wxArrayString descriptions
, filters
;
1273 size_t n
= (size_t) wxParseCommonDialogsFilter(filter
, filters
, descriptions
);
1275 if (n
> 0 && defaultFilter
< (int) n
)
1277 for (size_t i
= 0; i
< n
; i
++)
1278 Append(descriptions
[i
]);
1279 SetSelection(defaultFilter
);
1282 #endif // wxUSE_DIRDLG
1284 #if wxUSE_DIRDLG || wxUSE_FILEDLG
1286 // ----------------------------------------------------------------------------
1287 // wxFileIconsTable icons
1288 // ----------------------------------------------------------------------------
1291 static const char * file_icons_tbl_folder_open_xpm
[] = {
1292 /* width height ncolors chars_per_pixel */
1320 static const char * file_icons_tbl_computer_xpm
[] = {
1347 static const char * file_icons_tbl_drive_xpm
[] = {
1374 static const char *file_icons_tbl_cdrom_xpm
[] = {
1404 static const char * file_icons_tbl_floppy_xpm
[] = {
1431 static const char * file_icons_tbl_removeable_xpm
[] = {
1457 // ----------------------------------------------------------------------------
1458 // wxFileIconsTable & friends
1459 // ----------------------------------------------------------------------------
1461 // global instance of a wxFileIconsTable
1462 wxFileIconsTable
* wxTheFileIconsTable
= (wxFileIconsTable
*)NULL
;
1464 // A module to allow icons table cleanup
1466 class wxFileIconsTableModule
: public wxModule
1468 DECLARE_DYNAMIC_CLASS(wxFileIconsTableModule
)
1470 wxFileIconsTableModule() {}
1471 bool OnInit() { wxTheFileIconsTable
= new wxFileIconsTable
; return true; }
1474 if (wxTheFileIconsTable
)
1476 delete wxTheFileIconsTable
;
1477 wxTheFileIconsTable
= NULL
;
1482 IMPLEMENT_DYNAMIC_CLASS(wxFileIconsTableModule
, wxModule
)
1484 class wxFileIconEntry
: public wxObject
1487 wxFileIconEntry(int i
) { id
= i
; }
1492 wxFileIconsTable::wxFileIconsTable()
1495 m_smallImageList
= NULL
;
1498 wxFileIconsTable::~wxFileIconsTable()
1502 WX_CLEAR_HASH_TABLE(*m_HashTable
);
1505 if (m_smallImageList
) delete m_smallImageList
;
1508 // delayed initialization - wait until first use (wxArtProv not created yet)
1509 void wxFileIconsTable::Create()
1511 wxCHECK_RET(!m_smallImageList
&& !m_HashTable
, wxT("creating icons twice"));
1512 m_HashTable
= new wxHashTable(wxKEY_STRING
);
1513 m_smallImageList
= new wxImageList(16, 16);
1516 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER
, wxART_CMN_DIALOG
));
1518 m_smallImageList
->Add(wxIcon(file_icons_tbl_folder_open_xpm
));
1520 m_smallImageList
->Add(wxIcon(file_icons_tbl_computer_xpm
));
1522 m_smallImageList
->Add(wxIcon(file_icons_tbl_drive_xpm
));
1524 m_smallImageList
->Add(wxIcon(file_icons_tbl_cdrom_xpm
));
1526 m_smallImageList
->Add(wxIcon(file_icons_tbl_floppy_xpm
));
1528 m_smallImageList
->Add(wxIcon(file_icons_tbl_removeable_xpm
));
1530 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE
, wxART_CMN_DIALOG
));
1532 if (GetIconID(wxEmptyString
, _T("application/x-executable")) == file
)
1534 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE
, wxART_CMN_DIALOG
));
1535 delete m_HashTable
->Get(_T("exe"));
1536 m_HashTable
->Delete(_T("exe"));
1537 m_HashTable
->Put(_T("exe"), new wxFileIconEntry(executable
));
1539 /* else put into list by GetIconID
1540 (KDE defines application/x-executable for *.exe and has nice icon)
1544 wxImageList
*wxFileIconsTable::GetSmallImageList()
1546 if (!m_smallImageList
)
1549 return m_smallImageList
;
1552 #if wxUSE_MIMETYPE && wxUSE_IMAGE
1553 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
1554 // one icon and we won't resize it
1556 static wxBitmap
CreateAntialiasedBitmap(const wxImage
& img
)
1558 const unsigned int size
= 16;
1560 wxImage
smallimg (size
, size
);
1561 unsigned char *p1
, *p2
, *ps
;
1562 unsigned char mr
= img
.GetMaskRed(),
1563 mg
= img
.GetMaskGreen(),
1564 mb
= img
.GetMaskBlue();
1567 unsigned sr
, sg
, sb
, smask
;
1569 p1
= img
.GetData(), p2
= img
.GetData() + 3 * size
*2, ps
= smallimg
.GetData();
1570 smallimg
.SetMaskColour(mr
, mr
, mr
);
1572 for (y
= 0; y
< size
; y
++)
1574 for (x
= 0; x
< size
; x
++)
1576 sr
= sg
= sb
= smask
= 0;
1577 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1578 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1581 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1582 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1585 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1586 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1589 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1590 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1595 ps
[0] = ps
[1] = ps
[2] = mr
;
1597 ps
[0] = sr
>> 2, ps
[1] = sg
>> 2, ps
[2] = sb
>> 2;
1600 p1
+= size
*2 * 3, p2
+= size
*2 * 3;
1603 return wxBitmap(smallimg
);
1606 // This function is currently not unused anymore
1608 // finds empty borders and return non-empty area of image:
1609 static wxImage
CutEmptyBorders(const wxImage
& img
)
1611 unsigned char mr
= img
.GetMaskRed(),
1612 mg
= img
.GetMaskGreen(),
1613 mb
= img
.GetMaskBlue();
1614 unsigned char *dt
= img
.GetData(), *dttmp
;
1615 unsigned w
= img
.GetWidth(), h
= img
.GetHeight();
1617 unsigned top
, bottom
, left
, right
, i
;
1620 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
1621 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = false; break;}
1623 for (empt
= true, top
= 0; empt
&& top
< h
; top
++)
1626 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1629 for (empt
= true, bottom
= h
-1; empt
&& bottom
> top
; bottom
--)
1631 MK_DTTMP(0, bottom
);
1632 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1635 for (empt
= true, left
= 0; empt
&& left
< w
; left
++)
1638 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1641 for (empt
= true, right
= w
-1; empt
&& right
> left
; right
--)
1644 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1647 top
--, left
--, bottom
++, right
++;
1649 return img
.GetSubImage(wxRect(left
, top
, right
- left
+ 1, bottom
- top
+ 1));
1653 #endif // wxUSE_MIMETYPE
1655 int wxFileIconsTable::GetIconID(const wxString
& extension
, const wxString
& mime
)
1657 if (!m_smallImageList
)
1661 if (!extension
.IsEmpty())
1663 wxFileIconEntry
*entry
= (wxFileIconEntry
*) m_HashTable
->Get(extension
);
1664 if (entry
) return (entry
-> id
);
1667 wxFileType
*ft
= (mime
.IsEmpty()) ?
1668 wxTheMimeTypesManager
-> GetFileTypeFromExtension(extension
) :
1669 wxTheMimeTypesManager
-> GetFileTypeFromMimeType(mime
);
1671 wxIconLocation iconLoc
;
1676 if ( ft
&& ft
->GetIcon(&iconLoc
) )
1678 ic
= wxIcon( iconLoc
.GetFileName() );
1687 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1692 bmp
.CopyFromIcon(ic
);
1697 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1701 const unsigned int size
= 16;
1703 int id
= m_smallImageList
->GetImageCount();
1704 if ((bmp
.GetWidth() == (int) size
) && (bmp
.GetHeight() == (int) size
))
1706 m_smallImageList
->Add(bmp
);
1711 wxImage img
= bmp
.ConvertToImage();
1713 if ((img
.GetWidth() != size
*2) || (img
.GetHeight() != size
*2))
1714 // m_smallImageList->Add(CreateAntialiasedBitmap(CutEmptyBorders(img).Rescale(size*2, size*2)));
1715 m_smallImageList
->Add(CreateAntialiasedBitmap(img
.Rescale(size
*2, size
*2)));
1717 m_smallImageList
->Add(CreateAntialiasedBitmap(img
));
1719 #endif // wxUSE_IMAGE
1721 m_HashTable
->Put(extension
, new wxFileIconEntry(id
));
1724 #else // !wxUSE_MIMETYPE
1726 if (extension
== wxT("exe"))
1730 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
1733 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG