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, OS2, MAC, UNIX (returns "/")
107 // ----------------------------------------------------------------------------
109 size_t wxGetAvailableDrives(wxArrayString
&paths
, wxArrayString
&names
, wxArrayInt
&icon_ids
)
111 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
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
]);
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'))
158 #elif defined(__OS2__)
160 ULONG ulDriveNum
= 0;
161 ULONG ulDriveMap
= 0;
162 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 return paths
.GetCount();
297 // ----------------------------------------------------------------------------
298 // wxIsDriveAvailable
299 // ----------------------------------------------------------------------------
303 bool wxIsDriveAvailable(const wxString
& dirName
)
305 // FIXME_MGL - this method leads to hang up under Watcom for some reason
307 if ( dirName
.Len() == 3 && dirName
[1u] == wxT(':') )
309 wxString
dirNameLower(dirName
.Lower());
310 // VS: always return TRUE for removable media, since Win95 doesn't
311 // like it when MS-DOS app accesses empty floppy drive
312 return (dirNameLower
[0u] == wxT('a') ||
313 dirNameLower
[0u] == wxT('b') ||
314 wxPathExists(dirNameLower
));
321 #elif defined(__WINDOWS__) || defined(__OS2__)
323 int setdrive(int drive
)
327 #elif defined(__GNUWIN32__) && \
328 (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
329 return _chdrive(drive
);
333 if (drive
< 1 || drive
> 31)
335 newdrive
[0] = (wxChar
)(wxT('A') + drive
- 1);
336 newdrive
[1] = wxT(':');
338 newdrive
[2] = wxT('\\');
339 newdrive
[3] = wxT('\0');
341 newdrive
[2] = wxT('\0');
343 #if defined(__WXMSW__)
344 if (::SetCurrentDirectory(newdrive
))
346 // VA doesn't know what LPSTR is and has its own set
347 if (!DosSetCurrentDir((PSZ
)newdrive
))
355 bool wxIsDriveAvailable(const wxString
& dirName
)
361 UINT errorMode
= SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOOPENFILEERRORBOX
);
365 // Check if this is a root directory and if so,
366 // whether the drive is available.
367 if (dirName
.Len() == 3 && dirName
[(size_t)1] == wxT(':'))
369 wxString
dirNameLower(dirName
.Lower());
370 #if defined(__GNUWIN32__) && !(defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
371 success
= wxPathExists(dirNameLower
);
374 // Avoid changing to drive since no media may be inserted.
375 if (dirNameLower
[(size_t)0] == 'a' || dirNameLower
[(size_t)0] == 'b')
378 int currentDrive
= _getdrive();
379 int thisDrive
= (int) (dirNameLower
[(size_t)0] - 'a' + 1) ;
380 int err
= setdrive( thisDrive
) ;
381 setdrive( currentDrive
);
390 (void) SetErrorMode(errorMode
);
396 #endif // __WINDOWS__ || __OS2__
399 // Function which is called by quick sort. We want to override the default wxArrayString behaviour,
400 // and sort regardless of case.
401 static int wxCMPFUNC_CONV
wxDirCtrlStringCompareFunction(wxString
* strFirst
, wxString
* strSecond
)
403 return strFirst
->CmpNoCase(*strSecond
);
406 //-----------------------------------------------------------------------------
408 //-----------------------------------------------------------------------------
410 wxDirItemData::wxDirItemData(const wxString
& path
, const wxString
& name
,
415 /* Insert logic to detect hidden files here
416 * In UnixLand we just check whether the first char is a dot
417 * For FileNameFromPath read LastDirNameInThisPath ;-) */
418 // m_isHidden = (bool)(wxFileNameFromPath(*m_path)[0] == '.');
420 m_isExpanded
= FALSE
;
424 wxDirItemData::~wxDirItemData()
428 void wxDirItemData::SetNewDirName(const wxString
& path
)
431 m_name
= wxFileNameFromPath(path
);
434 bool wxDirItemData::HasSubDirs() const
436 if (m_path
.IsEmpty())
442 if ( !dir
.Open(m_path
) )
446 return dir
.HasSubDirs();
449 bool wxDirItemData::HasFiles(const wxString
& WXUNUSED(spec
)) const
451 if (m_path
.IsEmpty())
457 if ( !dir
.Open(m_path
) )
461 return dir
.HasFiles();
464 //-----------------------------------------------------------------------------
466 //-----------------------------------------------------------------------------
469 #if wxUSE_EXTENDED_RTTI
470 WX_DEFINE_FLAGS( wxGenericDirCtrlStyle
)
472 wxBEGIN_FLAGS( wxGenericDirCtrlStyle
)
473 // new style border flags, we put them first to
474 // use them for streaming out
475 wxFLAGS_MEMBER(wxBORDER_SIMPLE
)
476 wxFLAGS_MEMBER(wxBORDER_SUNKEN
)
477 wxFLAGS_MEMBER(wxBORDER_DOUBLE
)
478 wxFLAGS_MEMBER(wxBORDER_RAISED
)
479 wxFLAGS_MEMBER(wxBORDER_STATIC
)
480 wxFLAGS_MEMBER(wxBORDER_NONE
)
482 // old style border flags
483 wxFLAGS_MEMBER(wxSIMPLE_BORDER
)
484 wxFLAGS_MEMBER(wxSUNKEN_BORDER
)
485 wxFLAGS_MEMBER(wxDOUBLE_BORDER
)
486 wxFLAGS_MEMBER(wxRAISED_BORDER
)
487 wxFLAGS_MEMBER(wxSTATIC_BORDER
)
488 wxFLAGS_MEMBER(wxBORDER
)
490 // standard window styles
491 wxFLAGS_MEMBER(wxTAB_TRAVERSAL
)
492 wxFLAGS_MEMBER(wxCLIP_CHILDREN
)
493 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW
)
494 wxFLAGS_MEMBER(wxWANTS_CHARS
)
495 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE
)
496 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB
)
497 wxFLAGS_MEMBER(wxVSCROLL
)
498 wxFLAGS_MEMBER(wxHSCROLL
)
500 wxFLAGS_MEMBER(wxDIRCTRL_DIR_ONLY
)
501 wxFLAGS_MEMBER(wxDIRCTRL_3D_INTERNAL
)
502 wxFLAGS_MEMBER(wxDIRCTRL_SELECT_FIRST
)
503 wxFLAGS_MEMBER(wxDIRCTRL_SHOW_FILTERS
)
505 wxEND_FLAGS( wxGenericDirCtrlStyle
)
507 IMPLEMENT_DYNAMIC_CLASS_XTI(wxGenericDirCtrl
, wxControl
,"wx/dirctrl.h")
509 wxBEGIN_PROPERTIES_TABLE(wxGenericDirCtrl
)
510 wxHIDE_PROPERTY( Children
)
511 wxPROPERTY( DefaultPath
, wxString
, SetDefaultPath
, GetDefaultPath
, , 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
512 wxPROPERTY( Filter
, wxString
, SetFilter
, GetFilter
,, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
513 wxPROPERTY( DefaultFilter
, int , SetFilterIndex
, GetFilterIndex
,, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
514 wxEND_PROPERTIES_TABLE()
516 wxBEGIN_HANDLERS_TABLE(wxGenericDirCtrl
)
517 wxEND_HANDLERS_TABLE()
519 wxCONSTRUCTOR_8( wxGenericDirCtrl
, wxWindow
* , Parent
, wxWindowID
, Id
, wxString
, DefaultPath
,
520 wxPoint
, Position
, wxSize
, Size
, long , WindowStyle
, wxString
, Filter
, int , DefaultFilter
)
522 IMPLEMENT_DYNAMIC_CLASS(wxGenericDirCtrl
, wxControl
)
525 BEGIN_EVENT_TABLE(wxGenericDirCtrl
, wxControl
)
526 EVT_TREE_ITEM_EXPANDING (-1, wxGenericDirCtrl::OnExpandItem
)
527 EVT_TREE_ITEM_COLLAPSED (-1, wxGenericDirCtrl::OnCollapseItem
)
528 EVT_TREE_BEGIN_LABEL_EDIT (-1, wxGenericDirCtrl::OnBeginEditItem
)
529 EVT_TREE_END_LABEL_EDIT (-1, wxGenericDirCtrl::OnEndEditItem
)
530 EVT_SIZE (wxGenericDirCtrl::OnSize
)
533 wxGenericDirCtrl::wxGenericDirCtrl(void)
538 bool wxGenericDirCtrl::Create(wxWindow
*parent
,
544 const wxString
& filter
,
546 const wxString
& name
)
548 if (!wxControl::Create(parent
, id
, pos
, size
, style
, wxDefaultValidator
, name
))
551 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE
));
555 long treeStyle
= wxTR_HAS_BUTTONS
| wxTR_HIDE_ROOT
;
557 if (style
& wxDIRCTRL_EDIT_LABELS
)
558 treeStyle
|= wxTR_EDIT_LABELS
;
560 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
561 treeStyle
|= wxNO_BORDER
;
563 treeStyle
|= wxBORDER_SUNKEN
;
565 long filterStyle
= 0;
566 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
567 filterStyle
|= wxNO_BORDER
;
569 filterStyle
|= wxBORDER_SUNKEN
;
571 m_treeCtrl
= new wxTreeCtrl(this, wxID_TREECTRL
, pos
, size
, treeStyle
);
573 if (!filter
.IsEmpty() && (style
& wxDIRCTRL_SHOW_FILTERS
))
574 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
, wxDefaultPosition
, wxDefaultSize
, filterStyle
);
579 SetFilterIndex(defaultFilter
);
581 if (m_filterListCtrl
)
582 m_filterListCtrl
->FillFilterList(filter
, defaultFilter
);
584 m_treeCtrl
->SetImageList(wxTheFileIconsTable
->GetSmallImageList());
586 m_showHidden
= FALSE
;
587 wxDirItemData
* rootData
= new wxDirItemData(wxT(""), wxT(""), TRUE
);
591 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
592 rootName
= _("Computer");
594 rootName
= _("Sections");
597 m_rootId
= m_treeCtrl
->AddRoot( rootName
, 3, -1, rootData
);
598 m_treeCtrl
->SetItemHasChildren(m_rootId
);
599 ExpandDir(m_rootId
); // automatically expand first level
601 // Expand and select the default path
602 if (!m_defaultPath
.IsEmpty())
603 ExpandPath(m_defaultPath
);
610 wxGenericDirCtrl::~wxGenericDirCtrl()
614 void wxGenericDirCtrl::Init()
616 m_showHidden
= FALSE
;
618 m_currentFilterStr
= wxEmptyString
; // Default: any file
620 m_filterListCtrl
= NULL
;
623 void wxGenericDirCtrl::ShowHidden( bool show
)
627 wxString path
= GetPath();
633 wxGenericDirCtrl::AddSection(const wxString
& path
, const wxString
& name
, int imageId
)
635 wxDirItemData
*dir_item
= new wxDirItemData(path
,name
,TRUE
);
637 wxTreeItemId id
= AppendItem( m_rootId
, name
, imageId
, -1, dir_item
);
639 m_treeCtrl
->SetItemHasChildren(id
);
644 void wxGenericDirCtrl::SetupSections()
646 wxArrayString paths
, names
;
649 size_t n
, count
= wxGetAvailableDrives(paths
, names
, icons
);
651 for (n
= 0; n
< count
; n
++)
653 AddSection(paths
[n
], names
[n
], icons
[n
]);
657 void wxGenericDirCtrl::OnBeginEditItem(wxTreeEvent
&event
)
659 // don't rename the main entry "Sections"
660 if (event
.GetItem() == m_rootId
)
666 // don't rename the individual sections
667 if (m_treeCtrl
->GetItemParent( event
.GetItem() ) == m_rootId
)
674 void wxGenericDirCtrl::OnEndEditItem(wxTreeEvent
&event
)
676 if ((event
.GetLabel().IsEmpty()) ||
677 (event
.GetLabel() == _(".")) ||
678 (event
.GetLabel() == _("..")) ||
679 (event
.GetLabel().Find(wxT('/')) != wxNOT_FOUND
) ||
680 (event
.GetLabel().Find(wxT('\\')) != wxNOT_FOUND
) ||
681 (event
.GetLabel().Find(wxT('|')) != wxNOT_FOUND
))
683 wxMessageDialog
dialog(this, _("Illegal directory name."), _("Error"), wxOK
| wxICON_ERROR
);
689 wxTreeItemId id
= event
.GetItem();
690 wxDirItemData
*data
= (wxDirItemData
*)m_treeCtrl
->GetItemData( id
);
693 wxString
new_name( wxPathOnly( data
->m_path
) );
694 new_name
+= wxString(wxFILE_SEP_PATH
);
695 new_name
+= event
.GetLabel();
699 if (wxFileExists(new_name
))
701 wxMessageDialog
dialog(this, _("File name exists already."), _("Error"), wxOK
| wxICON_ERROR
);
706 if (wxRenameFile(data
->m_path
,new_name
))
708 data
->SetNewDirName( new_name
);
712 wxMessageDialog
dialog(this, _("Operation not permitted."), _("Error"), wxOK
| wxICON_ERROR
);
718 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent
&event
)
720 wxTreeItemId parentId
= event
.GetItem();
722 // VS: this is needed because the event handler is called from wxTreeCtrl
723 // ctor when wxTR_HIDE_ROOT was specified
725 if (!m_rootId
.IsOk())
727 m_rootId
= m_treeCtrl
->GetRootItem();
732 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent
&event
)
734 CollapseDir(event
.GetItem());
737 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId
)
741 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
742 if (!data
->m_isExpanded
)
745 data
->m_isExpanded
= FALSE
;
746 wxTreeItemIdValue cookie
;
747 /* Workaround because DeleteChildren has disapeared (why?) and
748 * CollapseAndReset doesn't work as advertised (deletes parent too) */
749 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
752 m_treeCtrl
->Delete(child
);
753 /* Not GetNextChild below, because the cookie mechanism can't
754 * handle disappearing children! */
755 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
759 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId
)
761 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
763 if (data
->m_isExpanded
)
766 data
->m_isExpanded
= TRUE
;
768 if (parentId
== m_treeCtrl
->GetRootItem())
776 wxString search
,path
,filename
;
778 wxString
dirName(data
->m_path
);
780 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
781 // Check if this is a root directory and if so,
782 // whether the drive is avaiable.
783 if (!wxIsDriveAvailable(dirName
))
785 data
->m_isExpanded
= FALSE
;
786 //wxMessageBox(wxT("Sorry, this drive is not available."));
791 // This may take a longish time. Go to busy cursor
794 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
795 if (dirName
.Last() == ':')
796 dirName
+= wxString(wxFILE_SEP_PATH
);
800 wxArrayString filenames
;
803 wxString eachFilename
;
810 int style
= wxDIR_DIRS
;
811 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
812 if (d
.GetFirst(& eachFilename
, wxEmptyString
, style
))
816 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
818 dirs
.Add(eachFilename
);
821 while (d
.GetNext(& eachFilename
));
824 dirs
.Sort(wxDirCtrlStringCompareFunction
);
826 // Now do the filenames -- but only if we're allowed to
827 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
835 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, wxDIR_FILES
))
839 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
841 filenames
.Add(eachFilename
);
844 while (d
.GetNext(& eachFilename
));
847 filenames
.Sort(wxDirCtrlStringCompareFunction
);
850 // Add the sorted dirs
852 for (i
= 0; i
< dirs
.Count(); i
++)
854 wxString
eachFilename(dirs
[i
]);
856 if (!wxEndsWithPathSeparator(path
))
857 path
+= wxString(wxFILE_SEP_PATH
);
858 path
+= eachFilename
;
860 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,TRUE
);
861 wxTreeItemId id
= AppendItem( parentId
, eachFilename
,
862 wxFileIconsTable::folder
, -1, dir_item
);
863 m_treeCtrl
->SetItemImage( id
, wxFileIconsTable::folder_open
,
864 wxTreeItemIcon_Expanded
);
866 // Has this got any children? If so, make it expandable.
867 // (There are two situations when a dir has children: either it
868 // has subdirectories or it contains files that weren't filtered
869 // out. The latter only applies to dirctrl with files.)
870 if ( dir_item
->HasSubDirs() ||
871 (((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0) &&
872 dir_item
->HasFiles(m_currentFilterStr
)) )
874 m_treeCtrl
->SetItemHasChildren(id
);
878 // Add the sorted filenames
879 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
881 for (i
= 0; i
< filenames
.Count(); i
++)
883 wxString
eachFilename(filenames
[i
]);
885 if (!wxEndsWithPathSeparator(path
))
886 path
+= wxString(wxFILE_SEP_PATH
);
887 path
+= eachFilename
;
888 //path = dirName + wxString(wxT("/")) + eachFilename;
889 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,FALSE
);
890 int image_id
= wxFileIconsTable::file
;
891 if (eachFilename
.Find(wxT('.')) != wxNOT_FOUND
)
892 image_id
= wxTheFileIconsTable
->GetIconID(eachFilename
.AfterLast(wxT('.')));
893 (void) AppendItem( parentId
, eachFilename
, image_id
, -1, dir_item
);
898 void wxGenericDirCtrl::ReCreateTree()
900 CollapseDir(m_treeCtrl
->GetRootItem());
901 ExpandDir(m_treeCtrl
->GetRootItem());
904 // Find the child that matches the first part of 'path'.
905 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
906 // then the child for /usr is returned.
907 wxTreeItemId
wxGenericDirCtrl::FindChild(wxTreeItemId parentId
, const wxString
& path
, bool& done
)
909 wxString
path2(path
);
911 // Make sure all separators are as per the current platform
912 path2
.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH
));
913 path2
.Replace(wxT("/"), wxString(wxFILE_SEP_PATH
));
915 // Append a separator to foil bogus substring matching
916 path2
+= wxString(wxFILE_SEP_PATH
);
918 // In MSW or PM, case is not significant
919 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
923 wxTreeItemIdValue cookie
;
924 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
925 while (childId
.IsOk())
927 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
929 if (data
&& !data
->m_path
.IsEmpty())
931 wxString
childPath(data
->m_path
);
932 if (!wxEndsWithPathSeparator(childPath
))
933 childPath
+= wxString(wxFILE_SEP_PATH
);
935 // In MSW and PM, case is not significant
936 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
937 childPath
.MakeLower();
940 if (childPath
.Len() <= path2
.Len())
942 wxString path3
= path2
.Mid(0, childPath
.Len());
943 if (childPath
== path3
)
945 if (path3
.Len() == path2
.Len())
954 childId
= m_treeCtrl
->GetNextChild(parentId
, cookie
);
956 wxTreeItemId invalid
;
960 // Try to expand as much of the given path as possible,
961 // and select the given tree item.
962 bool wxGenericDirCtrl::ExpandPath(const wxString
& path
)
965 wxTreeItemId id
= FindChild(m_rootId
, path
, done
);
966 wxTreeItemId lastId
= id
; // The last non-zero id
967 while (id
.IsOk() && !done
)
971 id
= FindChild(id
, path
, done
);
977 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(lastId
);
980 m_treeCtrl
->Expand(lastId
);
982 if ((GetWindowStyle() & wxDIRCTRL_SELECT_FIRST
) && data
->m_isDir
)
984 // Find the first file in this directory
985 wxTreeItemIdValue cookie
;
986 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(lastId
, cookie
);
987 bool selectedChild
= FALSE
;
988 while (childId
.IsOk())
990 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
992 if (data
&& data
->m_path
!= wxT("") && !data
->m_isDir
)
994 m_treeCtrl
->SelectItem(childId
);
995 m_treeCtrl
->EnsureVisible(childId
);
996 selectedChild
= TRUE
;
999 childId
= m_treeCtrl
->GetNextChild(lastId
, cookie
);
1003 m_treeCtrl
->SelectItem(lastId
);
1004 m_treeCtrl
->EnsureVisible(lastId
);
1009 m_treeCtrl
->SelectItem(lastId
);
1010 m_treeCtrl
->EnsureVisible(lastId
);
1019 wxString
wxGenericDirCtrl::GetPath() const
1021 wxTreeItemId id
= m_treeCtrl
->GetSelection();
1024 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1025 return data
->m_path
;
1028 return wxEmptyString
;
1031 wxString
wxGenericDirCtrl::GetFilePath() const
1033 wxTreeItemId id
= m_treeCtrl
->GetSelection();
1036 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1038 return wxEmptyString
;
1040 return data
->m_path
;
1043 return wxEmptyString
;
1046 void wxGenericDirCtrl::SetPath(const wxString
& path
)
1048 m_defaultPath
= path
;
1055 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId id
, int dirFlags
, wxArrayString
& filenames
)
1057 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1059 // This may take a longish time. Go to busy cursor
1064 wxString search
,path
,filename
;
1066 wxString
dirName(data
->m_path
);
1068 #if defined(__WXMSW__) || defined(__OS2__)
1069 if (dirName
.Last() == ':')
1070 dirName
+= wxString(wxFILE_SEP_PATH
);
1074 wxString eachFilename
;
1081 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, dirFlags
))
1085 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
1087 filenames
.Add(eachFilename
);
1090 while (d
.GetNext(& eachFilename
)) ;
1096 void wxGenericDirCtrl::SetFilterIndex(int n
)
1098 m_currentFilter
= n
;
1101 if (ExtractWildcard(m_filter
, n
, f
, d
))
1102 m_currentFilterStr
= f
;
1104 m_currentFilterStr
= wxT("*.*");
1107 void wxGenericDirCtrl::SetFilter(const wxString
& filter
)
1112 if (ExtractWildcard(m_filter
, m_currentFilter
, f
, d
))
1113 m_currentFilterStr
= f
;
1115 m_currentFilterStr
= wxT("*.*");
1118 // Extract description and actual filter from overall filter string
1119 bool wxGenericDirCtrl::ExtractWildcard(const wxString
& filterStr
, int n
, wxString
& filter
, wxString
& description
)
1121 wxArrayString filters
, descriptions
;
1122 int count
= ParseFilter(filterStr
, filters
, descriptions
);
1123 if (count
> 0 && n
< count
)
1125 filter
= filters
[n
];
1126 description
= descriptions
[n
];
1133 // Parses the global filter, returning the number of filters.
1134 // Returns 0 if none or if there's a problem.
1135 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpg"
1137 int wxGenericDirCtrl::ParseFilter(const wxString
& filterStr
, wxArrayString
& filters
, wxArrayString
& descriptions
)
1139 return wxFileDialogBase::ParseWildcard(filterStr
, descriptions
, filters
);
1142 void wxGenericDirCtrl::DoResize()
1144 wxSize sz
= GetClientSize();
1145 int verticalSpacing
= 3;
1149 if (m_filterListCtrl
)
1152 // For some reason, this is required in order for the
1153 // correct control height to always be returned, rather
1154 // than the drop-down list height which is sometimes returned.
1155 wxSize oldSize
= m_filterListCtrl
->GetSize();
1156 m_filterListCtrl
->SetSize(-1, -1, oldSize
.x
+10, -1, wxSIZE_USE_EXISTING
);
1157 m_filterListCtrl
->SetSize(-1, -1, oldSize
.x
, -1, wxSIZE_USE_EXISTING
);
1159 filterSz
= m_filterListCtrl
->GetSize();
1160 sz
.y
-= (filterSz
.y
+ verticalSpacing
);
1162 m_treeCtrl
->SetSize(0, 0, sz
.x
, sz
.y
);
1163 if (m_filterListCtrl
)
1165 m_filterListCtrl
->SetSize(0, sz
.y
+ verticalSpacing
, sz
.x
, filterSz
.y
);
1166 // Don't know why, but this needs refreshing after a resize (wxMSW)
1167 m_filterListCtrl
->Refresh();
1173 void wxGenericDirCtrl::OnSize(wxSizeEvent
& WXUNUSED(event
))
1178 wxTreeItemId
wxGenericDirCtrl::AppendItem (const wxTreeItemId
& parent
,
1179 const wxString
& text
,
1180 int image
, int selectedImage
,
1181 wxTreeItemData
* data
)
1183 wxTreeCtrl
*treeCtrl
= GetTreeCtrl ();
1185 wxASSERT (treeCtrl
);
1189 return treeCtrl
->AppendItem (parent
, text
, image
, selectedImage
, data
);
1193 return wxTreeItemId();
1198 //-----------------------------------------------------------------------------
1199 // wxDirFilterListCtrl
1200 //-----------------------------------------------------------------------------
1202 IMPLEMENT_CLASS(wxDirFilterListCtrl
, wxChoice
)
1204 BEGIN_EVENT_TABLE(wxDirFilterListCtrl
, wxChoice
)
1205 EVT_CHOICE(-1, wxDirFilterListCtrl::OnSelFilter
)
1208 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl
* parent
, const wxWindowID id
,
1214 return wxChoice::Create(parent
, id
, pos
, size
, 0, NULL
, style
);
1217 void wxDirFilterListCtrl::Init()
1222 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent
& WXUNUSED(event
))
1224 int sel
= GetSelection();
1226 wxString currentPath
= m_dirCtrl
->GetPath();
1228 m_dirCtrl
->SetFilterIndex(sel
);
1230 // If the filter has changed, the view is out of date, so
1231 // collapse the tree.
1232 m_dirCtrl
->ReCreateTree();
1234 // Try to restore the selection, or at least the directory
1235 m_dirCtrl
->ExpandPath(currentPath
);
1238 void wxDirFilterListCtrl::FillFilterList(const wxString
& filter
, int defaultFilter
)
1241 wxArrayString descriptions
, filters
;
1242 size_t n
= (size_t) m_dirCtrl
->ParseFilter(filter
, filters
, descriptions
);
1244 if (n
> 0 && defaultFilter
< (int) n
)
1246 for (size_t i
= 0; i
< n
; i
++)
1247 Append(descriptions
[i
]);
1248 SetSelection(defaultFilter
);
1253 // ----------------------------------------------------------------------------
1254 // wxFileIconsTable icons
1255 // ----------------------------------------------------------------------------
1258 static const char * file_icons_tbl_folder_open_xpm
[] = {
1259 /* width height ncolors chars_per_pixel */
1287 static const char * file_icons_tbl_computer_xpm
[] = {
1314 static const char * file_icons_tbl_drive_xpm
[] = {
1341 static const char *file_icons_tbl_cdrom_xpm
[] = {
1371 static const char * file_icons_tbl_floppy_xpm
[] = {
1398 static const char * file_icons_tbl_removeable_xpm
[] = {
1424 // ----------------------------------------------------------------------------
1425 // wxFileIconsTable & friends
1426 // ----------------------------------------------------------------------------
1428 // global instance of a wxFileIconsTable
1429 wxFileIconsTable
* wxTheFileIconsTable
= (wxFileIconsTable
*)NULL
;
1431 // A module to allow icons table cleanup
1433 class wxFileIconsTableModule
: public wxModule
1435 DECLARE_DYNAMIC_CLASS(wxFileIconsTableModule
)
1437 wxFileIconsTableModule() {}
1438 bool OnInit() { wxTheFileIconsTable
= new wxFileIconsTable
; return TRUE
; }
1441 if (wxTheFileIconsTable
)
1443 delete wxTheFileIconsTable
;
1444 wxTheFileIconsTable
= NULL
;
1449 IMPLEMENT_DYNAMIC_CLASS(wxFileIconsTableModule
, wxModule
)
1451 class wxFileIconEntry
: public wxObject
1454 wxFileIconEntry(int i
) { id
= i
; }
1459 wxFileIconsTable::wxFileIconsTable()
1462 m_smallImageList
= NULL
;
1465 wxFileIconsTable::~wxFileIconsTable()
1469 WX_CLEAR_HASH_TABLE(*m_HashTable
);
1472 if (m_smallImageList
) delete m_smallImageList
;
1475 // delayed initialization - wait until first use (wxArtProv not created yet)
1476 void wxFileIconsTable::Create()
1478 wxCHECK_RET(!m_smallImageList
&& !m_HashTable
, wxT("creating icons twice"));
1479 m_HashTable
= new wxHashTable(wxKEY_STRING
);
1480 m_smallImageList
= new wxImageList(16, 16);
1483 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER
, wxART_CMN_DIALOG
));
1485 m_smallImageList
->Add(wxIcon(file_icons_tbl_folder_open_xpm
));
1487 m_smallImageList
->Add(wxIcon(file_icons_tbl_computer_xpm
));
1489 m_smallImageList
->Add(wxIcon(file_icons_tbl_drive_xpm
));
1491 m_smallImageList
->Add(wxIcon(file_icons_tbl_cdrom_xpm
));
1493 m_smallImageList
->Add(wxIcon(file_icons_tbl_floppy_xpm
));
1495 m_smallImageList
->Add(wxIcon(file_icons_tbl_removeable_xpm
));
1497 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE
, wxART_CMN_DIALOG
));
1499 if (GetIconID(wxEmptyString
, _T("application/x-executable")) == file
)
1501 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE
, wxART_CMN_DIALOG
));
1502 delete m_HashTable
->Get(_T("exe"));
1503 m_HashTable
->Delete(_T("exe"));
1504 m_HashTable
->Put(_T("exe"), new wxFileIconEntry(executable
));
1506 /* else put into list by GetIconID
1507 (KDE defines application/x-executable for *.exe and has nice icon)
1511 wxImageList
*wxFileIconsTable::GetSmallImageList()
1513 if (!m_smallImageList
)
1516 return m_smallImageList
;
1520 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
1521 // one icon and we won't resize it
1523 static wxBitmap
CreateAntialiasedBitmap(const wxImage
& img
)
1525 wxImage
smallimg (16, 16);
1526 unsigned char *p1
, *p2
, *ps
;
1527 unsigned char mr
= img
.GetMaskRed(),
1528 mg
= img
.GetMaskGreen(),
1529 mb
= img
.GetMaskBlue();
1532 unsigned sr
, sg
, sb
, smask
;
1534 p1
= img
.GetData(), p2
= img
.GetData() + 3 * 32, ps
= smallimg
.GetData();
1535 smallimg
.SetMaskColour(mr
, mr
, mr
);
1537 for (y
= 0; y
< 16; y
++)
1539 for (x
= 0; x
< 16; x
++)
1541 sr
= sg
= sb
= smask
= 0;
1542 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1543 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1546 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1547 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1550 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1551 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1554 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1555 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1560 ps
[0] = ps
[1] = ps
[2] = mr
;
1562 ps
[0] = sr
>> 2, ps
[1] = sg
>> 2, ps
[2] = sb
>> 2;
1565 p1
+= 32 * 3, p2
+= 32 * 3;
1568 return wxBitmap(smallimg
);
1571 // finds empty borders and return non-empty area of image:
1572 static wxImage
CutEmptyBorders(const wxImage
& img
)
1574 unsigned char mr
= img
.GetMaskRed(),
1575 mg
= img
.GetMaskGreen(),
1576 mb
= img
.GetMaskBlue();
1577 unsigned char *dt
= img
.GetData(), *dttmp
;
1578 unsigned w
= img
.GetWidth(), h
= img
.GetHeight();
1580 unsigned top
, bottom
, left
, right
, i
;
1583 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
1584 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = FALSE; break;}
1586 for (empt
= TRUE
, top
= 0; empt
&& top
< h
; top
++)
1589 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1592 for (empt
= TRUE
, bottom
= h
-1; empt
&& bottom
> top
; bottom
--)
1594 MK_DTTMP(0, bottom
);
1595 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1598 for (empt
= TRUE
, left
= 0; empt
&& left
< w
; left
++)
1601 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1604 for (empt
= TRUE
, right
= w
-1; empt
&& right
> left
; right
--)
1607 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1610 top
--, left
--, bottom
++, right
++;
1612 return img
.GetSubImage(wxRect(left
, top
, right
- left
+ 1, bottom
- top
+ 1));
1614 #endif // wxUSE_MIMETYPE
1616 int wxFileIconsTable::GetIconID(const wxString
& extension
, const wxString
& mime
)
1618 if (!m_smallImageList
)
1622 if (!extension
.IsEmpty())
1624 wxFileIconEntry
*entry
= (wxFileIconEntry
*) m_HashTable
->Get(extension
);
1625 if (entry
) return (entry
-> id
);
1628 wxFileType
*ft
= (mime
.IsEmpty()) ?
1629 wxTheMimeTypesManager
-> GetFileTypeFromExtension(extension
) :
1630 wxTheMimeTypesManager
-> GetFileTypeFromMimeType(mime
);
1632 wxIconLocation iconLoc
;
1634 if ( ft
&& ft
->GetIcon(&iconLoc
) )
1636 ic
= wxIcon(iconLoc
);
1644 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1649 bmp
.CopyFromIcon(ic
);
1651 int id
= m_smallImageList
->GetImageCount();
1652 if ((bmp
.GetWidth() == 16) && (bmp
.GetHeight() == 16))
1653 m_smallImageList
->Add(bmp
);
1656 wxImage img
= bmp
.ConvertToImage();
1658 if ((img
.GetWidth() != 32) || (img
.GetHeight() != 32))
1659 m_smallImageList
->Add(CreateAntialiasedBitmap(CutEmptyBorders(img
).Rescale(32, 32)));
1661 m_smallImageList
->Add(CreateAntialiasedBitmap(img
));
1663 m_HashTable
->Put(extension
, new wxFileIconEntry(id
));
1666 #else // !wxUSE_MIMETYPE
1668 if (extension
== wxT("exe"))
1672 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
1675 #endif // wxUSE_DIRDLG