1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/generic/dirctrlg.cpp
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 // For compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
19 #if wxUSE_DIRDLG || wxUSE_FILEDLG
21 #include "wx/generic/dirctrlg.h"
28 #include "wx/button.h"
30 #include "wx/settings.h"
31 #include "wx/msgdlg.h"
32 #include "wx/cmndata.h"
33 #include "wx/choice.h"
34 #include "wx/textctrl.h"
35 #include "wx/layout.h"
37 #include "wx/textdlg.h"
38 #include "wx/gdicmn.h"
40 #include "wx/module.h"
43 #include "wx/filefn.h"
44 #include "wx/imaglist.h"
45 #include "wx/tokenzr.h"
47 #include "wx/artprov.h"
48 #include "wx/mimetype.h"
51 #include "wx/statline.h"
54 #if defined(__WXMAC__)
55 #include "wx/mac/private.h" // includes mac headers
60 #include "wx/msw/winundef.h"
61 #include "wx/volume.h"
63 // FIXME - Mingw32 1.0 has both _getdrive() and _chdrive(). For now, let's assume
64 // older releases don't, but it should be verified and the checks modified
66 #if !defined(__GNUWIN32__) || (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
67 #if !defined(__WXWINCE__)
76 #if defined(__OS2__) || defined(__DOS__)
88 #if defined(__WXMAC__)
89 #include "MoreFilesX.h"
96 extern WXDLLEXPORT_DATA(const wxChar
) wxFileSelectorDefaultWildcardStr
[];
98 // If compiled under Windows, this macro can cause problems
103 bool wxIsDriveAvailable(const wxString
& dirName
);
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("\\"));
117 icon_ids
.Add(wxFileIconsTable::computer
);
118 #elif defined(__WIN32__) && wxUSE_FSVOLUME
119 // TODO: this code (using wxFSVolumeBase) should be used for all platforms
120 // but unfortunately wxFSVolumeBase is not implemented everywhere
121 const wxArrayString as
= wxFSVolumeBase::GetVolumes();
123 for (size_t i
= 0; i
< as
.GetCount(); i
++)
125 wxString path
= as
[i
];
126 wxFSVolume
vol(path
);
128 switch (vol
.GetKind())
130 case wxFS_VOL_FLOPPY
:
131 if ( (path
== wxT("a:\\")) || (path
== wxT("b:\\")) )
132 imageId
= wxFileIconsTable::floppy
;
134 imageId
= wxFileIconsTable::removeable
;
136 case wxFS_VOL_DVDROM
:
138 imageId
= wxFileIconsTable::cdrom
;
140 case wxFS_VOL_NETWORK
:
141 if (path
[0] == wxT('\\'))
142 continue; // skip "\\computer\folder"
143 imageId
= wxFileIconsTable::drive
;
148 imageId
= wxFileIconsTable::drive
;
152 names
.Add(vol
.GetDisplayName());
153 icon_ids
.Add(imageId
);
155 #elif defined(__OS2__)
157 ULONG ulDriveNum
= 0;
158 ULONG ulDriveMap
= 0;
159 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
165 if (ulDriveMap
& ( 1 << i
))
168 path
.Printf(wxT("%c:\\"), 'A' + i
);
169 name
.Printf(wxT("%c:"), 'A' + i
);
171 // Note: If _filesys is unsupported by some compilers,
172 // we can always replace it by DosQueryFSAttach
173 char filesysname
[20];
175 ULONG cbBuffer
= sizeof(filesysname
);
176 PFSQBUFFER2 pfsqBuffer
= (PFSQBUFFER2
)filesysname
;
177 APIRET rc
= ::DosQueryFSAttach(name
.fn_str(),0,FSAIL_QUERYNAME
,pfsqBuffer
,&cbBuffer
);
180 filesysname
[0] = '\0';
183 _filesys(name
.fn_str(), filesysname
, sizeof(filesysname
));
185 /* FAT, LAN, HPFS, CDFS, NFS */
187 if (path
== wxT("A:\\") || path
== wxT("B:\\"))
188 imageId
= wxFileIconsTable::floppy
;
189 else if (!strcmp(filesysname
, "CDFS"))
190 imageId
= wxFileIconsTable::cdrom
;
191 else if (!strcmp(filesysname
, "LAN") ||
192 !strcmp(filesysname
, "NFS"))
193 imageId
= wxFileIconsTable::drive
;
195 imageId
= wxFileIconsTable::drive
;
198 icon_ids
.Add(imageId
);
203 #else // !__WIN32__, !__OS2__
206 /* If we can switch to the drive, it exists. */
207 for( drive
= 1; drive
<= 26; drive
++ )
210 path
.Printf(wxT("%c:\\"), (char) (drive
+ 'a' - 1));
211 name
.Printf(wxT("%c:"), (char) (drive
+ 'A' - 1));
213 if (wxIsDriveAvailable(path
))
217 icon_ids
.Add((drive
<= 2) ? wxFileIconsTable::floppy
: wxFileIconsTable::drive
);
220 #endif // __WIN32__/!__WIN32__
222 #elif defined(__WXMAC__)
224 ItemCount volumeIndex
= 1;
227 while( noErr
== err
)
229 HFSUniStr255 volumeName
;
231 FSVolumeInfo volumeInfo
;
232 err
= FSGetVolumeInfo(0, volumeIndex
, NULL
, kFSVolInfoFlags
, &volumeInfo
, &volumeName
, &fsRef
);
235 wxString path
= wxMacFSRefToPath( &fsRef
) ;
236 wxString name
= wxMacHFSUniStrToString( &volumeName
) ;
238 if ( (volumeInfo
.flags
& kFSVolFlagSoftwareLockedMask
) || (volumeInfo
.flags
& kFSVolFlagHardwareLockedMask
) )
240 icon_ids
.Add(wxFileIconsTable::cdrom
);
244 icon_ids
.Add(wxFileIconsTable::drive
);
246 // todo other removable
254 #elif defined(__UNIX__)
257 icon_ids
.Add(wxFileIconsTable::computer
);
259 #error "Unsupported platform in wxGenericDirCtrl!"
261 wxASSERT_MSG( (paths
.GetCount() == names
.GetCount()), wxT("The number of paths and their human readable names should be equal in number."));
262 wxASSERT_MSG( (paths
.GetCount() == icon_ids
.GetCount()), wxT("Wrong number of icons for available drives."));
263 return paths
.GetCount();
266 // ----------------------------------------------------------------------------
267 // wxIsDriveAvailable
268 // ----------------------------------------------------------------------------
272 bool wxIsDriveAvailable(const wxString
& dirName
)
274 // FIXME_MGL - this method leads to hang up under Watcom for some reason
276 wxUnusedVar(dirName
);
278 if ( dirName
.length() == 3 && dirName
[1u] == wxT(':') )
280 wxString
dirNameLower(dirName
.Lower());
281 // VS: always return true for removable media, since Win95 doesn't
282 // like it when MS-DOS app accesses empty floppy drive
283 return (dirNameLower
[0u] == wxT('a') ||
284 dirNameLower
[0u] == wxT('b') ||
285 wxDirExists(dirNameLower
));
292 #elif defined(__WINDOWS__) || defined(__OS2__)
294 int setdrive(int WXUNUSED_IN_WINCE(drive
))
298 #elif defined(__GNUWIN32__) && \
299 (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
300 return _chdrive(drive
);
304 if (drive
< 1 || drive
> 31)
306 newdrive
[0] = (wxChar
)(wxT('A') + drive
- 1);
307 newdrive
[1] = wxT(':');
309 newdrive
[2] = wxT('\\');
310 newdrive
[3] = wxT('\0');
312 newdrive
[2] = wxT('\0');
314 #if defined(__WXMSW__)
315 if (::SetCurrentDirectory(newdrive
))
317 // VA doesn't know what LPSTR is and has its own set
318 if (!DosSetCurrentDir((PSZ
)newdrive
))
326 bool wxIsDriveAvailable(const wxString
& WXUNUSED_IN_WINCE(dirName
))
332 UINT errorMode
= SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOOPENFILEERRORBOX
);
336 // Check if this is a root directory and if so,
337 // whether the drive is available.
338 if (dirName
.length() == 3 && dirName
[(size_t)1] == wxT(':'))
340 wxString
dirNameLower(dirName
.Lower());
341 #if defined(__GNUWIN32__) && !(defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
342 success
= wxDirExists(dirNameLower
);
345 // Avoid changing to drive since no media may be inserted.
346 if (dirNameLower
[(size_t)0] == 'a' || dirNameLower
[(size_t)0] == 'b')
349 int currentDrive
= _getdrive();
350 int thisDrive
= (int) (dirNameLower
[(size_t)0] - 'a' + 1) ;
351 int err
= setdrive( thisDrive
) ;
352 setdrive( currentDrive
);
361 (void) SetErrorMode(errorMode
);
367 #endif // __WINDOWS__ || __OS2__
369 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG
375 // Function which is called by quick sort. We want to override the default wxArrayString behaviour,
376 // and sort regardless of case.
377 static int wxCMPFUNC_CONV
wxDirCtrlStringCompareFunction(const wxString
& strFirst
, const wxString
& strSecond
)
379 return strFirst
.CmpNoCase(strSecond
);
382 //-----------------------------------------------------------------------------
384 //-----------------------------------------------------------------------------
386 wxDirItemData::wxDirItemData(const wxString
& path
, const wxString
& name
,
391 /* Insert logic to detect hidden files here
392 * In UnixLand we just check whether the first char is a dot
393 * For FileNameFromPath read LastDirNameInThisPath ;-) */
394 // m_isHidden = (bool)(wxFileNameFromPath(*m_path)[0] == '.');
396 m_isExpanded
= false;
400 void wxDirItemData::SetNewDirName(const wxString
& path
)
403 m_name
= wxFileNameFromPath(path
);
406 bool wxDirItemData::HasSubDirs() const
414 if ( !dir
.Open(m_path
) )
418 return dir
.HasSubDirs();
421 bool wxDirItemData::HasFiles(const wxString
& WXUNUSED(spec
)) const
429 if ( !dir
.Open(m_path
) )
433 return dir
.HasFiles();
436 //-----------------------------------------------------------------------------
438 //-----------------------------------------------------------------------------
441 #if wxUSE_EXTENDED_RTTI
442 WX_DEFINE_FLAGS( wxGenericDirCtrlStyle
)
444 wxBEGIN_FLAGS( wxGenericDirCtrlStyle
)
445 // new style border flags, we put them first to
446 // use them for streaming out
447 wxFLAGS_MEMBER(wxBORDER_SIMPLE
)
448 wxFLAGS_MEMBER(wxBORDER_SUNKEN
)
449 wxFLAGS_MEMBER(wxBORDER_DOUBLE
)
450 wxFLAGS_MEMBER(wxBORDER_RAISED
)
451 wxFLAGS_MEMBER(wxBORDER_STATIC
)
452 wxFLAGS_MEMBER(wxBORDER_NONE
)
454 // old style border flags
455 wxFLAGS_MEMBER(wxSIMPLE_BORDER
)
456 wxFLAGS_MEMBER(wxSUNKEN_BORDER
)
457 wxFLAGS_MEMBER(wxDOUBLE_BORDER
)
458 wxFLAGS_MEMBER(wxRAISED_BORDER
)
459 wxFLAGS_MEMBER(wxSTATIC_BORDER
)
460 wxFLAGS_MEMBER(wxBORDER
)
462 // standard window styles
463 wxFLAGS_MEMBER(wxTAB_TRAVERSAL
)
464 wxFLAGS_MEMBER(wxCLIP_CHILDREN
)
465 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW
)
466 wxFLAGS_MEMBER(wxWANTS_CHARS
)
467 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE
)
468 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB
)
469 wxFLAGS_MEMBER(wxVSCROLL
)
470 wxFLAGS_MEMBER(wxHSCROLL
)
472 wxFLAGS_MEMBER(wxDIRCTRL_DIR_ONLY
)
473 wxFLAGS_MEMBER(wxDIRCTRL_3D_INTERNAL
)
474 wxFLAGS_MEMBER(wxDIRCTRL_SELECT_FIRST
)
476 wxEND_FLAGS( wxGenericDirCtrlStyle
)
478 IMPLEMENT_DYNAMIC_CLASS_XTI(wxGenericDirCtrl
, wxControl
,"wx/dirctrl.h")
480 wxBEGIN_PROPERTIES_TABLE(wxGenericDirCtrl
)
481 wxHIDE_PROPERTY( Children
)
482 wxPROPERTY( DefaultPath
, wxString
, SetDefaultPath
, GetDefaultPath
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
483 wxPROPERTY( Filter
, wxString
, SetFilter
, GetFilter
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
484 wxPROPERTY( DefaultFilter
, int , SetFilterIndex
, GetFilterIndex
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
485 wxPROPERTY_FLAGS( WindowStyle
, wxGenericDirCtrlStyle
, long, SetWindowStyleFlag
, GetWindowStyleFlag
, EMPTY_MACROVALUE
, 0, wxT("Helpstring"), wxT("group") )
486 wxEND_PROPERTIES_TABLE()
488 wxBEGIN_HANDLERS_TABLE(wxGenericDirCtrl
)
489 wxEND_HANDLERS_TABLE()
491 wxCONSTRUCTOR_8( wxGenericDirCtrl
, wxWindow
* , Parent
, wxWindowID
, Id
, wxString
, DefaultPath
,
492 wxPoint
, Position
, wxSize
, Size
, long , WindowStyle
, wxString
, Filter
, int , DefaultFilter
)
494 IMPLEMENT_DYNAMIC_CLASS(wxGenericDirCtrl
, wxControl
)
497 BEGIN_EVENT_TABLE(wxGenericDirCtrl
, wxControl
)
498 EVT_TREE_ITEM_EXPANDING (wxID_TREECTRL
, wxGenericDirCtrl::OnExpandItem
)
499 EVT_TREE_ITEM_COLLAPSED (wxID_TREECTRL
, wxGenericDirCtrl::OnCollapseItem
)
500 EVT_TREE_BEGIN_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnBeginEditItem
)
501 EVT_TREE_END_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnEndEditItem
)
502 EVT_SIZE (wxGenericDirCtrl::OnSize
)
505 wxGenericDirCtrl::wxGenericDirCtrl(void)
510 void wxGenericDirCtrl::ExpandRoot()
512 ExpandDir(m_rootId
); // automatically expand first level
514 // Expand and select the default path
515 if (!m_defaultPath
.empty())
517 ExpandPath(m_defaultPath
);
522 // On Unix, there's only one node under the (hidden) root node. It
523 // represents the / path, so the user would always have to expand it;
524 // let's do it ourselves
525 ExpandPath( wxT("/") );
530 bool wxGenericDirCtrl::Create(wxWindow
*parent
,
536 const wxString
& filter
,
538 const wxString
& name
)
540 if (!wxControl::Create(parent
, id
, pos
, size
, style
, wxDefaultValidator
, name
))
543 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE
));
544 SetForegroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT
));
548 long treeStyle
= wxTR_HAS_BUTTONS
;
550 // On Windows CE, if you hide the root, you get a crash when
551 // attempting to access data for children of the root item.
553 treeStyle
|= wxTR_HIDE_ROOT
;
557 treeStyle
|= wxTR_NO_LINES
;
560 if (style
& wxDIRCTRL_EDIT_LABELS
)
561 treeStyle
|= wxTR_EDIT_LABELS
;
563 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
564 treeStyle
|= wxNO_BORDER
;
566 treeStyle
|= wxBORDER_SUNKEN
;
568 m_treeCtrl
= CreateTreeCtrl(this, wxID_TREECTRL
,
569 wxPoint(0,0), GetClientSize(), treeStyle
);
572 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
);
577 if (m_filter
.empty())
578 m_filter
= wxFileSelectorDefaultWildcardStr
;
580 SetFilterIndex(defaultFilter
);
582 if (m_filterListCtrl
)
583 m_filterListCtrl
->FillFilterList(filter
, defaultFilter
);
585 m_treeCtrl
->SetImageList(wxTheFileIconsTable
->GetSmallImageList());
587 m_showHidden
= false;
588 wxDirItemData
* rootData
= new wxDirItemData(wxEmptyString
, wxEmptyString
, true);
592 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
593 rootName
= _("Computer");
595 rootName
= _("Sections");
598 m_rootId
= m_treeCtrl
->AddRoot( rootName
, 3, -1, rootData
);
599 m_treeCtrl
->SetItemHasChildren(m_rootId
);
603 SetInitialSize(size
);
609 wxGenericDirCtrl::~wxGenericDirCtrl()
613 void wxGenericDirCtrl::Init()
615 m_showHidden
= false;
617 m_currentFilterStr
= wxEmptyString
; // Default: any file
619 m_filterListCtrl
= NULL
;
622 wxTreeCtrl
* wxGenericDirCtrl::CreateTreeCtrl(wxWindow
*parent
, wxWindowID id
, const wxPoint
& pos
, const wxSize
& size
, long treeStyle
)
624 return new wxTreeCtrl(parent
, id
, pos
, size
, treeStyle
);
627 void wxGenericDirCtrl::ShowHidden( bool show
)
629 if ( m_showHidden
== show
)
634 wxString path
= GetPath();
640 wxGenericDirCtrl::AddSection(const wxString
& path
, const wxString
& name
, int imageId
)
642 wxDirItemData
*dir_item
= new wxDirItemData(path
,name
,true);
644 wxTreeItemId id
= AppendItem( m_rootId
, name
, imageId
, -1, dir_item
);
646 m_treeCtrl
->SetItemHasChildren(id
);
651 void wxGenericDirCtrl::SetupSections()
653 wxArrayString paths
, names
;
656 size_t n
, count
= wxGetAvailableDrives(paths
, names
, icons
);
659 wxString home
= wxGetHomeDir();
660 AddSection( home
, _("Home directory"), 1);
661 home
+= wxT("/Desktop");
662 AddSection( home
, _("Desktop"), 1);
665 for (n
= 0; n
< count
; n
++)
666 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
.IsEditCancelled())
691 if ((event
.GetLabel().empty()) ||
692 (event
.GetLabel() == wxT(".")) ||
693 (event
.GetLabel() == wxT("..")) ||
694 (event
.GetLabel().Find(wxT('/')) != wxNOT_FOUND
) ||
695 (event
.GetLabel().Find(wxT('\\')) != wxNOT_FOUND
) ||
696 (event
.GetLabel().Find(wxT('|')) != wxNOT_FOUND
))
698 wxMessageDialog
dialog(this, _("Illegal directory name."), _("Error"), wxOK
| wxICON_ERROR
);
704 wxTreeItemId id
= event
.GetItem();
705 wxDirItemData
*data
= (wxDirItemData
*)m_treeCtrl
->GetItemData( id
);
708 wxString
new_name( wxPathOnly( data
->m_path
) );
709 new_name
+= wxString(wxFILE_SEP_PATH
);
710 new_name
+= event
.GetLabel();
714 if (wxFileExists(new_name
))
716 wxMessageDialog
dialog(this, _("File name exists already."), _("Error"), wxOK
| wxICON_ERROR
);
721 if (wxRenameFile(data
->m_path
,new_name
))
723 data
->SetNewDirName( new_name
);
727 wxMessageDialog
dialog(this, _("Operation not permitted."), _("Error"), wxOK
| wxICON_ERROR
);
733 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent
&event
)
735 wxTreeItemId parentId
= event
.GetItem();
737 // VS: this is needed because the event handler is called from wxTreeCtrl
738 // ctor when wxTR_HIDE_ROOT was specified
740 if (!m_rootId
.IsOk())
742 m_rootId
= m_treeCtrl
->GetRootItem();
747 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent
&event
)
749 CollapseDir(event
.GetItem());
752 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId
)
756 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
757 if (!data
->m_isExpanded
)
760 data
->m_isExpanded
= false;
761 wxTreeItemIdValue cookie
;
762 /* Workaround because DeleteChildren has disapeared (why?) and
763 * CollapseAndReset doesn't work as advertised (deletes parent too) */
764 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
767 m_treeCtrl
->Delete(child
);
768 /* Not GetNextChild below, because the cookie mechanism can't
769 * handle disappearing children! */
770 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
772 if (parentId
!= m_treeCtrl
->GetRootItem())
773 m_treeCtrl
->Collapse(parentId
);
776 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId
)
778 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
780 if (data
->m_isExpanded
)
783 data
->m_isExpanded
= true;
785 if (parentId
== m_treeCtrl
->GetRootItem())
793 wxString search
,path
,filename
;
795 wxString
dirName(data
->m_path
);
797 #if (defined(__WINDOWS__) && !defined(__WXWINCE__)) || defined(__DOS__) || defined(__OS2__)
798 // Check if this is a root directory and if so,
799 // whether the drive is avaiable.
800 if (!wxIsDriveAvailable(dirName
))
802 data
->m_isExpanded
= false;
803 //wxMessageBox(wxT("Sorry, this drive is not available."));
808 // This may take a longish time. Go to busy cursor
811 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
812 if (dirName
.Last() == ':')
813 dirName
+= wxString(wxFILE_SEP_PATH
);
817 wxArrayString filenames
;
820 wxString eachFilename
;
827 int style
= wxDIR_DIRS
;
828 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
829 if (d
.GetFirst(& eachFilename
, wxEmptyString
, style
))
833 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
835 dirs
.Add(eachFilename
);
838 while (d
.GetNext(&eachFilename
));
841 dirs
.Sort(wxDirCtrlStringCompareFunction
);
843 // Now do the filenames -- but only if we're allowed to
844 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
850 int style
= wxDIR_FILES
;
851 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
852 // Process each filter (ex: "JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg")
853 wxStringTokenizer strTok
;
855 strTok
.SetString(m_currentFilterStr
,wxT(";"));
856 while(strTok
.HasMoreTokens())
858 curFilter
= strTok
.GetNextToken();
859 if (d
.GetFirst(& eachFilename
, curFilter
, style
))
863 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
865 filenames
.Add(eachFilename
);
868 while (d
.GetNext(& eachFilename
));
872 filenames
.Sort(wxDirCtrlStringCompareFunction
);
875 // Add the sorted dirs
877 for (i
= 0; i
< dirs
.GetCount(); i
++)
879 eachFilename
= dirs
[i
];
881 if (!wxEndsWithPathSeparator(path
))
882 path
+= wxString(wxFILE_SEP_PATH
);
883 path
+= eachFilename
;
885 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,true);
886 wxTreeItemId id
= AppendItem( parentId
, eachFilename
,
887 wxFileIconsTable::folder
, -1, dir_item
);
888 m_treeCtrl
->SetItemImage( id
, wxFileIconsTable::folder_open
,
889 wxTreeItemIcon_Expanded
);
891 // Has this got any children? If so, make it expandable.
892 // (There are two situations when a dir has children: either it
893 // has subdirectories or it contains files that weren't filtered
894 // out. The latter only applies to dirctrl with files.)
895 if ( dir_item
->HasSubDirs() ||
896 (((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0) &&
897 dir_item
->HasFiles(m_currentFilterStr
)) )
899 m_treeCtrl
->SetItemHasChildren(id
);
903 // Add the sorted filenames
904 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
906 for (i
= 0; i
< filenames
.GetCount(); i
++)
908 eachFilename
= filenames
[i
];
910 if (!wxEndsWithPathSeparator(path
))
911 path
+= wxString(wxFILE_SEP_PATH
);
912 path
+= eachFilename
;
913 //path = dirName + wxString(wxT("/")) + eachFilename;
914 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,false);
915 int image_id
= wxFileIconsTable::file
;
916 if (eachFilename
.Find(wxT('.')) != wxNOT_FOUND
)
917 image_id
= wxTheFileIconsTable
->GetIconID(eachFilename
.AfterLast(wxT('.')));
918 (void) AppendItem( parentId
, eachFilename
, image_id
, -1, dir_item
);
923 void wxGenericDirCtrl::ReCreateTree()
925 CollapseDir(m_treeCtrl
->GetRootItem());
929 void wxGenericDirCtrl::CollapseTree()
931 wxTreeItemIdValue cookie
;
932 wxTreeItemId child
= m_treeCtrl
->GetFirstChild(m_rootId
, cookie
);
936 child
= m_treeCtrl
->GetNextChild(m_rootId
, cookie
);
940 // Find the child that matches the first part of 'path'.
941 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
942 // then the child for /usr is returned.
943 wxTreeItemId
wxGenericDirCtrl::FindChild(wxTreeItemId parentId
, const wxString
& path
, bool& done
)
945 wxString
path2(path
);
947 // Make sure all separators are as per the current platform
948 path2
.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH
));
949 path2
.Replace(wxT("/"), wxString(wxFILE_SEP_PATH
));
951 // Append a separator to foil bogus substring matching
952 path2
+= wxString(wxFILE_SEP_PATH
);
954 // In MSW or PM, case is not significant
955 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
959 wxTreeItemIdValue cookie
;
960 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
961 while (childId
.IsOk())
963 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
965 if (data
&& !data
->m_path
.empty())
967 wxString
childPath(data
->m_path
);
968 if (!wxEndsWithPathSeparator(childPath
))
969 childPath
+= wxString(wxFILE_SEP_PATH
);
971 // In MSW and PM, case is not significant
972 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
973 childPath
.MakeLower();
976 if (childPath
.length() <= path2
.length())
978 wxString path3
= path2
.Mid(0, childPath
.length());
979 if (childPath
== path3
)
981 if (path3
.length() == path2
.length())
990 childId
= m_treeCtrl
->GetNextChild(parentId
, cookie
);
992 wxTreeItemId invalid
;
996 // Try to expand as much of the given path as possible,
997 // and select the given tree item.
998 bool wxGenericDirCtrl::ExpandPath(const wxString
& path
)
1001 wxTreeItemId id
= FindChild(m_rootId
, path
, done
);
1002 wxTreeItemId lastId
= id
; // The last non-zero id
1003 while (id
.IsOk() && !done
)
1007 id
= FindChild(id
, path
, done
);
1014 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(lastId
);
1017 m_treeCtrl
->Expand(lastId
);
1019 if ((GetWindowStyle() & wxDIRCTRL_SELECT_FIRST
) && data
->m_isDir
)
1021 // Find the first file in this directory
1022 wxTreeItemIdValue cookie
;
1023 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(lastId
, cookie
);
1024 bool selectedChild
= false;
1025 while (childId
.IsOk())
1027 data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
1029 if (data
&& data
->m_path
!= wxEmptyString
&& !data
->m_isDir
)
1031 m_treeCtrl
->SelectItem(childId
);
1032 m_treeCtrl
->EnsureVisible(childId
);
1033 selectedChild
= true;
1036 childId
= m_treeCtrl
->GetNextChild(lastId
, cookie
);
1040 m_treeCtrl
->SelectItem(lastId
);
1041 m_treeCtrl
->EnsureVisible(lastId
);
1046 m_treeCtrl
->SelectItem(lastId
);
1047 m_treeCtrl
->EnsureVisible(lastId
);
1054 bool wxGenericDirCtrl::CollapsePath(const wxString
& path
)
1057 wxTreeItemId id
= FindChild(m_rootId
, path
, done
);
1058 wxTreeItemId lastId
= id
; // The last non-zero id
1060 while ( id
.IsOk() && !done
)
1064 id
= FindChild(id
, path
, done
);
1070 if ( !lastId
.IsOk() )
1073 m_treeCtrl
->SelectItem(lastId
);
1074 m_treeCtrl
->EnsureVisible(lastId
);
1080 wxString
wxGenericDirCtrl::GetPath() const
1082 wxTreeItemId id
= m_treeCtrl
->GetSelection();
1085 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1086 return data
->m_path
;
1089 return wxEmptyString
;
1092 wxString
wxGenericDirCtrl::GetFilePath() const
1094 wxTreeItemId id
= m_treeCtrl
->GetSelection();
1097 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1099 return wxEmptyString
;
1101 return data
->m_path
;
1104 return wxEmptyString
;
1107 void wxGenericDirCtrl::SetPath(const wxString
& path
)
1109 m_defaultPath
= path
;
1116 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId id
, int dirFlags
, wxArrayString
& filenames
)
1118 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1120 // This may take a longish time. Go to busy cursor
1125 wxString search
,path
,filename
;
1127 wxString
dirName(data
->m_path
);
1129 #if defined(__WXMSW__) || defined(__OS2__)
1130 if (dirName
.Last() == ':')
1131 dirName
+= wxString(wxFILE_SEP_PATH
);
1135 wxString eachFilename
;
1142 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, dirFlags
))
1146 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
1148 filenames
.Add(eachFilename
);
1151 while (d
.GetNext(& eachFilename
)) ;
1157 void wxGenericDirCtrl::SetFilterIndex(int n
)
1159 m_currentFilter
= n
;
1162 if (ExtractWildcard(m_filter
, n
, f
, d
))
1163 m_currentFilterStr
= f
;
1166 m_currentFilterStr
= wxT("*");
1168 m_currentFilterStr
= wxT("*.*");
1172 void wxGenericDirCtrl::SetFilter(const wxString
& filter
)
1176 if (!filter
.empty() && !m_filterListCtrl
)
1177 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
);
1178 else if (filter
.empty() && m_filterListCtrl
)
1180 m_filterListCtrl
->Destroy();
1181 m_filterListCtrl
= NULL
;
1185 if (ExtractWildcard(m_filter
, m_currentFilter
, f
, d
))
1186 m_currentFilterStr
= f
;
1189 m_currentFilterStr
= wxT("*");
1191 m_currentFilterStr
= wxT("*.*");
1193 // current filter index is meaningless after filter change, set it to zero
1195 if (m_filterListCtrl
)
1196 m_filterListCtrl
->FillFilterList(m_filter
, 0);
1199 // Extract description and actual filter from overall filter string
1200 bool wxGenericDirCtrl::ExtractWildcard(const wxString
& filterStr
, int n
, wxString
& filter
, wxString
& description
)
1202 wxArrayString filters
, descriptions
;
1203 int count
= wxParseCommonDialogsFilter(filterStr
, descriptions
, filters
);
1204 if (count
> 0 && n
< count
)
1206 filter
= filters
[n
];
1207 description
= descriptions
[n
];
1215 void wxGenericDirCtrl::DoResize()
1217 wxSize sz
= GetClientSize();
1218 int verticalSpacing
= 3;
1222 if (m_filterListCtrl
)
1224 filterSz
= m_filterListCtrl
->GetSize();
1225 sz
.y
-= (filterSz
.y
+ verticalSpacing
);
1227 m_treeCtrl
->SetSize(0, 0, sz
.x
, sz
.y
);
1228 if (m_filterListCtrl
)
1230 m_filterListCtrl
->SetSize(0, sz
.y
+ verticalSpacing
, sz
.x
, filterSz
.y
);
1231 // Don't know why, but this needs refreshing after a resize (wxMSW)
1232 m_filterListCtrl
->Refresh();
1238 void wxGenericDirCtrl::OnSize(wxSizeEvent
& WXUNUSED(event
))
1243 wxTreeItemId
wxGenericDirCtrl::AppendItem (const wxTreeItemId
& parent
,
1244 const wxString
& text
,
1245 int image
, int selectedImage
,
1246 wxTreeItemData
* data
)
1248 wxTreeCtrl
*treeCtrl
= GetTreeCtrl ();
1250 wxASSERT (treeCtrl
);
1254 return treeCtrl
->AppendItem (parent
, text
, image
, selectedImage
, data
);
1258 return wxTreeItemId();
1263 //-----------------------------------------------------------------------------
1264 // wxDirFilterListCtrl
1265 //-----------------------------------------------------------------------------
1267 IMPLEMENT_CLASS(wxDirFilterListCtrl
, wxChoice
)
1269 BEGIN_EVENT_TABLE(wxDirFilterListCtrl
, wxChoice
)
1270 EVT_CHOICE(wxID_ANY
, wxDirFilterListCtrl::OnSelFilter
)
1273 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl
* parent
,
1274 const wxWindowID id
,
1281 // by default our border style is determined by the style of our parent
1282 if ( !(style
& wxBORDER_MASK
) )
1284 style
|= parent
->HasFlag(wxDIRCTRL_3D_INTERNAL
) ? wxBORDER_SUNKEN
1288 return wxChoice::Create(parent
, id
, pos
, size
, 0, NULL
, style
);
1291 void wxDirFilterListCtrl::Init()
1296 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent
& WXUNUSED(event
))
1298 int sel
= GetSelection();
1300 wxString currentPath
= m_dirCtrl
->GetPath();
1302 m_dirCtrl
->SetFilterIndex(sel
);
1304 // If the filter has changed, the view is out of date, so
1305 // collapse the tree.
1306 m_dirCtrl
->ReCreateTree();
1308 // Try to restore the selection, or at least the directory
1309 m_dirCtrl
->ExpandPath(currentPath
);
1312 void wxDirFilterListCtrl::FillFilterList(const wxString
& filter
, int defaultFilter
)
1315 wxArrayString descriptions
, filters
;
1316 size_t n
= (size_t) wxParseCommonDialogsFilter(filter
, descriptions
, filters
);
1318 if (n
> 0 && defaultFilter
< (int) n
)
1320 for (size_t i
= 0; i
< n
; i
++)
1321 Append(descriptions
[i
]);
1322 SetSelection(defaultFilter
);
1325 #endif // wxUSE_DIRDLG
1327 #if wxUSE_DIRDLG || wxUSE_FILEDLG
1329 // ----------------------------------------------------------------------------
1330 // wxFileIconsTable icons
1331 // ----------------------------------------------------------------------------
1334 /* Computer (c) Julian Smart */
1335 static const char * file_icons_tbl_computer_xpm
[] = {
1336 /* columns rows colors chars-per-pixel */
1398 #endif // GTK+ < 2.4
1400 // ----------------------------------------------------------------------------
1401 // wxFileIconsTable & friends
1402 // ----------------------------------------------------------------------------
1404 // global instance of a wxFileIconsTable
1405 wxFileIconsTable
* wxTheFileIconsTable
= (wxFileIconsTable
*)NULL
;
1407 // A module to allow icons table cleanup
1409 class wxFileIconsTableModule
: public wxModule
1411 DECLARE_DYNAMIC_CLASS(wxFileIconsTableModule
)
1413 wxFileIconsTableModule() {}
1414 bool OnInit() { wxTheFileIconsTable
= new wxFileIconsTable
; return true; }
1417 if (wxTheFileIconsTable
)
1419 delete wxTheFileIconsTable
;
1420 wxTheFileIconsTable
= NULL
;
1425 IMPLEMENT_DYNAMIC_CLASS(wxFileIconsTableModule
, wxModule
)
1427 class wxFileIconEntry
: public wxObject
1430 wxFileIconEntry(int i
) { id
= i
; }
1435 wxFileIconsTable::wxFileIconsTable()
1438 m_smallImageList
= NULL
;
1441 wxFileIconsTable::~wxFileIconsTable()
1445 WX_CLEAR_HASH_TABLE(*m_HashTable
);
1448 if (m_smallImageList
) delete m_smallImageList
;
1451 // delayed initialization - wait until first use (wxArtProv not created yet)
1452 void wxFileIconsTable::Create()
1454 wxCHECK_RET(!m_smallImageList
&& !m_HashTable
, wxT("creating icons twice"));
1455 m_HashTable
= new wxHashTable(wxKEY_STRING
);
1456 m_smallImageList
= new wxImageList(16, 16);
1459 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER
,
1463 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER_OPEN
,
1468 // GTK24 uses this icon in the file open dialog
1469 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_HARDDISK
,
1473 m_smallImageList
->Add(wxIcon(file_icons_tbl_computer_xpm
));
1476 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_HARDDISK
,
1480 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_CDROM
,
1484 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FLOPPY
,
1488 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_REMOVABLE
,
1492 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE
,
1496 if (GetIconID(wxEmptyString
, _T("application/x-executable")) == file
)
1498 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE
,
1501 delete m_HashTable
->Get(_T("exe"));
1502 m_HashTable
->Delete(_T("exe"));
1503 m_HashTable
->Put(_T("exe"), new wxFileIconEntry(executable
));
1505 /* else put into list by GetIconID
1506 (KDE defines application/x-executable for *.exe and has nice icon)
1510 wxImageList
*wxFileIconsTable::GetSmallImageList()
1512 if (!m_smallImageList
)
1515 return m_smallImageList
;
1518 #if wxUSE_MIMETYPE && wxUSE_IMAGE && (!defined(__WXMSW__) || wxUSE_WXDIB)
1519 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
1520 // one icon and we won't resize it
1522 static wxBitmap
CreateAntialiasedBitmap(const wxImage
& img
)
1524 const unsigned int size
= 16;
1526 wxImage
smallimg (size
, size
);
1527 unsigned char *p1
, *p2
, *ps
;
1528 unsigned char mr
= img
.GetMaskRed(),
1529 mg
= img
.GetMaskGreen(),
1530 mb
= img
.GetMaskBlue();
1533 unsigned sr
, sg
, sb
, smask
;
1535 p1
= img
.GetData(), p2
= img
.GetData() + 3 * size
*2, ps
= smallimg
.GetData();
1536 smallimg
.SetMaskColour(mr
, mr
, mr
);
1538 for (y
= 0; y
< size
; y
++)
1540 for (x
= 0; x
< size
; x
++)
1542 sr
= sg
= sb
= smask
= 0;
1543 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1544 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1547 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1548 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1551 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1552 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1555 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1556 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1561 ps
[0] = ps
[1] = ps
[2] = mr
;
1564 ps
[0] = (unsigned char)(sr
>> 2);
1565 ps
[1] = (unsigned char)(sg
>> 2);
1566 ps
[2] = (unsigned char)(sb
>> 2);
1570 p1
+= size
*2 * 3, p2
+= size
*2 * 3;
1573 return wxBitmap(smallimg
);
1576 // This function is currently not unused anymore
1578 // finds empty borders and return non-empty area of image:
1579 static wxImage
CutEmptyBorders(const wxImage
& img
)
1581 unsigned char mr
= img
.GetMaskRed(),
1582 mg
= img
.GetMaskGreen(),
1583 mb
= img
.GetMaskBlue();
1584 unsigned char *dt
= img
.GetData(), *dttmp
;
1585 unsigned w
= img
.GetWidth(), h
= img
.GetHeight();
1587 unsigned top
, bottom
, left
, right
, i
;
1590 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
1591 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = false; break;}
1593 for (empt
= true, top
= 0; empt
&& top
< h
; top
++)
1596 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1599 for (empt
= true, bottom
= h
-1; empt
&& bottom
> top
; bottom
--)
1601 MK_DTTMP(0, bottom
);
1602 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1605 for (empt
= true, left
= 0; empt
&& left
< w
; left
++)
1608 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1611 for (empt
= true, right
= w
-1; empt
&& right
> left
; right
--)
1614 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1617 top
--, left
--, bottom
++, right
++;
1619 return img
.GetSubImage(wxRect(left
, top
, right
- left
+ 1, bottom
- top
+ 1));
1623 #endif // wxUSE_MIMETYPE
1625 int wxFileIconsTable::GetIconID(const wxString
& extension
, const wxString
& mime
)
1627 if (!m_smallImageList
)
1631 if (!extension
.empty())
1633 wxFileIconEntry
*entry
= (wxFileIconEntry
*) m_HashTable
->Get(extension
);
1634 if (entry
) return (entry
-> id
);
1637 wxFileType
*ft
= (mime
.empty()) ?
1638 wxTheMimeTypesManager
-> GetFileTypeFromExtension(extension
) :
1639 wxTheMimeTypesManager
-> GetFileTypeFromMimeType(mime
);
1641 wxIconLocation iconLoc
;
1646 if ( ft
&& ft
->GetIcon(&iconLoc
) )
1648 ic
= wxIcon( iconLoc
);
1657 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1662 bmp
.CopyFromIcon(ic
);
1667 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1671 const unsigned int size
= 16;
1673 int id
= m_smallImageList
->GetImageCount();
1674 if ((bmp
.GetWidth() == (int) size
) && (bmp
.GetHeight() == (int) size
))
1676 m_smallImageList
->Add(bmp
);
1678 #if wxUSE_IMAGE && (!defined(__WXMSW__) || wxUSE_WXDIB)
1681 wxImage img
= bmp
.ConvertToImage();
1683 if ((img
.GetWidth() != size
*2) || (img
.GetHeight() != size
*2))
1684 // m_smallImageList->Add(CreateAntialiasedBitmap(CutEmptyBorders(img).Rescale(size*2, size*2)));
1685 m_smallImageList
->Add(CreateAntialiasedBitmap(img
.Rescale(size
*2, size
*2)));
1687 m_smallImageList
->Add(CreateAntialiasedBitmap(img
));
1689 #endif // wxUSE_IMAGE
1691 m_HashTable
->Put(extension
, new wxFileIconEntry(id
));
1694 #else // !wxUSE_MIMETYPE
1697 if (extension
== wxT("exe"))
1701 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
1704 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG