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/filename.h"
44 #include "wx/filefn.h"
45 #include "wx/imaglist.h"
46 #include "wx/tokenzr.h"
48 #include "wx/artprov.h"
49 #include "wx/mimetype.h"
52 #include "wx/statline.h"
55 #if defined(__WXMAC__)
56 #include "wx/osx/private.h" // includes mac headers
61 #include "wx/msw/winundef.h"
62 #include "wx/volume.h"
64 // FIXME - Mingw32 1.0 has both _getdrive() and _chdrive(). For now, let's assume
65 // older releases don't, but it should be verified and the checks modified
67 #if !defined(__GNUWIN32__) || (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
68 #if !defined(__WXWINCE__)
77 #if defined(__OS2__) || defined(__DOS__)
89 #if defined(__WXMAC__)
90 // #include "MoreFilesX.h"
97 extern WXDLLEXPORT_DATA(const char) wxFileSelectorDefaultWildcardStr
[];
99 // If compiled under Windows, this macro can cause problems
104 bool wxIsDriveAvailable(const wxString
& dirName
);
106 // ----------------------------------------------------------------------------
107 // wxGetAvailableDrives, for WINDOWS, DOS, OS2, MAC, UNIX (returns "/")
108 // ----------------------------------------------------------------------------
110 size_t wxGetAvailableDrives(wxArrayString
&paths
, wxArrayString
&names
, wxArrayInt
&icon_ids
)
112 #ifdef wxHAS_FILESYSTEM_VOLUMES
115 // No logical drives; return "\"
116 paths
.Add(wxT("\\"));
117 names
.Add(wxT("\\"));
118 icon_ids
.Add(wxFileIconsTable::computer
);
119 #elif defined(__WIN32__) && wxUSE_FSVOLUME
120 // TODO: this code (using wxFSVolumeBase) should be used for all platforms
121 // but unfortunately wxFSVolumeBase is not implemented everywhere
122 const wxArrayString as
= wxFSVolumeBase::GetVolumes();
124 for (size_t i
= 0; i
< as
.GetCount(); i
++)
126 wxString path
= as
[i
];
127 wxFSVolume
vol(path
);
129 switch (vol
.GetKind())
131 case wxFS_VOL_FLOPPY
:
132 if ( (path
== wxT("a:\\")) || (path
== wxT("b:\\")) )
133 imageId
= wxFileIconsTable::floppy
;
135 imageId
= wxFileIconsTable::removeable
;
137 case wxFS_VOL_DVDROM
:
139 imageId
= wxFileIconsTable::cdrom
;
141 case wxFS_VOL_NETWORK
:
142 if (path
[0] == wxT('\\'))
143 continue; // skip "\\computer\folder"
144 imageId
= wxFileIconsTable::drive
;
149 imageId
= wxFileIconsTable::drive
;
153 names
.Add(vol
.GetDisplayName());
154 icon_ids
.Add(imageId
);
156 #elif defined(__OS2__)
158 ULONG ulDriveNum
= 0;
159 ULONG ulDriveMap
= 0;
160 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
166 if (ulDriveMap
& ( 1 << i
))
168 const wxString path
= wxFileName::GetVolumeString(
169 'A' + i
, wxPATH_GET_SEPARATOR
);
170 const wxString name
= wxFileName::GetVolumeString(
171 'A' + i
, wxPATH_NO_SEPARATOR
);
173 // Note: If _filesys is unsupported by some compilers,
174 // we can always replace it by DosQueryFSAttach
175 char filesysname
[20];
177 ULONG cbBuffer
= sizeof(filesysname
);
178 PFSQBUFFER2 pfsqBuffer
= (PFSQBUFFER2
)filesysname
;
179 APIRET rc
= ::DosQueryFSAttach(name
.fn_str(),0,FSAIL_QUERYNAME
,pfsqBuffer
,&cbBuffer
);
182 filesysname
[0] = '\0';
185 _filesys(name
.fn_str(), filesysname
, sizeof(filesysname
));
187 /* FAT, LAN, HPFS, CDFS, NFS */
189 if (path
== wxT("A:\\") || path
== wxT("B:\\"))
190 imageId
= wxFileIconsTable::floppy
;
191 else if (!strcmp(filesysname
, "CDFS"))
192 imageId
= wxFileIconsTable::cdrom
;
193 else if (!strcmp(filesysname
, "LAN") ||
194 !strcmp(filesysname
, "NFS"))
195 imageId
= wxFileIconsTable::drive
;
197 imageId
= wxFileIconsTable::drive
;
200 icon_ids
.Add(imageId
);
205 #else // !__WIN32__, !__OS2__
206 /* If we can switch to the drive, it exists. */
207 for ( char drive
= 'A'; drive
<= 'Z'; drive
++ )
210 path
= wxFileName::GetVolumeString(drive
, wxPATH_GET_SEPARATOR
);
212 if (wxIsDriveAvailable(path
))
215 names
.Add(wxFileName::GetVolumeString(drive
, wxPATH_NO_SEPARATOR
));
216 icon_ids
.Add(drive
<= 2 ? wxFileIconsTable::floppy
217 : wxFileIconsTable::drive
);
220 #endif // __WIN32__/!__WIN32__
222 #elif defined(__WXMAC__) && wxOSX_USE_COCOA_OR_CARBON
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__) || defined(__WXPALMOS__)
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 //-----------------------------------------------------------------------------
440 BEGIN_EVENT_TABLE(wxGenericDirCtrl
, wxControl
)
441 EVT_TREE_ITEM_EXPANDING (wxID_TREECTRL
, wxGenericDirCtrl::OnExpandItem
)
442 EVT_TREE_ITEM_COLLAPSED (wxID_TREECTRL
, wxGenericDirCtrl::OnCollapseItem
)
443 EVT_TREE_BEGIN_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnBeginEditItem
)
444 EVT_TREE_END_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnEndEditItem
)
445 EVT_SIZE (wxGenericDirCtrl::OnSize
)
448 wxGenericDirCtrl::wxGenericDirCtrl(void)
453 void wxGenericDirCtrl::ExpandRoot()
455 ExpandDir(m_rootId
); // automatically expand first level
457 // Expand and select the default path
458 if (!m_defaultPath
.empty())
460 ExpandPath(m_defaultPath
);
465 // On Unix, there's only one node under the (hidden) root node. It
466 // represents the / path, so the user would always have to expand it;
467 // let's do it ourselves
468 ExpandPath( wxT("/") );
473 bool wxGenericDirCtrl::Create(wxWindow
*parent
,
479 const wxString
& filter
,
481 const wxString
& name
)
483 if (!wxControl::Create(parent
, id
, pos
, size
, style
, wxDefaultValidator
, name
))
486 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE
));
487 SetForegroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT
));
491 long treeStyle
= wxTR_HAS_BUTTONS
;
493 // On Windows CE, if you hide the root, you get a crash when
494 // attempting to access data for children of the root item.
496 treeStyle
|= wxTR_HIDE_ROOT
;
500 treeStyle
|= wxTR_NO_LINES
;
503 if (style
& wxDIRCTRL_EDIT_LABELS
)
504 treeStyle
|= wxTR_EDIT_LABELS
;
506 if (style
& wxDIRCTRL_MULTIPLE
)
507 treeStyle
|= wxTR_MULTIPLE
;
509 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
510 treeStyle
|= wxNO_BORDER
;
512 m_treeCtrl
= CreateTreeCtrl(this, wxID_TREECTRL
,
513 wxPoint(0,0), GetClientSize(), treeStyle
);
516 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
);
521 if (m_filter
.empty())
522 m_filter
= wxFileSelectorDefaultWildcardStr
;
524 SetFilterIndex(defaultFilter
);
526 if (m_filterListCtrl
)
527 m_filterListCtrl
->FillFilterList(filter
, defaultFilter
);
529 m_treeCtrl
->SetImageList(wxTheFileIconsTable
->GetSmallImageList());
531 m_showHidden
= false;
532 wxDirItemData
* rootData
= new wxDirItemData(wxEmptyString
, wxEmptyString
, true);
536 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
537 rootName
= _("Computer");
539 rootName
= _("Sections");
542 m_rootId
= m_treeCtrl
->AddRoot( rootName
, 3, -1, rootData
);
543 m_treeCtrl
->SetItemHasChildren(m_rootId
);
547 SetInitialSize(size
);
553 wxGenericDirCtrl::~wxGenericDirCtrl()
557 void wxGenericDirCtrl::Init()
559 m_showHidden
= false;
561 m_currentFilterStr
= wxEmptyString
; // Default: any file
563 m_filterListCtrl
= NULL
;
566 wxTreeCtrl
* wxGenericDirCtrl::CreateTreeCtrl(wxWindow
*parent
, wxWindowID id
, const wxPoint
& pos
, const wxSize
& size
, long treeStyle
)
568 return new wxTreeCtrl(parent
, id
, pos
, size
, treeStyle
);
571 void wxGenericDirCtrl::ShowHidden( bool show
)
573 if ( m_showHidden
== show
)
578 if ( HasFlag(wxDIRCTRL_MULTIPLE
) )
583 for ( unsigned n
= 0; n
< paths
.size(); n
++ )
585 ExpandPath(paths
[n
]);
590 wxString path
= GetPath();
597 wxGenericDirCtrl::AddSection(const wxString
& path
, const wxString
& name
, int imageId
)
599 wxDirItemData
*dir_item
= new wxDirItemData(path
,name
,true);
601 wxTreeItemId id
= AppendItem( m_rootId
, name
, imageId
, -1, dir_item
);
603 m_treeCtrl
->SetItemHasChildren(id
);
608 void wxGenericDirCtrl::SetupSections()
610 wxArrayString paths
, names
;
613 size_t n
, count
= wxGetAvailableDrives(paths
, names
, icons
);
616 wxString home
= wxGetHomeDir();
617 AddSection( home
, _("Home directory"), 1);
618 home
+= wxT("/Desktop");
619 AddSection( home
, _("Desktop"), 1);
622 for (n
= 0; n
< count
; n
++)
623 AddSection(paths
[n
], names
[n
], icons
[n
]);
626 void wxGenericDirCtrl::SetFocus()
628 // we don't need focus ourselves, give it to the tree so that the user
631 m_treeCtrl
->SetFocus();
634 void wxGenericDirCtrl::OnBeginEditItem(wxTreeEvent
&event
)
636 // don't rename the main entry "Sections"
637 if (event
.GetItem() == m_rootId
)
643 // don't rename the individual sections
644 if (m_treeCtrl
->GetItemParent( event
.GetItem() ) == m_rootId
)
651 void wxGenericDirCtrl::OnEndEditItem(wxTreeEvent
&event
)
653 if (event
.IsEditCancelled())
656 if ((event
.GetLabel().empty()) ||
657 (event
.GetLabel() == wxT(".")) ||
658 (event
.GetLabel() == wxT("..")) ||
659 (event
.GetLabel().Find(wxT('/')) != wxNOT_FOUND
) ||
660 (event
.GetLabel().Find(wxT('\\')) != wxNOT_FOUND
) ||
661 (event
.GetLabel().Find(wxT('|')) != wxNOT_FOUND
))
663 wxMessageDialog
dialog(this, _("Illegal directory name."), _("Error"), wxOK
| wxICON_ERROR
);
669 wxTreeItemId id
= event
.GetItem();
670 wxDirItemData
*data
= (wxDirItemData
*)m_treeCtrl
->GetItemData( id
);
673 wxString
new_name( wxPathOnly( data
->m_path
) );
674 new_name
+= wxString(wxFILE_SEP_PATH
);
675 new_name
+= event
.GetLabel();
679 if (wxFileExists(new_name
))
681 wxMessageDialog
dialog(this, _("File name exists already."), _("Error"), wxOK
| wxICON_ERROR
);
686 if (wxRenameFile(data
->m_path
,new_name
))
688 data
->SetNewDirName( new_name
);
692 wxMessageDialog
dialog(this, _("Operation not permitted."), _("Error"), wxOK
| wxICON_ERROR
);
698 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent
&event
)
700 wxTreeItemId parentId
= event
.GetItem();
702 // VS: this is needed because the event handler is called from wxTreeCtrl
703 // ctor when wxTR_HIDE_ROOT was specified
705 if (!m_rootId
.IsOk())
706 m_rootId
= m_treeCtrl
->GetRootItem();
711 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent
&event
)
713 CollapseDir(event
.GetItem());
716 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId
)
720 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
721 if (!data
->m_isExpanded
)
724 data
->m_isExpanded
= false;
726 m_treeCtrl
->Freeze();
727 if (parentId
!= m_treeCtrl
->GetRootItem())
728 m_treeCtrl
->CollapseAndReset(parentId
);
729 m_treeCtrl
->DeleteChildren(parentId
);
733 void wxGenericDirCtrl::PopulateNode(wxTreeItemId parentId
)
735 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
737 if (data
->m_isExpanded
)
740 data
->m_isExpanded
= true;
742 if (parentId
== m_treeCtrl
->GetRootItem())
750 wxString search
,path
,filename
;
752 wxString
dirName(data
->m_path
);
754 #if (defined(__WINDOWS__) && !defined(__WXWINCE__)) || defined(__DOS__) || defined(__OS2__)
755 // Check if this is a root directory and if so,
756 // whether the drive is avaiable.
757 if (!wxIsDriveAvailable(dirName
))
759 data
->m_isExpanded
= false;
760 //wxMessageBox(wxT("Sorry, this drive is not available."));
765 // This may take a longish time. Go to busy cursor
768 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
769 if (dirName
.Last() == ':')
770 dirName
+= wxString(wxFILE_SEP_PATH
);
774 wxArrayString filenames
;
777 wxString eachFilename
;
784 int style
= wxDIR_DIRS
;
785 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
786 if (d
.GetFirst(& eachFilename
, wxEmptyString
, style
))
790 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
792 dirs
.Add(eachFilename
);
795 while (d
.GetNext(&eachFilename
));
798 dirs
.Sort(wxDirCtrlStringCompareFunction
);
800 // Now do the filenames -- but only if we're allowed to
801 if (!HasFlag(wxDIRCTRL_DIR_ONLY
))
807 int style
= wxDIR_FILES
;
808 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
809 // Process each filter (ex: "JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg")
810 wxStringTokenizer strTok
;
812 strTok
.SetString(m_currentFilterStr
,wxT(";"));
813 while(strTok
.HasMoreTokens())
815 curFilter
= strTok
.GetNextToken();
816 if (d
.GetFirst(& eachFilename
, curFilter
, style
))
820 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
822 filenames
.Add(eachFilename
);
825 while (d
.GetNext(& eachFilename
));
829 filenames
.Sort(wxDirCtrlStringCompareFunction
);
832 // Now we really know whether we have any children so tell the tree control
834 m_treeCtrl
->SetItemHasChildren(parentId
, !dirs
.empty() || !filenames
.empty());
836 // Add the sorted dirs
838 for (i
= 0; i
< dirs
.GetCount(); i
++)
840 eachFilename
= dirs
[i
];
842 if (!wxEndsWithPathSeparator(path
))
843 path
+= wxString(wxFILE_SEP_PATH
);
844 path
+= eachFilename
;
846 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,true);
847 wxTreeItemId id
= AppendItem( parentId
, eachFilename
,
848 wxFileIconsTable::folder
, -1, dir_item
);
849 m_treeCtrl
->SetItemImage( id
, wxFileIconsTable::folder_open
,
850 wxTreeItemIcon_Expanded
);
852 // assume that it does have children by default as it can take a long
853 // time to really check for this (think remote drives...)
855 // and if we're wrong, we'll correct the icon later if
856 // the user really tries to open this item
857 m_treeCtrl
->SetItemHasChildren(id
);
860 // Add the sorted filenames
861 if (!HasFlag(wxDIRCTRL_DIR_ONLY
))
863 for (i
= 0; i
< filenames
.GetCount(); i
++)
865 eachFilename
= filenames
[i
];
867 if (!wxEndsWithPathSeparator(path
))
868 path
+= wxString(wxFILE_SEP_PATH
);
869 path
+= eachFilename
;
870 //path = dirName + wxString(wxT("/")) + eachFilename;
871 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,false);
872 int image_id
= wxFileIconsTable::file
;
873 if (eachFilename
.Find(wxT('.')) != wxNOT_FOUND
)
874 image_id
= wxTheFileIconsTable
->GetIconID(eachFilename
.AfterLast(wxT('.')));
875 (void) AppendItem( parentId
, eachFilename
, image_id
, -1, dir_item
);
880 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId
)
882 // ExpandDir() will not actually expand the tree node, just populate it
883 PopulateNode(parentId
);
886 void wxGenericDirCtrl::ReCreateTree()
888 CollapseDir(m_treeCtrl
->GetRootItem());
892 void wxGenericDirCtrl::CollapseTree()
894 wxTreeItemIdValue cookie
;
895 wxTreeItemId child
= m_treeCtrl
->GetFirstChild(m_rootId
, cookie
);
899 child
= m_treeCtrl
->GetNextChild(m_rootId
, cookie
);
903 // Find the child that matches the first part of 'path'.
904 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
905 // then the child for /usr is returned.
906 wxTreeItemId
wxGenericDirCtrl::FindChild(wxTreeItemId parentId
, const wxString
& path
, bool& done
)
908 wxString
path2(path
);
910 // Make sure all separators are as per the current platform
911 path2
.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH
));
912 path2
.Replace(wxT("/"), wxString(wxFILE_SEP_PATH
));
914 // Append a separator to foil bogus substring matching
915 path2
+= wxString(wxFILE_SEP_PATH
);
917 // In MSW or PM, case is not significant
918 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
922 wxTreeItemIdValue cookie
;
923 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
924 while (childId
.IsOk())
926 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
928 if (data
&& !data
->m_path
.empty())
930 wxString
childPath(data
->m_path
);
931 if (!wxEndsWithPathSeparator(childPath
))
932 childPath
+= wxString(wxFILE_SEP_PATH
);
934 // In MSW and PM, case is not significant
935 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
936 childPath
.MakeLower();
939 if (childPath
.length() <= path2
.length())
941 wxString path3
= path2
.Mid(0, childPath
.length());
942 if (childPath
== path3
)
944 if (path3
.length() == path2
.length())
953 childId
= m_treeCtrl
->GetNextChild(parentId
, cookie
);
955 wxTreeItemId invalid
;
959 // Try to expand as much of the given path as possible,
960 // and select the given tree item.
961 bool wxGenericDirCtrl::ExpandPath(const wxString
& path
)
964 wxTreeItemId id
= FindChild(m_rootId
, path
, done
);
965 wxTreeItemId lastId
= id
; // The last non-zero id
966 while (id
.IsOk() && !done
)
970 id
= FindChild(id
, path
, done
);
977 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(lastId
);
980 m_treeCtrl
->Expand(lastId
);
982 if (HasFlag(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 data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
992 if (data
&& data
->m_path
!= wxEmptyString
&& !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
);
1017 bool wxGenericDirCtrl::CollapsePath(const wxString
& path
)
1020 wxTreeItemId id
= FindChild(m_rootId
, path
, done
);
1021 wxTreeItemId lastId
= id
; // The last non-zero id
1023 while ( id
.IsOk() && !done
)
1027 id
= FindChild(id
, path
, done
);
1033 if ( !lastId
.IsOk() )
1036 m_treeCtrl
->SelectItem(lastId
);
1037 m_treeCtrl
->EnsureVisible(lastId
);
1043 wxString
wxGenericDirCtrl::GetPath() const
1045 // Allow calling GetPath() in multiple selection from OnSelFilter
1046 if (m_treeCtrl
->HasFlag(wxTR_MULTIPLE
))
1048 wxArrayTreeItemIds items
;
1049 m_treeCtrl
->GetSelections(items
);
1050 if (items
.size() > 0)
1052 // return first string only
1053 wxTreeItemId id
= items
[0];
1054 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1055 return data
->m_path
;
1058 return wxEmptyString
;
1061 wxTreeItemId id
= m_treeCtrl
->GetSelection();
1064 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1065 return data
->m_path
;
1068 return wxEmptyString
;
1071 void wxGenericDirCtrl::GetPaths(wxArrayString
& paths
) const
1075 wxArrayTreeItemIds items
;
1076 m_treeCtrl
->GetSelections(items
);
1077 for ( unsigned n
= 0; n
< items
.size(); n
++ )
1079 wxTreeItemId id
= items
[n
];
1080 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1081 paths
.Add(data
->m_path
);
1085 wxString
wxGenericDirCtrl::GetFilePath() const
1087 wxTreeItemId id
= m_treeCtrl
->GetSelection();
1090 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1092 return wxEmptyString
;
1094 return data
->m_path
;
1097 return wxEmptyString
;
1100 void wxGenericDirCtrl::GetFilePaths(wxArrayString
& paths
) const
1104 wxArrayTreeItemIds items
;
1105 m_treeCtrl
->GetSelections(items
);
1106 for ( unsigned n
= 0; n
< items
.size(); n
++ )
1108 wxTreeItemId id
= items
[n
];
1109 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1110 if ( !data
->m_isDir
)
1111 paths
.Add(data
->m_path
);
1115 void wxGenericDirCtrl::SetPath(const wxString
& path
)
1117 m_defaultPath
= path
;
1122 void wxGenericDirCtrl::SelectPath(const wxString
& path
, bool select
)
1125 wxTreeItemId id
= FindChild(m_rootId
, path
, done
);
1126 wxTreeItemId lastId
= id
; // The last non-zero id
1127 while ( id
.IsOk() && !done
)
1129 id
= FindChild(id
, path
, done
);
1133 if ( !lastId
.IsOk() )
1138 m_treeCtrl
->SelectItem(id
, select
);
1142 void wxGenericDirCtrl::SelectPaths(const wxArrayString
& paths
)
1144 if ( HasFlag(wxDIRCTRL_MULTIPLE
) )
1147 for ( unsigned n
= 0; n
< paths
.size(); n
++ )
1149 SelectPath(paths
[n
]);
1154 void wxGenericDirCtrl::UnselectAll()
1156 m_treeCtrl
->UnselectAll();
1161 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId id
, int dirFlags
, wxArrayString
& filenames
)
1163 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1165 // This may take a longish time. Go to busy cursor
1170 wxString search
,path
,filename
;
1172 wxString
dirName(data
->m_path
);
1174 #if defined(__WXMSW__) || defined(__OS2__)
1175 if (dirName
.Last() == ':')
1176 dirName
+= wxString(wxFILE_SEP_PATH
);
1180 wxString eachFilename
;
1187 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, dirFlags
))
1191 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
1193 filenames
.Add(eachFilename
);
1196 while (d
.GetNext(& eachFilename
)) ;
1202 void wxGenericDirCtrl::SetFilterIndex(int n
)
1204 m_currentFilter
= n
;
1207 if (ExtractWildcard(m_filter
, n
, f
, d
))
1208 m_currentFilterStr
= f
;
1211 m_currentFilterStr
= wxT("*");
1213 m_currentFilterStr
= wxT("*.*");
1217 void wxGenericDirCtrl::SetFilter(const wxString
& filter
)
1221 if (!filter
.empty() && !m_filterListCtrl
)
1222 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
);
1223 else if (filter
.empty() && m_filterListCtrl
)
1225 m_filterListCtrl
->Destroy();
1226 m_filterListCtrl
= NULL
;
1230 if (ExtractWildcard(m_filter
, m_currentFilter
, f
, d
))
1231 m_currentFilterStr
= f
;
1234 m_currentFilterStr
= wxT("*");
1236 m_currentFilterStr
= wxT("*.*");
1238 // current filter index is meaningless after filter change, set it to zero
1240 if (m_filterListCtrl
)
1241 m_filterListCtrl
->FillFilterList(m_filter
, 0);
1244 // Extract description and actual filter from overall filter string
1245 bool wxGenericDirCtrl::ExtractWildcard(const wxString
& filterStr
, int n
, wxString
& filter
, wxString
& description
)
1247 wxArrayString filters
, descriptions
;
1248 int count
= wxParseCommonDialogsFilter(filterStr
, descriptions
, filters
);
1249 if (count
> 0 && n
< count
)
1251 filter
= filters
[n
];
1252 description
= descriptions
[n
];
1260 void wxGenericDirCtrl::DoResize()
1262 wxSize sz
= GetClientSize();
1263 int verticalSpacing
= 3;
1267 if (m_filterListCtrl
)
1269 filterSz
= m_filterListCtrl
->GetSize();
1270 sz
.y
-= (filterSz
.y
+ verticalSpacing
);
1272 m_treeCtrl
->SetSize(0, 0, sz
.x
, sz
.y
);
1273 if (m_filterListCtrl
)
1275 m_filterListCtrl
->SetSize(0, sz
.y
+ verticalSpacing
, sz
.x
, filterSz
.y
);
1276 // Don't know why, but this needs refreshing after a resize (wxMSW)
1277 m_filterListCtrl
->Refresh();
1283 void wxGenericDirCtrl::OnSize(wxSizeEvent
& WXUNUSED(event
))
1288 wxTreeItemId
wxGenericDirCtrl::AppendItem (const wxTreeItemId
& parent
,
1289 const wxString
& text
,
1290 int image
, int selectedImage
,
1291 wxTreeItemData
* data
)
1293 wxTreeCtrl
*treeCtrl
= GetTreeCtrl ();
1295 wxASSERT (treeCtrl
);
1299 return treeCtrl
->AppendItem (parent
, text
, image
, selectedImage
, data
);
1303 return wxTreeItemId();
1308 //-----------------------------------------------------------------------------
1309 // wxDirFilterListCtrl
1310 //-----------------------------------------------------------------------------
1312 IMPLEMENT_CLASS(wxDirFilterListCtrl
, wxChoice
)
1314 BEGIN_EVENT_TABLE(wxDirFilterListCtrl
, wxChoice
)
1315 EVT_CHOICE(wxID_ANY
, wxDirFilterListCtrl::OnSelFilter
)
1318 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl
* parent
,
1319 const wxWindowID id
,
1326 // by default our border style is determined by the style of our parent
1327 if ( !(style
& wxBORDER_MASK
) )
1329 style
|= parent
->HasFlag(wxDIRCTRL_3D_INTERNAL
) ? wxBORDER_SUNKEN
1333 return wxChoice::Create(parent
, id
, pos
, size
, 0, NULL
, style
);
1336 void wxDirFilterListCtrl::Init()
1341 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent
& WXUNUSED(event
))
1343 int sel
= GetSelection();
1345 if (m_dirCtrl
->HasFlag(wxDIRCTRL_MULTIPLE
))
1347 wxArrayString paths
;
1348 m_dirCtrl
->GetPaths(paths
);
1350 m_dirCtrl
->SetFilterIndex(sel
);
1352 // If the filter has changed, the view is out of date, so
1353 // collapse the tree.
1354 m_dirCtrl
->ReCreateTree();
1356 // Expand and select the previously selected paths
1357 for (unsigned int i
= 0; i
< paths
.GetCount(); i
++)
1359 m_dirCtrl
->ExpandPath(paths
.Item(i
));
1364 wxString currentPath
= m_dirCtrl
->GetPath();
1366 m_dirCtrl
->SetFilterIndex(sel
);
1367 m_dirCtrl
->ReCreateTree();
1369 // Try to restore the selection, or at least the directory
1370 m_dirCtrl
->ExpandPath(currentPath
);
1374 void wxDirFilterListCtrl::FillFilterList(const wxString
& filter
, int defaultFilter
)
1377 wxArrayString descriptions
, filters
;
1378 size_t n
= (size_t) wxParseCommonDialogsFilter(filter
, descriptions
, filters
);
1380 if (n
> 0 && defaultFilter
< (int) n
)
1382 for (size_t i
= 0; i
< n
; i
++)
1383 Append(descriptions
[i
]);
1384 SetSelection(defaultFilter
);
1387 #endif // wxUSE_DIRDLG
1389 #if wxUSE_DIRDLG || wxUSE_FILEDLG
1391 // ----------------------------------------------------------------------------
1392 // wxFileIconsTable icons
1393 // ----------------------------------------------------------------------------
1396 /* Computer (c) Julian Smart */
1397 static const char* const file_icons_tbl_computer_xpm
[] = {
1398 /* columns rows colors chars-per-pixel */
1462 // ----------------------------------------------------------------------------
1463 // wxFileIconsTable & friends
1464 // ----------------------------------------------------------------------------
1466 // global instance of a wxFileIconsTable
1467 wxFileIconsTable
* wxTheFileIconsTable
= NULL
;
1469 // A module to allow icons table cleanup
1471 class wxFileIconsTableModule
: public wxModule
1473 DECLARE_DYNAMIC_CLASS(wxFileIconsTableModule
)
1475 wxFileIconsTableModule() {}
1476 bool OnInit() { wxTheFileIconsTable
= new wxFileIconsTable
; return true; }
1479 wxDELETE(wxTheFileIconsTable
);
1483 IMPLEMENT_DYNAMIC_CLASS(wxFileIconsTableModule
, wxModule
)
1485 class wxFileIconEntry
: public wxObject
1488 wxFileIconEntry(int i
) { id
= i
; }
1493 wxFileIconsTable::wxFileIconsTable()
1496 m_smallImageList
= NULL
;
1499 wxFileIconsTable::~wxFileIconsTable()
1503 WX_CLEAR_HASH_TABLE(*m_HashTable
);
1506 if (m_smallImageList
) delete m_smallImageList
;
1509 // delayed initialization - wait until first use (wxArtProv not created yet)
1510 void wxFileIconsTable::Create()
1512 wxCHECK_RET(!m_smallImageList
&& !m_HashTable
, wxT("creating icons twice"));
1513 m_HashTable
= new wxHashTable(wxKEY_STRING
);
1514 m_smallImageList
= new wxImageList(16, 16);
1517 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER
,
1521 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER_OPEN
,
1526 // GTK24 uses this icon in the file open dialog
1527 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_HARDDISK
,
1531 m_smallImageList
->Add(wxIcon(file_icons_tbl_computer_xpm
));
1534 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_HARDDISK
,
1538 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_CDROM
,
1542 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FLOPPY
,
1546 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_REMOVABLE
,
1550 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE
,
1554 if (GetIconID(wxEmptyString
, wxT("application/x-executable")) == file
)
1556 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE
,
1559 delete m_HashTable
->Get(wxT("exe"));
1560 m_HashTable
->Delete(wxT("exe"));
1561 m_HashTable
->Put(wxT("exe"), new wxFileIconEntry(executable
));
1563 /* else put into list by GetIconID
1564 (KDE defines application/x-executable for *.exe and has nice icon)
1568 wxImageList
*wxFileIconsTable::GetSmallImageList()
1570 if (!m_smallImageList
)
1573 return m_smallImageList
;
1576 #if wxUSE_MIMETYPE && wxUSE_IMAGE && (!defined(__WXMSW__) || wxUSE_WXDIB)
1577 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
1578 // one icon and we won't resize it
1580 static wxBitmap
CreateAntialiasedBitmap(const wxImage
& img
)
1582 const unsigned int size
= 16;
1584 wxImage
smallimg (size
, size
);
1585 unsigned char *p1
, *p2
, *ps
;
1586 unsigned char mr
= img
.GetMaskRed(),
1587 mg
= img
.GetMaskGreen(),
1588 mb
= img
.GetMaskBlue();
1591 unsigned sr
, sg
, sb
, smask
;
1593 p1
= img
.GetData(), p2
= img
.GetData() + 3 * size
*2, ps
= smallimg
.GetData();
1594 smallimg
.SetMaskColour(mr
, mr
, mr
);
1596 for (y
= 0; y
< size
; y
++)
1598 for (x
= 0; x
< size
; x
++)
1600 sr
= sg
= sb
= smask
= 0;
1601 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1602 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1605 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1606 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1609 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1610 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1613 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1614 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1619 ps
[0] = ps
[1] = ps
[2] = mr
;
1622 ps
[0] = (unsigned char)(sr
>> 2);
1623 ps
[1] = (unsigned char)(sg
>> 2);
1624 ps
[2] = (unsigned char)(sb
>> 2);
1628 p1
+= size
*2 * 3, p2
+= size
*2 * 3;
1631 return wxBitmap(smallimg
);
1634 // This function is currently not unused anymore
1636 // finds empty borders and return non-empty area of image:
1637 static wxImage
CutEmptyBorders(const wxImage
& img
)
1639 unsigned char mr
= img
.GetMaskRed(),
1640 mg
= img
.GetMaskGreen(),
1641 mb
= img
.GetMaskBlue();
1642 unsigned char *dt
= img
.GetData(), *dttmp
;
1643 unsigned w
= img
.GetWidth(), h
= img
.GetHeight();
1645 unsigned top
, bottom
, left
, right
, i
;
1648 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
1649 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = false; break;}
1651 for (empt
= true, top
= 0; empt
&& top
< h
; top
++)
1654 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1657 for (empt
= true, bottom
= h
-1; empt
&& bottom
> top
; bottom
--)
1659 MK_DTTMP(0, bottom
);
1660 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1663 for (empt
= true, left
= 0; empt
&& left
< w
; left
++)
1666 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1669 for (empt
= true, right
= w
-1; empt
&& right
> left
; right
--)
1672 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1675 top
--, left
--, bottom
++, right
++;
1677 return img
.GetSubImage(wxRect(left
, top
, right
- left
+ 1, bottom
- top
+ 1));
1681 #endif // wxUSE_MIMETYPE
1683 int wxFileIconsTable::GetIconID(const wxString
& extension
, const wxString
& mime
)
1685 if (!m_smallImageList
)
1689 if (!extension
.empty())
1691 wxFileIconEntry
*entry
= (wxFileIconEntry
*) m_HashTable
->Get(extension
);
1692 if (entry
) return (entry
-> id
);
1695 wxFileType
*ft
= (mime
.empty()) ?
1696 wxTheMimeTypesManager
-> GetFileTypeFromExtension(extension
) :
1697 wxTheMimeTypesManager
-> GetFileTypeFromMimeType(mime
);
1699 wxIconLocation iconLoc
;
1704 if ( ft
&& ft
->GetIcon(&iconLoc
) )
1706 ic
= wxIcon( iconLoc
);
1715 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1720 bmp
.CopyFromIcon(ic
);
1725 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1729 const unsigned int size
= 16;
1731 int id
= m_smallImageList
->GetImageCount();
1732 if ((bmp
.GetWidth() == (int) size
) && (bmp
.GetHeight() == (int) size
))
1734 m_smallImageList
->Add(bmp
);
1736 #if wxUSE_IMAGE && (!defined(__WXMSW__) || wxUSE_WXDIB)
1739 wxImage img
= bmp
.ConvertToImage();
1741 if ((img
.GetWidth() != size
*2) || (img
.GetHeight() != size
*2))
1742 // m_smallImageList->Add(CreateAntialiasedBitmap(CutEmptyBorders(img).Rescale(size*2, size*2)));
1743 m_smallImageList
->Add(CreateAntialiasedBitmap(img
.Rescale(size
*2, size
*2)));
1745 m_smallImageList
->Add(CreateAntialiasedBitmap(img
));
1747 #endif // wxUSE_IMAGE
1749 m_HashTable
->Put(extension
, new wxFileIconEntry(id
));
1752 #else // !wxUSE_MIMETYPE
1755 if (extension
== wxT("exe"))
1759 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
1762 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG