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/choice.h"
33 #include "wx/textctrl.h"
34 #include "wx/layout.h"
36 #include "wx/textdlg.h"
37 #include "wx/gdicmn.h"
39 #include "wx/module.h"
42 #include "wx/filename.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/osx/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 char) 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 #ifdef wxHAS_FILESYSTEM_VOLUMES
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
))
167 const wxString path
= wxFileName::GetVolumeString(
168 'A' + i
, wxPATH_GET_SEPARATOR
);
169 const wxString name
= wxFileName::GetVolumeString(
170 'A' + i
, wxPATH_NO_SEPARATOR
);
172 // Note: If _filesys is unsupported by some compilers,
173 // we can always replace it by DosQueryFSAttach
174 char filesysname
[20];
176 ULONG cbBuffer
= sizeof(filesysname
);
177 PFSQBUFFER2 pfsqBuffer
= (PFSQBUFFER2
)filesysname
;
178 APIRET rc
= ::DosQueryFSAttach(name
.fn_str(),0,FSAIL_QUERYNAME
,pfsqBuffer
,&cbBuffer
);
181 filesysname
[0] = '\0';
184 _filesys(name
.fn_str(), filesysname
, sizeof(filesysname
));
186 /* FAT, LAN, HPFS, CDFS, NFS */
188 if (path
== wxT("A:\\") || path
== wxT("B:\\"))
189 imageId
= wxFileIconsTable::floppy
;
190 else if (!strcmp(filesysname
, "CDFS"))
191 imageId
= wxFileIconsTable::cdrom
;
192 else if (!strcmp(filesysname
, "LAN") ||
193 !strcmp(filesysname
, "NFS"))
194 imageId
= wxFileIconsTable::drive
;
196 imageId
= wxFileIconsTable::drive
;
199 icon_ids
.Add(imageId
);
204 #else // !__WIN32__, !__OS2__
205 /* If we can switch to the drive, it exists. */
206 for ( char drive
= 'A'; drive
<= 'Z'; drive
++ )
209 path
= wxFileName::GetVolumeString(drive
, wxPATH_GET_SEPARATOR
);
211 if (wxIsDriveAvailable(path
))
214 names
.Add(wxFileName::GetVolumeString(drive
, wxPATH_NO_SEPARATOR
));
215 icon_ids
.Add(drive
<= 2 ? wxFileIconsTable::floppy
216 : wxFileIconsTable::drive
);
219 #endif // __WIN32__/!__WIN32__
221 #elif defined(__WXMAC__) && wxOSX_USE_COCOA_OR_CARBON
223 ItemCount volumeIndex
= 1;
226 while( noErr
== err
)
228 HFSUniStr255 volumeName
;
230 FSVolumeInfo volumeInfo
;
231 err
= FSGetVolumeInfo(0, volumeIndex
, NULL
, kFSVolInfoFlags
, &volumeInfo
, &volumeName
, &fsRef
);
234 wxString path
= wxMacFSRefToPath( &fsRef
) ;
235 wxString name
= wxMacHFSUniStrToString( &volumeName
) ;
237 if ( (volumeInfo
.flags
& kFSVolFlagSoftwareLockedMask
) || (volumeInfo
.flags
& kFSVolFlagHardwareLockedMask
) )
239 icon_ids
.Add(wxFileIconsTable::cdrom
);
243 icon_ids
.Add(wxFileIconsTable::drive
);
245 // todo other removable
253 #elif defined(__UNIX__)
256 icon_ids
.Add(wxFileIconsTable::computer
);
258 #error "Unsupported platform in wxGenericDirCtrl!"
260 wxASSERT_MSG( (paths
.GetCount() == names
.GetCount()), wxT("The number of paths and their human readable names should be equal in number."));
261 wxASSERT_MSG( (paths
.GetCount() == icon_ids
.GetCount()), wxT("Wrong number of icons for available drives."));
262 return paths
.GetCount();
265 // ----------------------------------------------------------------------------
266 // wxIsDriveAvailable
267 // ----------------------------------------------------------------------------
271 bool wxIsDriveAvailable(const wxString
& dirName
)
273 // FIXME: this method leads to hang up under Watcom for some reason
275 wxUnusedVar(dirName
);
277 if ( dirName
.length() == 3 && dirName
[1u] == wxT(':') )
279 wxString
dirNameLower(dirName
.Lower());
280 // VS: always return true for removable media, since Win95 doesn't
281 // like it when MS-DOS app accesses empty floppy drive
282 return (dirNameLower
[0u] == wxT('a') ||
283 dirNameLower
[0u] == wxT('b') ||
284 wxDirExists(dirNameLower
));
291 #elif defined(__WINDOWS__) || defined(__OS2__)
293 int setdrive(int WXUNUSED_IN_WINCE(drive
))
297 #elif defined(__GNUWIN32__) && \
298 (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
299 return _chdrive(drive
);
303 if (drive
< 1 || drive
> 31)
305 newdrive
[0] = (wxChar
)(wxT('A') + drive
- 1);
306 newdrive
[1] = wxT(':');
308 newdrive
[2] = wxT('\\');
309 newdrive
[3] = wxT('\0');
311 newdrive
[2] = wxT('\0');
313 #if defined(__WINDOWS__)
314 if (::SetCurrentDirectory(newdrive
))
316 // VA doesn't know what LPSTR is and has its own set
317 if (!DosSetCurrentDir((PSZ
)newdrive
))
325 bool wxIsDriveAvailable(const wxString
& WXUNUSED_IN_WINCE(dirName
))
331 UINT errorMode
= SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOOPENFILEERRORBOX
);
335 // Check if this is a root directory and if so,
336 // whether the drive is available.
337 if (dirName
.length() == 3 && dirName
[(size_t)1] == wxT(':'))
339 wxString
dirNameLower(dirName
.Lower());
340 #if defined(__GNUWIN32__) && !(defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
341 success
= wxDirExists(dirNameLower
);
344 // Avoid changing to drive since no media may be inserted.
345 if (dirNameLower
[(size_t)0] == 'a' || dirNameLower
[(size_t)0] == 'b')
348 int currentDrive
= _getdrive();
349 int thisDrive
= (int) (dirNameLower
[(size_t)0] - 'a' + 1) ;
350 int err
= setdrive( thisDrive
) ;
351 setdrive( currentDrive
);
360 (void) SetErrorMode(errorMode
);
366 #endif // __WINDOWS__ || __OS2__
368 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG
374 // Function which is called by quick sort. We want to override the default wxArrayString behaviour,
375 // and sort regardless of case.
376 static int wxCMPFUNC_CONV
wxDirCtrlStringCompareFunction(const wxString
& strFirst
, const wxString
& strSecond
)
378 return strFirst
.CmpNoCase(strSecond
);
381 //-----------------------------------------------------------------------------
383 //-----------------------------------------------------------------------------
385 wxDirItemData::wxDirItemData(const wxString
& path
, const wxString
& name
,
390 /* Insert logic to detect hidden files here
391 * In UnixLand we just check whether the first char is a dot
392 * For FileNameFromPath read LastDirNameInThisPath ;-) */
393 // m_isHidden = (bool)(wxFileNameFromPath(*m_path)[0] == '.');
395 m_isExpanded
= false;
399 void wxDirItemData::SetNewDirName(const wxString
& path
)
402 m_name
= wxFileNameFromPath(path
);
405 bool wxDirItemData::HasSubDirs() const
413 if ( !dir
.Open(m_path
) )
417 return dir
.HasSubDirs();
420 bool wxDirItemData::HasFiles(const wxString
& WXUNUSED(spec
)) const
428 if ( !dir
.Open(m_path
) )
432 return dir
.HasFiles();
435 //-----------------------------------------------------------------------------
437 //-----------------------------------------------------------------------------
439 BEGIN_EVENT_TABLE(wxGenericDirCtrl
, wxControl
)
440 EVT_TREE_ITEM_EXPANDING (wxID_TREECTRL
, wxGenericDirCtrl::OnExpandItem
)
441 EVT_TREE_ITEM_COLLAPSED (wxID_TREECTRL
, wxGenericDirCtrl::OnCollapseItem
)
442 EVT_TREE_BEGIN_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnBeginEditItem
)
443 EVT_TREE_END_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnEndEditItem
)
444 EVT_SIZE (wxGenericDirCtrl::OnSize
)
447 wxGenericDirCtrl::wxGenericDirCtrl(void)
452 void wxGenericDirCtrl::ExpandRoot()
454 ExpandDir(m_rootId
); // automatically expand first level
456 // Expand and select the default path
457 if (!m_defaultPath
.empty())
459 ExpandPath(m_defaultPath
);
464 // On Unix, there's only one node under the (hidden) root node. It
465 // represents the / path, so the user would always have to expand it;
466 // let's do it ourselves
467 ExpandPath( wxT("/") );
472 bool wxGenericDirCtrl::Create(wxWindow
*parent
,
473 const wxWindowID treeid
,
478 const wxString
& filter
,
480 const wxString
& name
)
482 if (!wxControl::Create(parent
, treeid
, pos
, size
, style
, wxDefaultValidator
, name
))
485 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE
));
486 SetForegroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT
));
490 long treeStyle
= wxTR_HAS_BUTTONS
;
492 // On Windows CE, if you hide the root, you get a crash when
493 // attempting to access data for children of the root item.
495 treeStyle
|= wxTR_HIDE_ROOT
;
499 treeStyle
|= wxTR_NO_LINES
;
502 if (style
& wxDIRCTRL_EDIT_LABELS
)
503 treeStyle
|= wxTR_EDIT_LABELS
;
505 if (style
& wxDIRCTRL_MULTIPLE
)
506 treeStyle
|= wxTR_MULTIPLE
;
508 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
509 treeStyle
|= wxNO_BORDER
;
511 m_treeCtrl
= CreateTreeCtrl(this, wxID_TREECTRL
,
512 wxPoint(0,0), GetClientSize(), treeStyle
);
515 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
);
520 if (m_filter
.empty())
521 m_filter
= wxFileSelectorDefaultWildcardStr
;
523 SetFilterIndex(defaultFilter
);
525 if (m_filterListCtrl
)
526 m_filterListCtrl
->FillFilterList(filter
, defaultFilter
);
528 m_treeCtrl
->SetImageList(wxTheFileIconsTable
->GetSmallImageList());
530 m_showHidden
= false;
531 wxDirItemData
* rootData
= new wxDirItemData(wxEmptyString
, wxEmptyString
, true);
535 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
536 rootName
= _("Computer");
538 rootName
= _("Sections");
541 m_rootId
= m_treeCtrl
->AddRoot( rootName
, 3, -1, rootData
);
542 m_treeCtrl
->SetItemHasChildren(m_rootId
);
546 SetInitialSize(size
);
552 wxGenericDirCtrl::~wxGenericDirCtrl()
556 void wxGenericDirCtrl::Init()
558 m_showHidden
= false;
560 m_currentFilterStr
= wxEmptyString
; // Default: any file
562 m_filterListCtrl
= NULL
;
565 wxTreeCtrl
* wxGenericDirCtrl::CreateTreeCtrl(wxWindow
*parent
, wxWindowID treeid
, const wxPoint
& pos
, const wxSize
& size
, long treeStyle
)
567 return new wxTreeCtrl(parent
, treeid
, pos
, size
, treeStyle
);
570 void wxGenericDirCtrl::ShowHidden( bool show
)
572 if ( m_showHidden
== show
)
577 if ( HasFlag(wxDIRCTRL_MULTIPLE
) )
582 for ( unsigned n
= 0; n
< paths
.size(); n
++ )
584 ExpandPath(paths
[n
]);
589 wxString path
= GetPath();
596 wxGenericDirCtrl::AddSection(const wxString
& path
, const wxString
& name
, int imageId
)
598 wxDirItemData
*dir_item
= new wxDirItemData(path
,name
,true);
600 wxTreeItemId treeid
= AppendItem( m_rootId
, name
, imageId
, -1, dir_item
);
602 m_treeCtrl
->SetItemHasChildren(treeid
);
607 void wxGenericDirCtrl::SetupSections()
609 wxArrayString paths
, names
;
612 size_t n
, count
= wxGetAvailableDrives(paths
, names
, icons
);
615 wxString home
= wxGetHomeDir();
616 AddSection( home
, _("Home directory"), 1);
617 home
+= wxT("/Desktop");
618 AddSection( home
, _("Desktop"), 1);
621 for (n
= 0; n
< count
; n
++)
622 AddSection(paths
[n
], names
[n
], icons
[n
]);
625 void wxGenericDirCtrl::SetFocus()
627 // we don't need focus ourselves, give it to the tree so that the user
630 m_treeCtrl
->SetFocus();
633 void wxGenericDirCtrl::OnBeginEditItem(wxTreeEvent
&event
)
635 // don't rename the main entry "Sections"
636 if (event
.GetItem() == m_rootId
)
642 // don't rename the individual sections
643 if (m_treeCtrl
->GetItemParent( event
.GetItem() ) == m_rootId
)
650 void wxGenericDirCtrl::OnEndEditItem(wxTreeEvent
&event
)
652 if (event
.IsEditCancelled())
655 if ((event
.GetLabel().empty()) ||
656 (event
.GetLabel() == wxT(".")) ||
657 (event
.GetLabel() == wxT("..")) ||
658 (event
.GetLabel().Find(wxT('/')) != wxNOT_FOUND
) ||
659 (event
.GetLabel().Find(wxT('\\')) != wxNOT_FOUND
) ||
660 (event
.GetLabel().Find(wxT('|')) != wxNOT_FOUND
))
662 wxMessageDialog
dialog(this, _("Illegal directory name."), _("Error"), wxOK
| wxICON_ERROR
);
668 wxTreeItemId treeid
= event
.GetItem();
669 wxDirItemData
*data
= (wxDirItemData
*)m_treeCtrl
->GetItemData( treeid
);
672 wxString
new_name( wxPathOnly( data
->m_path
) );
673 new_name
+= wxString(wxFILE_SEP_PATH
);
674 new_name
+= event
.GetLabel();
678 if (wxFileExists(new_name
))
680 wxMessageDialog
dialog(this, _("File name exists already."), _("Error"), wxOK
| wxICON_ERROR
);
685 if (wxRenameFile(data
->m_path
,new_name
))
687 data
->SetNewDirName( new_name
);
691 wxMessageDialog
dialog(this, _("Operation not permitted."), _("Error"), wxOK
| wxICON_ERROR
);
697 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent
&event
)
699 wxTreeItemId parentId
= event
.GetItem();
701 // VS: this is needed because the event handler is called from wxTreeCtrl
702 // ctor when wxTR_HIDE_ROOT was specified
704 if (!m_rootId
.IsOk())
705 m_rootId
= m_treeCtrl
->GetRootItem();
710 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent
&event
)
712 CollapseDir(event
.GetItem());
715 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId
)
719 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
720 if (!data
->m_isExpanded
)
723 data
->m_isExpanded
= false;
725 m_treeCtrl
->Freeze();
726 if (parentId
!= m_treeCtrl
->GetRootItem())
727 m_treeCtrl
->CollapseAndReset(parentId
);
728 m_treeCtrl
->DeleteChildren(parentId
);
732 void wxGenericDirCtrl::PopulateNode(wxTreeItemId parentId
)
734 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
736 if (data
->m_isExpanded
)
739 data
->m_isExpanded
= true;
741 if (parentId
== m_treeCtrl
->GetRootItem())
749 wxString search
,path
,filename
;
751 wxString
dirName(data
->m_path
);
753 #if (defined(__WINDOWS__) && !defined(__WXWINCE__)) || defined(__DOS__) || defined(__OS2__)
754 // Check if this is a root directory and if so,
755 // whether the drive is avaiable.
756 if (!wxIsDriveAvailable(dirName
))
758 data
->m_isExpanded
= false;
759 //wxMessageBox(wxT("Sorry, this drive is not available."));
764 // This may take a longish time. Go to busy cursor
767 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
768 if (dirName
.Last() == ':')
769 dirName
+= wxString(wxFILE_SEP_PATH
);
773 wxArrayString filenames
;
776 wxString eachFilename
;
783 int style
= wxDIR_DIRS
;
784 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
785 if (d
.GetFirst(& eachFilename
, wxEmptyString
, style
))
789 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
791 dirs
.Add(eachFilename
);
794 while (d
.GetNext(&eachFilename
));
797 dirs
.Sort(wxDirCtrlStringCompareFunction
);
799 // Now do the filenames -- but only if we're allowed to
800 if (!HasFlag(wxDIRCTRL_DIR_ONLY
))
806 int style
= wxDIR_FILES
;
807 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
808 // Process each filter (ex: "JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg")
809 wxStringTokenizer strTok
;
811 strTok
.SetString(m_currentFilterStr
,wxT(";"));
812 while(strTok
.HasMoreTokens())
814 curFilter
= strTok
.GetNextToken();
815 if (d
.GetFirst(& eachFilename
, curFilter
, style
))
819 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
821 filenames
.Add(eachFilename
);
824 while (d
.GetNext(& eachFilename
));
828 filenames
.Sort(wxDirCtrlStringCompareFunction
);
831 // Now we really know whether we have any children so tell the tree control
833 m_treeCtrl
->SetItemHasChildren(parentId
, !dirs
.empty() || !filenames
.empty());
835 // Add the sorted dirs
837 for (i
= 0; i
< dirs
.GetCount(); i
++)
839 eachFilename
= dirs
[i
];
841 if (!wxEndsWithPathSeparator(path
))
842 path
+= wxString(wxFILE_SEP_PATH
);
843 path
+= eachFilename
;
845 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,true);
846 wxTreeItemId treeid
= AppendItem( parentId
, eachFilename
,
847 wxFileIconsTable::folder
, -1, dir_item
);
848 m_treeCtrl
->SetItemImage( treeid
, wxFileIconsTable::folder_open
,
849 wxTreeItemIcon_Expanded
);
851 // assume that it does have children by default as it can take a long
852 // time to really check for this (think remote drives...)
854 // and if we're wrong, we'll correct the icon later if
855 // the user really tries to open this item
856 m_treeCtrl
->SetItemHasChildren(treeid
);
859 // Add the sorted filenames
860 if (!HasFlag(wxDIRCTRL_DIR_ONLY
))
862 for (i
= 0; i
< filenames
.GetCount(); i
++)
864 eachFilename
= filenames
[i
];
866 if (!wxEndsWithPathSeparator(path
))
867 path
+= wxString(wxFILE_SEP_PATH
);
868 path
+= eachFilename
;
869 //path = dirName + wxString(wxT("/")) + eachFilename;
870 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,false);
871 int image_id
= wxFileIconsTable::file
;
872 if (eachFilename
.Find(wxT('.')) != wxNOT_FOUND
)
873 image_id
= wxTheFileIconsTable
->GetIconID(eachFilename
.AfterLast(wxT('.')));
874 (void) AppendItem( parentId
, eachFilename
, image_id
, -1, dir_item
);
879 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId
)
881 // ExpandDir() will not actually expand the tree node, just populate it
882 PopulateNode(parentId
);
885 void wxGenericDirCtrl::ReCreateTree()
887 CollapseDir(m_treeCtrl
->GetRootItem());
891 void wxGenericDirCtrl::CollapseTree()
893 wxTreeItemIdValue cookie
;
894 wxTreeItemId child
= m_treeCtrl
->GetFirstChild(m_rootId
, cookie
);
898 child
= m_treeCtrl
->GetNextChild(m_rootId
, cookie
);
902 // Find the child that matches the first part of 'path'.
903 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
904 // then the child for /usr is returned.
905 wxTreeItemId
wxGenericDirCtrl::FindChild(wxTreeItemId parentId
, const wxString
& path
, bool& done
)
907 wxString
path2(path
);
909 // Make sure all separators are as per the current platform
910 path2
.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH
));
911 path2
.Replace(wxT("/"), wxString(wxFILE_SEP_PATH
));
913 // Append a separator to foil bogus substring matching
914 path2
+= wxString(wxFILE_SEP_PATH
);
916 // In MSW or PM, case is not significant
917 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
921 wxTreeItemIdValue cookie
;
922 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
923 while (childId
.IsOk())
925 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
927 if (data
&& !data
->m_path
.empty())
929 wxString
childPath(data
->m_path
);
930 if (!wxEndsWithPathSeparator(childPath
))
931 childPath
+= wxString(wxFILE_SEP_PATH
);
933 // In MSW and PM, case is not significant
934 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
935 childPath
.MakeLower();
938 if (childPath
.length() <= path2
.length())
940 wxString path3
= path2
.Mid(0, childPath
.length());
941 if (childPath
== path3
)
943 if (path3
.length() == path2
.length())
952 childId
= m_treeCtrl
->GetNextChild(parentId
, cookie
);
954 wxTreeItemId invalid
;
958 // Try to expand as much of the given path as possible,
959 // and select the given tree item.
960 bool wxGenericDirCtrl::ExpandPath(const wxString
& path
)
963 wxTreeItemId treeid
= FindChild(m_rootId
, path
, done
);
964 wxTreeItemId lastId
= treeid
; // The last non-zero treeid
965 while (treeid
.IsOk() && !done
)
969 treeid
= FindChild(treeid
, path
, done
);
976 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(lastId
);
979 m_treeCtrl
->Expand(lastId
);
981 if (HasFlag(wxDIRCTRL_SELECT_FIRST
) && data
->m_isDir
)
983 // Find the first file in this directory
984 wxTreeItemIdValue cookie
;
985 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(lastId
, cookie
);
986 bool selectedChild
= false;
987 while (childId
.IsOk())
989 data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
991 if (data
&& data
->m_path
!= wxEmptyString
&& !data
->m_isDir
)
993 m_treeCtrl
->SelectItem(childId
);
994 m_treeCtrl
->EnsureVisible(childId
);
995 selectedChild
= true;
998 childId
= m_treeCtrl
->GetNextChild(lastId
, cookie
);
1002 m_treeCtrl
->SelectItem(lastId
);
1003 m_treeCtrl
->EnsureVisible(lastId
);
1008 m_treeCtrl
->SelectItem(lastId
);
1009 m_treeCtrl
->EnsureVisible(lastId
);
1016 bool wxGenericDirCtrl::CollapsePath(const wxString
& path
)
1019 wxTreeItemId treeid
= FindChild(m_rootId
, path
, done
);
1020 wxTreeItemId lastId
= treeid
; // The last non-zero treeid
1022 while ( treeid
.IsOk() && !done
)
1024 CollapseDir(treeid
);
1026 treeid
= FindChild(treeid
, path
, done
);
1028 if ( treeid
.IsOk() )
1032 if ( !lastId
.IsOk() )
1035 m_treeCtrl
->SelectItem(lastId
);
1036 m_treeCtrl
->EnsureVisible(lastId
);
1041 wxString
wxGenericDirCtrl::GetPath(wxTreeItemId itemId
) const
1043 const wxDirItemData
*
1044 data
= static_cast<wxDirItemData
*>(m_treeCtrl
->GetItemData(itemId
));
1046 return data
->m_path
;
1049 wxString
wxGenericDirCtrl::GetPath() const
1051 // Allow calling GetPath() in multiple selection from OnSelFilter
1052 if (m_treeCtrl
->HasFlag(wxTR_MULTIPLE
))
1054 wxArrayTreeItemIds items
;
1055 m_treeCtrl
->GetSelections(items
);
1056 if (items
.size() > 0)
1058 // return first string only
1059 wxTreeItemId treeid
= items
[0];
1060 return GetPath(treeid
);
1063 return wxEmptyString
;
1066 wxTreeItemId treeid
= m_treeCtrl
->GetSelection();
1069 return GetPath(treeid
);
1072 return wxEmptyString
;
1075 void wxGenericDirCtrl::GetPaths(wxArrayString
& paths
) const
1079 wxArrayTreeItemIds items
;
1080 m_treeCtrl
->GetSelections(items
);
1081 for ( unsigned n
= 0; n
< items
.size(); n
++ )
1083 wxTreeItemId treeid
= items
[n
];
1084 paths
.push_back(GetPath(treeid
));
1088 wxString
wxGenericDirCtrl::GetFilePath() const
1090 wxTreeItemId treeid
= m_treeCtrl
->GetSelection();
1093 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(treeid
);
1095 return wxEmptyString
;
1097 return data
->m_path
;
1100 return wxEmptyString
;
1103 void wxGenericDirCtrl::GetFilePaths(wxArrayString
& paths
) const
1107 wxArrayTreeItemIds items
;
1108 m_treeCtrl
->GetSelections(items
);
1109 for ( unsigned n
= 0; n
< items
.size(); n
++ )
1111 wxTreeItemId treeid
= items
[n
];
1112 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(treeid
);
1113 if ( !data
->m_isDir
)
1114 paths
.Add(data
->m_path
);
1118 void wxGenericDirCtrl::SetPath(const wxString
& path
)
1120 m_defaultPath
= path
;
1125 void wxGenericDirCtrl::SelectPath(const wxString
& path
, bool select
)
1128 wxTreeItemId treeid
= FindChild(m_rootId
, path
, done
);
1129 wxTreeItemId lastId
= treeid
; // The last non-zero treeid
1130 while ( treeid
.IsOk() && !done
)
1132 treeid
= FindChild(treeid
, path
, done
);
1133 if ( treeid
.IsOk() )
1136 if ( !lastId
.IsOk() )
1141 m_treeCtrl
->SelectItem(treeid
, select
);
1145 void wxGenericDirCtrl::SelectPaths(const wxArrayString
& paths
)
1147 if ( HasFlag(wxDIRCTRL_MULTIPLE
) )
1150 for ( unsigned n
= 0; n
< paths
.size(); n
++ )
1152 SelectPath(paths
[n
]);
1157 void wxGenericDirCtrl::UnselectAll()
1159 m_treeCtrl
->UnselectAll();
1164 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId treeid
, int dirFlags
, wxArrayString
& filenames
)
1166 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(treeid
);
1168 // This may take a longish time. Go to busy cursor
1173 wxString search
,path
,filename
;
1175 wxString
dirName(data
->m_path
);
1177 #if defined(__WINDOWS__) || defined(__OS2__)
1178 if (dirName
.Last() == ':')
1179 dirName
+= wxString(wxFILE_SEP_PATH
);
1183 wxString eachFilename
;
1190 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, dirFlags
))
1194 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
1196 filenames
.Add(eachFilename
);
1199 while (d
.GetNext(& eachFilename
)) ;
1205 void wxGenericDirCtrl::SetFilterIndex(int n
)
1207 m_currentFilter
= n
;
1210 if (ExtractWildcard(m_filter
, n
, f
, d
))
1211 m_currentFilterStr
= f
;
1214 m_currentFilterStr
= wxT("*");
1216 m_currentFilterStr
= wxT("*.*");
1220 void wxGenericDirCtrl::SetFilter(const wxString
& filter
)
1224 if (!filter
.empty() && !m_filterListCtrl
)
1225 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
);
1226 else if (filter
.empty() && m_filterListCtrl
)
1228 m_filterListCtrl
->Destroy();
1229 m_filterListCtrl
= NULL
;
1233 if (ExtractWildcard(m_filter
, m_currentFilter
, f
, d
))
1234 m_currentFilterStr
= f
;
1237 m_currentFilterStr
= wxT("*");
1239 m_currentFilterStr
= wxT("*.*");
1241 // current filter index is meaningless after filter change, set it to zero
1243 if (m_filterListCtrl
)
1244 m_filterListCtrl
->FillFilterList(m_filter
, 0);
1247 // Extract description and actual filter from overall filter string
1248 bool wxGenericDirCtrl::ExtractWildcard(const wxString
& filterStr
, int n
, wxString
& filter
, wxString
& description
)
1250 wxArrayString filters
, descriptions
;
1251 int count
= wxParseCommonDialogsFilter(filterStr
, descriptions
, filters
);
1252 if (count
> 0 && n
< count
)
1254 filter
= filters
[n
];
1255 description
= descriptions
[n
];
1263 void wxGenericDirCtrl::DoResize()
1265 wxSize sz
= GetClientSize();
1266 int verticalSpacing
= 3;
1270 if (m_filterListCtrl
)
1272 filterSz
= m_filterListCtrl
->GetSize();
1273 sz
.y
-= (filterSz
.y
+ verticalSpacing
);
1275 m_treeCtrl
->SetSize(0, 0, sz
.x
, sz
.y
);
1276 if (m_filterListCtrl
)
1278 m_filterListCtrl
->SetSize(0, sz
.y
+ verticalSpacing
, sz
.x
, filterSz
.y
);
1279 // Don't know why, but this needs refreshing after a resize (wxMSW)
1280 m_filterListCtrl
->Refresh();
1286 void wxGenericDirCtrl::OnSize(wxSizeEvent
& WXUNUSED(event
))
1291 wxTreeItemId
wxGenericDirCtrl::AppendItem (const wxTreeItemId
& parent
,
1292 const wxString
& text
,
1293 int image
, int selectedImage
,
1294 wxTreeItemData
* data
)
1296 wxTreeCtrl
*treeCtrl
= GetTreeCtrl ();
1298 wxASSERT (treeCtrl
);
1302 return treeCtrl
->AppendItem (parent
, text
, image
, selectedImage
, data
);
1306 return wxTreeItemId();
1311 //-----------------------------------------------------------------------------
1312 // wxDirFilterListCtrl
1313 //-----------------------------------------------------------------------------
1315 IMPLEMENT_CLASS(wxDirFilterListCtrl
, wxChoice
)
1317 BEGIN_EVENT_TABLE(wxDirFilterListCtrl
, wxChoice
)
1318 EVT_CHOICE(wxID_ANY
, wxDirFilterListCtrl::OnSelFilter
)
1321 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl
* parent
,
1322 const wxWindowID treeid
,
1329 // by default our border style is determined by the style of our parent
1330 if ( !(style
& wxBORDER_MASK
) )
1332 style
|= parent
->HasFlag(wxDIRCTRL_3D_INTERNAL
) ? wxBORDER_SUNKEN
1336 return wxChoice::Create(parent
, treeid
, pos
, size
, 0, NULL
, style
);
1339 void wxDirFilterListCtrl::Init()
1344 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent
& WXUNUSED(event
))
1346 int sel
= GetSelection();
1348 if (m_dirCtrl
->HasFlag(wxDIRCTRL_MULTIPLE
))
1350 wxArrayString paths
;
1351 m_dirCtrl
->GetPaths(paths
);
1353 m_dirCtrl
->SetFilterIndex(sel
);
1355 // If the filter has changed, the view is out of date, so
1356 // collapse the tree.
1357 m_dirCtrl
->ReCreateTree();
1359 // Expand and select the previously selected paths
1360 for (unsigned int i
= 0; i
< paths
.GetCount(); i
++)
1362 m_dirCtrl
->ExpandPath(paths
.Item(i
));
1367 wxString currentPath
= m_dirCtrl
->GetPath();
1369 m_dirCtrl
->SetFilterIndex(sel
);
1370 m_dirCtrl
->ReCreateTree();
1372 // Try to restore the selection, or at least the directory
1373 m_dirCtrl
->ExpandPath(currentPath
);
1377 void wxDirFilterListCtrl::FillFilterList(const wxString
& filter
, int defaultFilter
)
1380 wxArrayString descriptions
, filters
;
1381 size_t n
= (size_t) wxParseCommonDialogsFilter(filter
, descriptions
, filters
);
1383 if (n
> 0 && defaultFilter
< (int) n
)
1385 for (size_t i
= 0; i
< n
; i
++)
1386 Append(descriptions
[i
]);
1387 SetSelection(defaultFilter
);
1390 #endif // wxUSE_DIRDLG
1392 #if wxUSE_DIRDLG || wxUSE_FILEDLG
1394 // ----------------------------------------------------------------------------
1395 // wxFileIconsTable icons
1396 // ----------------------------------------------------------------------------
1399 /* Computer (c) Julian Smart */
1400 static const char* const file_icons_tbl_computer_xpm
[] = {
1401 /* columns rows colors chars-per-pixel */
1465 // ----------------------------------------------------------------------------
1466 // wxFileIconsTable & friends
1467 // ----------------------------------------------------------------------------
1469 // global instance of a wxFileIconsTable
1470 wxFileIconsTable
* wxTheFileIconsTable
= NULL
;
1472 // A module to allow icons table cleanup
1474 class wxFileIconsTableModule
: public wxModule
1476 DECLARE_DYNAMIC_CLASS(wxFileIconsTableModule
)
1478 wxFileIconsTableModule() {}
1479 bool OnInit() { wxTheFileIconsTable
= new wxFileIconsTable
; return true; }
1482 wxDELETE(wxTheFileIconsTable
);
1486 IMPLEMENT_DYNAMIC_CLASS(wxFileIconsTableModule
, wxModule
)
1488 class wxFileIconEntry
: public wxObject
1491 wxFileIconEntry(int i
) { iconid
= i
; }
1496 wxFileIconsTable::wxFileIconsTable()
1499 m_smallImageList
= NULL
;
1502 wxFileIconsTable::~wxFileIconsTable()
1506 WX_CLEAR_HASH_TABLE(*m_HashTable
);
1509 if (m_smallImageList
) delete m_smallImageList
;
1512 // delayed initialization - wait until first use (wxArtProv not created yet)
1513 void wxFileIconsTable::Create()
1515 wxCHECK_RET(!m_smallImageList
&& !m_HashTable
, wxT("creating icons twice"));
1516 m_HashTable
= new wxHashTable(wxKEY_STRING
);
1517 m_smallImageList
= new wxImageList(16, 16);
1520 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER
,
1524 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER_OPEN
,
1529 // GTK24 uses this icon in the file open dialog
1530 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_HARDDISK
,
1534 m_smallImageList
->Add(wxIcon(file_icons_tbl_computer_xpm
));
1537 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_HARDDISK
,
1541 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_CDROM
,
1545 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FLOPPY
,
1549 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_REMOVABLE
,
1553 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE
,
1557 if (GetIconID(wxEmptyString
, wxT("application/x-executable")) == file
)
1559 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE
,
1562 delete m_HashTable
->Get(wxT("exe"));
1563 m_HashTable
->Delete(wxT("exe"));
1564 m_HashTable
->Put(wxT("exe"), new wxFileIconEntry(executable
));
1566 /* else put into list by GetIconID
1567 (KDE defines application/x-executable for *.exe and has nice icon)
1571 wxImageList
*wxFileIconsTable::GetSmallImageList()
1573 if (!m_smallImageList
)
1576 return m_smallImageList
;
1579 #if wxUSE_MIMETYPE && wxUSE_IMAGE && (!defined(__WINDOWS__) || wxUSE_WXDIB)
1580 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
1581 // one icon and we won't resize it
1583 static wxBitmap
CreateAntialiasedBitmap(const wxImage
& img
)
1585 const unsigned int size
= 16;
1587 wxImage
smallimg (size
, size
);
1588 unsigned char *p1
, *p2
, *ps
;
1589 unsigned char mr
= img
.GetMaskRed(),
1590 mg
= img
.GetMaskGreen(),
1591 mb
= img
.GetMaskBlue();
1594 unsigned sr
, sg
, sb
, smask
;
1596 p1
= img
.GetData(), p2
= img
.GetData() + 3 * size
*2, ps
= smallimg
.GetData();
1597 smallimg
.SetMaskColour(mr
, mr
, mr
);
1599 for (y
= 0; y
< size
; y
++)
1601 for (x
= 0; x
< size
; x
++)
1603 sr
= sg
= sb
= smask
= 0;
1604 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1605 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1608 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1609 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1612 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1613 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1616 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1617 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1622 ps
[0] = ps
[1] = ps
[2] = mr
;
1625 ps
[0] = (unsigned char)(sr
>> 2);
1626 ps
[1] = (unsigned char)(sg
>> 2);
1627 ps
[2] = (unsigned char)(sb
>> 2);
1631 p1
+= size
*2 * 3, p2
+= size
*2 * 3;
1634 return wxBitmap(smallimg
);
1637 // This function is currently not unused anymore
1639 // finds empty borders and return non-empty area of image:
1640 static wxImage
CutEmptyBorders(const wxImage
& img
)
1642 unsigned char mr
= img
.GetMaskRed(),
1643 mg
= img
.GetMaskGreen(),
1644 mb
= img
.GetMaskBlue();
1645 unsigned char *dt
= img
.GetData(), *dttmp
;
1646 unsigned w
= img
.GetWidth(), h
= img
.GetHeight();
1648 unsigned top
, bottom
, left
, right
, i
;
1651 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
1652 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = false; break;}
1654 for (empt
= true, top
= 0; empt
&& top
< h
; top
++)
1657 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1660 for (empt
= true, bottom
= h
-1; empt
&& bottom
> top
; bottom
--)
1662 MK_DTTMP(0, bottom
);
1663 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1666 for (empt
= true, left
= 0; empt
&& left
< w
; left
++)
1669 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1672 for (empt
= true, right
= w
-1; empt
&& right
> left
; right
--)
1675 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1678 top
--, left
--, bottom
++, right
++;
1680 return img
.GetSubImage(wxRect(left
, top
, right
- left
+ 1, bottom
- top
+ 1));
1684 #endif // wxUSE_MIMETYPE
1686 int wxFileIconsTable::GetIconID(const wxString
& extension
, const wxString
& mime
)
1688 if (!m_smallImageList
)
1692 if (!extension
.empty())
1694 wxFileIconEntry
*entry
= (wxFileIconEntry
*) m_HashTable
->Get(extension
);
1695 if (entry
) return (entry
-> iconid
);
1698 wxFileType
*ft
= (mime
.empty()) ?
1699 wxTheMimeTypesManager
-> GetFileTypeFromExtension(extension
) :
1700 wxTheMimeTypesManager
-> GetFileTypeFromMimeType(mime
);
1702 wxIconLocation iconLoc
;
1707 if ( ft
&& ft
->GetIcon(&iconLoc
) )
1709 ic
= wxIcon( iconLoc
);
1718 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1723 bmp
.CopyFromIcon(ic
);
1728 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1732 const unsigned int size
= 16;
1734 int treeid
= m_smallImageList
->GetImageCount();
1735 if ((bmp
.GetWidth() == (int) size
) && (bmp
.GetHeight() == (int) size
))
1737 m_smallImageList
->Add(bmp
);
1739 #if wxUSE_IMAGE && (!defined(__WINDOWS__) || wxUSE_WXDIB)
1742 wxImage img
= bmp
.ConvertToImage();
1744 if ((img
.GetWidth() != size
*2) || (img
.GetHeight() != size
*2))
1745 // m_smallImageList->Add(CreateAntialiasedBitmap(CutEmptyBorders(img).Rescale(size*2, size*2)));
1746 m_smallImageList
->Add(CreateAntialiasedBitmap(img
.Rescale(size
*2, size
*2)));
1748 m_smallImageList
->Add(CreateAntialiasedBitmap(img
));
1750 #endif // wxUSE_IMAGE
1752 m_HashTable
->Put(extension
, new wxFileIconEntry(treeid
));
1755 #else // !wxUSE_MIMETYPE
1758 if (extension
== wxT("exe"))
1762 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
1765 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG