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 // ----------------------------------------------------------------------------
107 // ----------------------------------------------------------------------------
109 wxDEFINE_EVENT( wxEVT_COMMAND_DIRCTRL_CHANGED
, wxTreeEvent
);
111 // ----------------------------------------------------------------------------
112 // wxGetAvailableDrives, for WINDOWS, DOS, OS2, MAC, UNIX (returns "/")
113 // ----------------------------------------------------------------------------
115 size_t wxGetAvailableDrives(wxArrayString
&paths
, wxArrayString
&names
, wxArrayInt
&icon_ids
)
117 #ifdef wxHAS_FILESYSTEM_VOLUMES
120 // No logical drives; return "\"
121 paths
.Add(wxT("\\"));
122 names
.Add(wxT("\\"));
123 icon_ids
.Add(wxFileIconsTable::computer
);
124 #elif defined(__WIN32__) && wxUSE_FSVOLUME
125 // TODO: this code (using wxFSVolumeBase) should be used for all platforms
126 // but unfortunately wxFSVolumeBase is not implemented everywhere
127 const wxArrayString as
= wxFSVolumeBase::GetVolumes();
129 for (size_t i
= 0; i
< as
.GetCount(); i
++)
131 wxString path
= as
[i
];
132 wxFSVolume
vol(path
);
134 switch (vol
.GetKind())
136 case wxFS_VOL_FLOPPY
:
137 if ( (path
== wxT("a:\\")) || (path
== wxT("b:\\")) )
138 imageId
= wxFileIconsTable::floppy
;
140 imageId
= wxFileIconsTable::removeable
;
142 case wxFS_VOL_DVDROM
:
144 imageId
= wxFileIconsTable::cdrom
;
146 case wxFS_VOL_NETWORK
:
147 if (path
[0] == wxT('\\'))
148 continue; // skip "\\computer\folder"
149 imageId
= wxFileIconsTable::drive
;
154 imageId
= wxFileIconsTable::drive
;
158 names
.Add(vol
.GetDisplayName());
159 icon_ids
.Add(imageId
);
161 #elif defined(__OS2__)
163 ULONG ulDriveNum
= 0;
164 ULONG ulDriveMap
= 0;
165 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
171 if (ulDriveMap
& ( 1 << i
))
173 const wxString path
= wxFileName::GetVolumeString(
174 'A' + i
, wxPATH_GET_SEPARATOR
);
175 const wxString name
= wxFileName::GetVolumeString(
176 'A' + i
, wxPATH_NO_SEPARATOR
);
178 // Note: If _filesys is unsupported by some compilers,
179 // we can always replace it by DosQueryFSAttach
180 char filesysname
[20];
182 ULONG cbBuffer
= sizeof(filesysname
);
183 PFSQBUFFER2 pfsqBuffer
= (PFSQBUFFER2
)filesysname
;
184 APIRET rc
= ::DosQueryFSAttach(name
.fn_str(),0,FSAIL_QUERYNAME
,pfsqBuffer
,&cbBuffer
);
187 filesysname
[0] = '\0';
190 _filesys(name
.fn_str(), filesysname
, sizeof(filesysname
));
192 /* FAT, LAN, HPFS, CDFS, NFS */
194 if (path
== wxT("A:\\") || path
== wxT("B:\\"))
195 imageId
= wxFileIconsTable::floppy
;
196 else if (!strcmp(filesysname
, "CDFS"))
197 imageId
= wxFileIconsTable::cdrom
;
198 else if (!strcmp(filesysname
, "LAN") ||
199 !strcmp(filesysname
, "NFS"))
200 imageId
= wxFileIconsTable::drive
;
202 imageId
= wxFileIconsTable::drive
;
205 icon_ids
.Add(imageId
);
210 #else // !__WIN32__, !__OS2__
211 /* If we can switch to the drive, it exists. */
212 for ( char drive
= 'A'; drive
<= 'Z'; drive
++ )
215 path
= wxFileName::GetVolumeString(drive
, wxPATH_GET_SEPARATOR
);
217 if (wxIsDriveAvailable(path
))
220 names
.Add(wxFileName::GetVolumeString(drive
, wxPATH_NO_SEPARATOR
));
221 icon_ids
.Add(drive
<= 2 ? wxFileIconsTable::floppy
222 : wxFileIconsTable::drive
);
225 #endif // __WIN32__/!__WIN32__
227 #elif defined(__WXMAC__) && wxOSX_USE_COCOA_OR_CARBON
229 ItemCount volumeIndex
= 1;
232 while( noErr
== err
)
234 HFSUniStr255 volumeName
;
236 FSVolumeInfo volumeInfo
;
237 err
= FSGetVolumeInfo(0, volumeIndex
, NULL
, kFSVolInfoFlags
, &volumeInfo
, &volumeName
, &fsRef
);
240 wxString path
= wxMacFSRefToPath( &fsRef
) ;
241 wxString name
= wxMacHFSUniStrToString( &volumeName
) ;
243 if ( (volumeInfo
.flags
& kFSVolFlagSoftwareLockedMask
) || (volumeInfo
.flags
& kFSVolFlagHardwareLockedMask
) )
245 icon_ids
.Add(wxFileIconsTable::cdrom
);
249 icon_ids
.Add(wxFileIconsTable::drive
);
251 // todo other removable
259 #elif defined(__UNIX__)
262 icon_ids
.Add(wxFileIconsTable::computer
);
264 #error "Unsupported platform in wxGenericDirCtrl!"
266 wxASSERT_MSG( (paths
.GetCount() == names
.GetCount()), wxT("The number of paths and their human readable names should be equal in number."));
267 wxASSERT_MSG( (paths
.GetCount() == icon_ids
.GetCount()), wxT("Wrong number of icons for available drives."));
268 return paths
.GetCount();
271 // ----------------------------------------------------------------------------
272 // wxIsDriveAvailable
273 // ----------------------------------------------------------------------------
277 bool wxIsDriveAvailable(const wxString
& dirName
)
279 // FIXME: this method leads to hang up under Watcom for some reason
281 wxUnusedVar(dirName
);
283 if ( dirName
.length() == 3 && dirName
[1u] == wxT(':') )
285 wxString
dirNameLower(dirName
.Lower());
286 // VS: always return true for removable media, since Win95 doesn't
287 // like it when MS-DOS app accesses empty floppy drive
288 return (dirNameLower
[0u] == wxT('a') ||
289 dirNameLower
[0u] == wxT('b') ||
290 wxDirExists(dirNameLower
));
297 #elif defined(__WINDOWS__) || defined(__OS2__)
299 int setdrive(int WXUNUSED_IN_WINCE(drive
))
303 #elif defined(__GNUWIN32__) && \
304 (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
305 return _chdrive(drive
);
309 if (drive
< 1 || drive
> 31)
311 newdrive
[0] = (wxChar
)(wxT('A') + drive
- 1);
312 newdrive
[1] = wxT(':');
314 newdrive
[2] = wxT('\\');
315 newdrive
[3] = wxT('\0');
317 newdrive
[2] = wxT('\0');
319 #if defined(__WINDOWS__)
320 if (::SetCurrentDirectory(newdrive
))
322 // VA doesn't know what LPSTR is and has its own set
323 if (!DosSetCurrentDir((PSZ
)newdrive
))
331 bool wxIsDriveAvailable(const wxString
& WXUNUSED_IN_WINCE(dirName
))
337 UINT errorMode
= SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOOPENFILEERRORBOX
);
341 // Check if this is a root directory and if so,
342 // whether the drive is available.
343 if (dirName
.length() == 3 && dirName
[(size_t)1] == wxT(':'))
345 wxString
dirNameLower(dirName
.Lower());
346 #if defined(__GNUWIN32__) && !(defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
347 success
= wxDirExists(dirNameLower
);
350 // Avoid changing to drive since no media may be inserted.
351 if (dirNameLower
[(size_t)0] == 'a' || dirNameLower
[(size_t)0] == 'b')
354 int currentDrive
= _getdrive();
355 int thisDrive
= (int) (dirNameLower
[(size_t)0] - 'a' + 1) ;
356 int err
= setdrive( thisDrive
) ;
357 setdrive( currentDrive
);
366 (void) SetErrorMode(errorMode
);
372 #endif // __WINDOWS__ || __OS2__
374 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG
380 // Function which is called by quick sort. We want to override the default wxArrayString behaviour,
381 // and sort regardless of case.
382 static int wxCMPFUNC_CONV
wxDirCtrlStringCompareFunction(const wxString
& strFirst
, const wxString
& strSecond
)
384 return strFirst
.CmpNoCase(strSecond
);
387 //-----------------------------------------------------------------------------
389 //-----------------------------------------------------------------------------
391 wxDirItemData::wxDirItemData(const wxString
& path
, const wxString
& name
,
396 /* Insert logic to detect hidden files here
397 * In UnixLand we just check whether the first char is a dot
398 * For FileNameFromPath read LastDirNameInThisPath ;-) */
399 // m_isHidden = (bool)(wxFileNameFromPath(*m_path)[0] == '.');
401 m_isExpanded
= false;
405 void wxDirItemData::SetNewDirName(const wxString
& path
)
408 m_name
= wxFileNameFromPath(path
);
411 bool wxDirItemData::HasSubDirs() const
419 if ( !dir
.Open(m_path
) )
423 return dir
.HasSubDirs();
426 bool wxDirItemData::HasFiles(const wxString
& WXUNUSED(spec
)) const
434 if ( !dir
.Open(m_path
) )
438 return dir
.HasFiles();
441 //-----------------------------------------------------------------------------
443 //-----------------------------------------------------------------------------
445 BEGIN_EVENT_TABLE(wxGenericDirCtrl
, wxControl
)
446 EVT_TREE_ITEM_EXPANDING (wxID_TREECTRL
, wxGenericDirCtrl::OnExpandItem
)
447 EVT_TREE_ITEM_COLLAPSED (wxID_TREECTRL
, wxGenericDirCtrl::OnCollapseItem
)
448 EVT_TREE_BEGIN_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnBeginEditItem
)
449 EVT_TREE_END_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnEndEditItem
)
450 EVT_TREE_SEL_CHANGED (wxID_TREECTRL
, wxGenericDirCtrl::OnTreeSelChange
)
451 EVT_SIZE (wxGenericDirCtrl::OnSize
)
454 wxGenericDirCtrl::wxGenericDirCtrl(void)
459 void wxGenericDirCtrl::ExpandRoot()
461 ExpandDir(m_rootId
); // automatically expand first level
463 // Expand and select the default path
464 if (!m_defaultPath
.empty())
466 ExpandPath(m_defaultPath
);
471 // On Unix, there's only one node under the (hidden) root node. It
472 // represents the / path, so the user would always have to expand it;
473 // let's do it ourselves
474 ExpandPath( wxT("/") );
479 bool wxGenericDirCtrl::Create(wxWindow
*parent
,
480 const wxWindowID treeid
,
485 const wxString
& filter
,
487 const wxString
& name
)
489 if (!wxControl::Create(parent
, treeid
, pos
, size
, style
, wxDefaultValidator
, name
))
492 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE
));
493 SetForegroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT
));
497 long treeStyle
= wxTR_HAS_BUTTONS
;
499 // On Windows CE, if you hide the root, you get a crash when
500 // attempting to access data for children of the root item.
502 treeStyle
|= wxTR_HIDE_ROOT
;
506 treeStyle
|= wxTR_NO_LINES
;
509 if (style
& wxDIRCTRL_EDIT_LABELS
)
510 treeStyle
|= wxTR_EDIT_LABELS
;
512 if (style
& wxDIRCTRL_MULTIPLE
)
513 treeStyle
|= wxTR_MULTIPLE
;
515 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
516 treeStyle
|= wxNO_BORDER
;
518 m_treeCtrl
= CreateTreeCtrl(this, wxID_TREECTRL
,
519 wxPoint(0,0), GetClientSize(), treeStyle
);
521 if (!filter
.empty() && (style
& wxDIRCTRL_SHOW_FILTERS
))
522 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
);
527 if (m_filter
.empty())
528 m_filter
= wxFileSelectorDefaultWildcardStr
;
530 SetFilterIndex(defaultFilter
);
532 if (m_filterListCtrl
)
533 m_filterListCtrl
->FillFilterList(filter
, defaultFilter
);
535 m_treeCtrl
->SetImageList(wxTheFileIconsTable
->GetSmallImageList());
537 m_showHidden
= false;
538 wxDirItemData
* rootData
= new wxDirItemData(wxEmptyString
, wxEmptyString
, true);
542 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
543 rootName
= _("Computer");
545 rootName
= _("Sections");
548 m_rootId
= m_treeCtrl
->AddRoot( rootName
, 3, -1, rootData
);
549 m_treeCtrl
->SetItemHasChildren(m_rootId
);
553 SetInitialSize(size
);
559 wxGenericDirCtrl::~wxGenericDirCtrl()
563 void wxGenericDirCtrl::Init()
565 m_showHidden
= false;
567 m_currentFilterStr
= wxEmptyString
; // Default: any file
569 m_filterListCtrl
= NULL
;
572 wxTreeCtrl
* wxGenericDirCtrl::CreateTreeCtrl(wxWindow
*parent
, wxWindowID treeid
, const wxPoint
& pos
, const wxSize
& size
, long treeStyle
)
574 return new wxTreeCtrl(parent
, treeid
, pos
, size
, treeStyle
);
577 void wxGenericDirCtrl::ShowHidden( bool show
)
579 if ( m_showHidden
== show
)
584 if ( HasFlag(wxDIRCTRL_MULTIPLE
) )
589 for ( unsigned n
= 0; n
< paths
.size(); n
++ )
591 ExpandPath(paths
[n
]);
596 wxString path
= GetPath();
603 wxGenericDirCtrl::AddSection(const wxString
& path
, const wxString
& name
, int imageId
)
605 wxDirItemData
*dir_item
= new wxDirItemData(path
,name
,true);
607 wxTreeItemId treeid
= AppendItem( m_rootId
, name
, imageId
, -1, dir_item
);
609 m_treeCtrl
->SetItemHasChildren(treeid
);
614 void wxGenericDirCtrl::SetupSections()
616 wxArrayString paths
, names
;
619 size_t n
, count
= wxGetAvailableDrives(paths
, names
, icons
);
622 wxString home
= wxGetHomeDir();
623 AddSection( home
, _("Home directory"), 1);
624 home
+= wxT("/Desktop");
625 AddSection( home
, _("Desktop"), 1);
628 for (n
= 0; n
< count
; n
++)
629 AddSection(paths
[n
], names
[n
], icons
[n
]);
632 void wxGenericDirCtrl::SetFocus()
634 // we don't need focus ourselves, give it to the tree so that the user
637 m_treeCtrl
->SetFocus();
640 void wxGenericDirCtrl::OnBeginEditItem(wxTreeEvent
&event
)
642 // don't rename the main entry "Sections"
643 if (event
.GetItem() == m_rootId
)
649 // don't rename the individual sections
650 if (m_treeCtrl
->GetItemParent( event
.GetItem() ) == m_rootId
)
657 void wxGenericDirCtrl::OnEndEditItem(wxTreeEvent
&event
)
659 if (event
.IsEditCancelled())
662 if ((event
.GetLabel().empty()) ||
663 (event
.GetLabel() == wxT(".")) ||
664 (event
.GetLabel() == wxT("..")) ||
665 (event
.GetLabel().Find(wxT('/')) != wxNOT_FOUND
) ||
666 (event
.GetLabel().Find(wxT('\\')) != wxNOT_FOUND
) ||
667 (event
.GetLabel().Find(wxT('|')) != wxNOT_FOUND
))
669 wxMessageDialog
dialog(this, _("Illegal directory name."), _("Error"), wxOK
| wxICON_ERROR
);
675 wxTreeItemId treeid
= event
.GetItem();
676 wxDirItemData
*data
= GetItemData( treeid
);
679 wxString
new_name( wxPathOnly( data
->m_path
) );
680 new_name
+= wxString(wxFILE_SEP_PATH
);
681 new_name
+= event
.GetLabel();
685 if (wxFileExists(new_name
))
687 wxMessageDialog
dialog(this, _("File name exists already."), _("Error"), wxOK
| wxICON_ERROR
);
692 if (wxRenameFile(data
->m_path
,new_name
))
694 data
->SetNewDirName( new_name
);
698 wxMessageDialog
dialog(this, _("Operation not permitted."), _("Error"), wxOK
| wxICON_ERROR
);
704 void wxGenericDirCtrl::OnTreeSelChange(wxTreeEvent
&event
)
706 wxTreeEvent
changedEvent(wxEVT_COMMAND_DIRCTRL_CHANGED
, GetId());
708 changedEvent
.SetEventObject(this);
709 changedEvent
.SetItem(event
.GetItem());
710 changedEvent
.SetClientObject(m_treeCtrl
->GetItemData(event
.GetItem()));
712 if (GetEventHandler()->SafelyProcessEvent(changedEvent
) && !changedEvent
.IsAllowed())
722 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent
&event
)
724 wxTreeItemId parentId
= event
.GetItem();
726 // VS: this is needed because the event handler is called from wxTreeCtrl
727 // ctor when wxTR_HIDE_ROOT was specified
729 if (!m_rootId
.IsOk())
730 m_rootId
= m_treeCtrl
->GetRootItem();
735 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent
&event
)
737 CollapseDir(event
.GetItem());
740 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId
)
744 wxDirItemData
*data
= GetItemData(parentId
);
745 if (!data
->m_isExpanded
)
748 data
->m_isExpanded
= false;
750 m_treeCtrl
->Freeze();
751 if (parentId
!= m_treeCtrl
->GetRootItem())
752 m_treeCtrl
->CollapseAndReset(parentId
);
753 m_treeCtrl
->DeleteChildren(parentId
);
757 void wxGenericDirCtrl::PopulateNode(wxTreeItemId parentId
)
759 wxDirItemData
*data
= GetItemData(parentId
);
761 if (data
->m_isExpanded
)
764 data
->m_isExpanded
= true;
766 if (parentId
== m_treeCtrl
->GetRootItem())
774 wxString search
,path
,filename
;
776 wxString
dirName(data
->m_path
);
778 #if (defined(__WINDOWS__) && !defined(__WXWINCE__)) || defined(__DOS__) || defined(__OS2__)
779 // Check if this is a root directory and if so,
780 // whether the drive is avaiable.
781 if (!wxIsDriveAvailable(dirName
))
783 data
->m_isExpanded
= false;
784 //wxMessageBox(wxT("Sorry, this drive is not available."));
789 // This may take a longish time. Go to busy cursor
792 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
793 if (dirName
.Last() == ':')
794 dirName
+= wxString(wxFILE_SEP_PATH
);
798 wxArrayString filenames
;
801 wxString eachFilename
;
808 int style
= wxDIR_DIRS
;
809 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
810 if (d
.GetFirst(& eachFilename
, wxEmptyString
, style
))
814 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
816 dirs
.Add(eachFilename
);
819 while (d
.GetNext(&eachFilename
));
822 dirs
.Sort(wxDirCtrlStringCompareFunction
);
824 // Now do the filenames -- but only if we're allowed to
825 if (!HasFlag(wxDIRCTRL_DIR_ONLY
))
831 int style
= wxDIR_FILES
;
832 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
833 // Process each filter (ex: "JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg")
834 wxStringTokenizer strTok
;
836 strTok
.SetString(m_currentFilterStr
,wxT(";"));
837 while(strTok
.HasMoreTokens())
839 curFilter
= strTok
.GetNextToken();
840 if (d
.GetFirst(& eachFilename
, curFilter
, style
))
844 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
846 filenames
.Add(eachFilename
);
849 while (d
.GetNext(& eachFilename
));
853 filenames
.Sort(wxDirCtrlStringCompareFunction
);
856 // Now we really know whether we have any children so tell the tree control
858 m_treeCtrl
->SetItemHasChildren(parentId
, !dirs
.empty() || !filenames
.empty());
860 // Add the sorted dirs
862 for (i
= 0; i
< dirs
.GetCount(); i
++)
864 eachFilename
= dirs
[i
];
866 if (!wxEndsWithPathSeparator(path
))
867 path
+= wxString(wxFILE_SEP_PATH
);
868 path
+= eachFilename
;
870 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,true);
871 wxTreeItemId treeid
= AppendItem( parentId
, eachFilename
,
872 wxFileIconsTable::folder
, -1, dir_item
);
873 m_treeCtrl
->SetItemImage( treeid
, wxFileIconsTable::folder_open
,
874 wxTreeItemIcon_Expanded
);
876 // assume that it does have children by default as it can take a long
877 // time to really check for this (think remote drives...)
879 // and if we're wrong, we'll correct the icon later if
880 // the user really tries to open this item
881 m_treeCtrl
->SetItemHasChildren(treeid
);
884 // Add the sorted filenames
885 if (!HasFlag(wxDIRCTRL_DIR_ONLY
))
887 for (i
= 0; i
< filenames
.GetCount(); i
++)
889 eachFilename
= filenames
[i
];
891 if (!wxEndsWithPathSeparator(path
))
892 path
+= wxString(wxFILE_SEP_PATH
);
893 path
+= eachFilename
;
894 //path = dirName + wxString(wxT("/")) + eachFilename;
895 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,false);
896 int image_id
= wxFileIconsTable::file
;
897 if (eachFilename
.Find(wxT('.')) != wxNOT_FOUND
)
898 image_id
= wxTheFileIconsTable
->GetIconID(eachFilename
.AfterLast(wxT('.')));
899 (void) AppendItem( parentId
, eachFilename
, image_id
, -1, dir_item
);
904 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId
)
906 // ExpandDir() will not actually expand the tree node, just populate it
907 PopulateNode(parentId
);
910 void wxGenericDirCtrl::ReCreateTree()
912 CollapseDir(m_treeCtrl
->GetRootItem());
916 void wxGenericDirCtrl::CollapseTree()
918 wxTreeItemIdValue cookie
;
919 wxTreeItemId child
= m_treeCtrl
->GetFirstChild(m_rootId
, cookie
);
923 child
= m_treeCtrl
->GetNextChild(m_rootId
, cookie
);
927 // Find the child that matches the first part of 'path'.
928 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
929 // then the child for /usr is returned.
930 wxTreeItemId
wxGenericDirCtrl::FindChild(wxTreeItemId parentId
, const wxString
& path
, bool& done
)
932 wxString
path2(path
);
934 // Make sure all separators are as per the current platform
935 path2
.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH
));
936 path2
.Replace(wxT("/"), wxString(wxFILE_SEP_PATH
));
938 // Append a separator to foil bogus substring matching
939 path2
+= wxString(wxFILE_SEP_PATH
);
941 // In MSW or PM, case is not significant
942 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
946 wxTreeItemIdValue cookie
;
947 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
948 while (childId
.IsOk())
950 wxDirItemData
* data
= GetItemData(childId
);
952 if (data
&& !data
->m_path
.empty())
954 wxString
childPath(data
->m_path
);
955 if (!wxEndsWithPathSeparator(childPath
))
956 childPath
+= wxString(wxFILE_SEP_PATH
);
958 // In MSW and PM, case is not significant
959 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
960 childPath
.MakeLower();
963 if (childPath
.length() <= path2
.length())
965 wxString path3
= path2
.Mid(0, childPath
.length());
966 if (childPath
== path3
)
968 if (path3
.length() == path2
.length())
977 childId
= m_treeCtrl
->GetNextChild(parentId
, cookie
);
979 wxTreeItemId invalid
;
983 // Try to expand as much of the given path as possible,
984 // and select the given tree item.
985 bool wxGenericDirCtrl::ExpandPath(const wxString
& path
)
988 wxTreeItemId treeid
= FindChild(m_rootId
, path
, done
);
989 wxTreeItemId lastId
= treeid
; // The last non-zero treeid
990 while (treeid
.IsOk() && !done
)
994 treeid
= FindChild(treeid
, path
, done
);
1001 wxDirItemData
*data
= GetItemData(lastId
);
1004 m_treeCtrl
->Expand(lastId
);
1006 if (HasFlag(wxDIRCTRL_SELECT_FIRST
) && data
->m_isDir
)
1008 // Find the first file in this directory
1009 wxTreeItemIdValue cookie
;
1010 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(lastId
, cookie
);
1011 bool selectedChild
= false;
1012 while (childId
.IsOk())
1014 data
= GetItemData(childId
);
1016 if (data
&& data
->m_path
!= wxEmptyString
&& !data
->m_isDir
)
1018 m_treeCtrl
->SelectItem(childId
);
1019 m_treeCtrl
->EnsureVisible(childId
);
1020 selectedChild
= true;
1023 childId
= m_treeCtrl
->GetNextChild(lastId
, cookie
);
1027 m_treeCtrl
->SelectItem(lastId
);
1028 m_treeCtrl
->EnsureVisible(lastId
);
1033 m_treeCtrl
->SelectItem(lastId
);
1034 m_treeCtrl
->EnsureVisible(lastId
);
1041 bool wxGenericDirCtrl::CollapsePath(const wxString
& path
)
1044 wxTreeItemId treeid
= FindChild(m_rootId
, path
, done
);
1045 wxTreeItemId lastId
= treeid
; // The last non-zero treeid
1047 while ( treeid
.IsOk() && !done
)
1049 CollapseDir(treeid
);
1051 treeid
= FindChild(treeid
, path
, done
);
1053 if ( treeid
.IsOk() )
1057 if ( !lastId
.IsOk() )
1060 m_treeCtrl
->SelectItem(lastId
);
1061 m_treeCtrl
->EnsureVisible(lastId
);
1066 wxDirItemData
* wxGenericDirCtrl::GetItemData(wxTreeItemId itemId
)
1068 return static_cast<wxDirItemData
*>(m_treeCtrl
->GetItemData(itemId
));
1071 wxString
wxGenericDirCtrl::GetPath(wxTreeItemId itemId
) const
1073 const wxDirItemData
*
1074 data
= static_cast<wxDirItemData
*>(m_treeCtrl
->GetItemData(itemId
));
1076 return data
->m_path
;
1079 wxString
wxGenericDirCtrl::GetPath() const
1081 // Allow calling GetPath() in multiple selection from OnSelFilter
1082 if (m_treeCtrl
->HasFlag(wxTR_MULTIPLE
))
1084 wxArrayTreeItemIds items
;
1085 m_treeCtrl
->GetSelections(items
);
1086 if (items
.size() > 0)
1088 // return first string only
1089 wxTreeItemId treeid
= items
[0];
1090 return GetPath(treeid
);
1093 return wxEmptyString
;
1096 wxTreeItemId treeid
= m_treeCtrl
->GetSelection();
1099 return GetPath(treeid
);
1102 return wxEmptyString
;
1105 void wxGenericDirCtrl::GetPaths(wxArrayString
& paths
) const
1109 wxArrayTreeItemIds items
;
1110 m_treeCtrl
->GetSelections(items
);
1111 for ( unsigned n
= 0; n
< items
.size(); n
++ )
1113 wxTreeItemId treeid
= items
[n
];
1114 paths
.push_back(GetPath(treeid
));
1118 wxString
wxGenericDirCtrl::GetFilePath() const
1120 wxTreeItemId treeid
= m_treeCtrl
->GetSelection();
1123 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(treeid
);
1125 return wxEmptyString
;
1127 return data
->m_path
;
1130 return wxEmptyString
;
1133 void wxGenericDirCtrl::GetFilePaths(wxArrayString
& paths
) const
1137 wxArrayTreeItemIds items
;
1138 m_treeCtrl
->GetSelections(items
);
1139 for ( unsigned n
= 0; n
< items
.size(); n
++ )
1141 wxTreeItemId treeid
= items
[n
];
1142 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(treeid
);
1143 if ( !data
->m_isDir
)
1144 paths
.Add(data
->m_path
);
1148 void wxGenericDirCtrl::SetPath(const wxString
& path
)
1150 m_defaultPath
= path
;
1155 void wxGenericDirCtrl::SelectPath(const wxString
& path
, bool select
)
1158 wxTreeItemId treeid
= FindChild(m_rootId
, path
, done
);
1159 wxTreeItemId lastId
= treeid
; // The last non-zero treeid
1160 while ( treeid
.IsOk() && !done
)
1162 treeid
= FindChild(treeid
, path
, done
);
1163 if ( treeid
.IsOk() )
1166 if ( !lastId
.IsOk() )
1171 m_treeCtrl
->SelectItem(treeid
, select
);
1175 void wxGenericDirCtrl::SelectPaths(const wxArrayString
& paths
)
1177 if ( HasFlag(wxDIRCTRL_MULTIPLE
) )
1180 for ( unsigned n
= 0; n
< paths
.size(); n
++ )
1182 SelectPath(paths
[n
]);
1187 void wxGenericDirCtrl::UnselectAll()
1189 m_treeCtrl
->UnselectAll();
1194 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId treeid
, int dirFlags
, wxArrayString
& filenames
)
1196 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(treeid
);
1198 // This may take a longish time. Go to busy cursor
1203 wxString search
,path
,filename
;
1205 wxString
dirName(data
->m_path
);
1207 #if defined(__WINDOWS__) || defined(__OS2__)
1208 if (dirName
.Last() == ':')
1209 dirName
+= wxString(wxFILE_SEP_PATH
);
1213 wxString eachFilename
;
1220 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, dirFlags
))
1224 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
1226 filenames
.Add(eachFilename
);
1229 while (d
.GetNext(& eachFilename
)) ;
1235 void wxGenericDirCtrl::SetFilterIndex(int n
)
1237 m_currentFilter
= n
;
1240 if (ExtractWildcard(m_filter
, n
, f
, d
))
1241 m_currentFilterStr
= f
;
1244 m_currentFilterStr
= wxT("*");
1246 m_currentFilterStr
= wxT("*.*");
1250 void wxGenericDirCtrl::SetFilter(const wxString
& filter
)
1254 if (!filter
.empty() && !m_filterListCtrl
&& HasFlag(wxDIRCTRL_SHOW_FILTERS
))
1255 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
);
1256 else if (filter
.empty() && m_filterListCtrl
)
1258 m_filterListCtrl
->Destroy();
1259 m_filterListCtrl
= NULL
;
1263 if (ExtractWildcard(m_filter
, m_currentFilter
, f
, d
))
1264 m_currentFilterStr
= f
;
1267 m_currentFilterStr
= wxT("*");
1269 m_currentFilterStr
= wxT("*.*");
1271 // current filter index is meaningless after filter change, set it to zero
1273 if (m_filterListCtrl
)
1274 m_filterListCtrl
->FillFilterList(m_filter
, 0);
1277 // Extract description and actual filter from overall filter string
1278 bool wxGenericDirCtrl::ExtractWildcard(const wxString
& filterStr
, int n
, wxString
& filter
, wxString
& description
)
1280 wxArrayString filters
, descriptions
;
1281 int count
= wxParseCommonDialogsFilter(filterStr
, descriptions
, filters
);
1282 if (count
> 0 && n
< count
)
1284 filter
= filters
[n
];
1285 description
= descriptions
[n
];
1293 void wxGenericDirCtrl::DoResize()
1295 wxSize sz
= GetClientSize();
1296 int verticalSpacing
= 3;
1300 if (m_filterListCtrl
)
1302 filterSz
= m_filterListCtrl
->GetSize();
1303 sz
.y
-= (filterSz
.y
+ verticalSpacing
);
1305 m_treeCtrl
->SetSize(0, 0, sz
.x
, sz
.y
);
1306 if (m_filterListCtrl
)
1308 m_filterListCtrl
->SetSize(0, sz
.y
+ verticalSpacing
, sz
.x
, filterSz
.y
);
1309 // Don't know why, but this needs refreshing after a resize (wxMSW)
1310 m_filterListCtrl
->Refresh();
1316 void wxGenericDirCtrl::OnSize(wxSizeEvent
& WXUNUSED(event
))
1321 wxTreeItemId
wxGenericDirCtrl::AppendItem (const wxTreeItemId
& parent
,
1322 const wxString
& text
,
1323 int image
, int selectedImage
,
1324 wxTreeItemData
* data
)
1326 wxTreeCtrl
*treeCtrl
= GetTreeCtrl ();
1328 wxASSERT (treeCtrl
);
1332 return treeCtrl
->AppendItem (parent
, text
, image
, selectedImage
, data
);
1336 return wxTreeItemId();
1341 //-----------------------------------------------------------------------------
1342 // wxDirFilterListCtrl
1343 //-----------------------------------------------------------------------------
1345 IMPLEMENT_CLASS(wxDirFilterListCtrl
, wxChoice
)
1347 BEGIN_EVENT_TABLE(wxDirFilterListCtrl
, wxChoice
)
1348 EVT_CHOICE(wxID_ANY
, wxDirFilterListCtrl::OnSelFilter
)
1351 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl
* parent
,
1352 const wxWindowID treeid
,
1359 // by default our border style is determined by the style of our parent
1360 if ( !(style
& wxBORDER_MASK
) )
1362 style
|= parent
->HasFlag(wxDIRCTRL_3D_INTERNAL
) ? wxBORDER_SUNKEN
1366 return wxChoice::Create(parent
, treeid
, pos
, size
, 0, NULL
, style
);
1369 void wxDirFilterListCtrl::Init()
1374 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent
& WXUNUSED(event
))
1376 int sel
= GetSelection();
1378 if (m_dirCtrl
->HasFlag(wxDIRCTRL_MULTIPLE
))
1380 wxArrayString paths
;
1381 m_dirCtrl
->GetPaths(paths
);
1383 m_dirCtrl
->SetFilterIndex(sel
);
1385 // If the filter has changed, the view is out of date, so
1386 // collapse the tree.
1387 m_dirCtrl
->ReCreateTree();
1389 // Expand and select the previously selected paths
1390 for (unsigned int i
= 0; i
< paths
.GetCount(); i
++)
1392 m_dirCtrl
->ExpandPath(paths
.Item(i
));
1397 wxString currentPath
= m_dirCtrl
->GetPath();
1399 m_dirCtrl
->SetFilterIndex(sel
);
1400 m_dirCtrl
->ReCreateTree();
1402 // Try to restore the selection, or at least the directory
1403 m_dirCtrl
->ExpandPath(currentPath
);
1407 void wxDirFilterListCtrl::FillFilterList(const wxString
& filter
, int defaultFilter
)
1410 wxArrayString descriptions
, filters
;
1411 size_t n
= (size_t) wxParseCommonDialogsFilter(filter
, descriptions
, filters
);
1413 if (n
> 0 && defaultFilter
< (int) n
)
1415 for (size_t i
= 0; i
< n
; i
++)
1416 Append(descriptions
[i
]);
1417 SetSelection(defaultFilter
);
1420 #endif // wxUSE_DIRDLG
1422 #if wxUSE_DIRDLG || wxUSE_FILEDLG
1424 // ----------------------------------------------------------------------------
1425 // wxFileIconsTable icons
1426 // ----------------------------------------------------------------------------
1429 /* Computer (c) Julian Smart */
1430 static const char* const file_icons_tbl_computer_xpm
[] = {
1431 /* columns rows colors chars-per-pixel */
1495 // ----------------------------------------------------------------------------
1496 // wxFileIconsTable & friends
1497 // ----------------------------------------------------------------------------
1499 // global instance of a wxFileIconsTable
1500 wxFileIconsTable
* wxTheFileIconsTable
= NULL
;
1502 // A module to allow icons table cleanup
1504 class wxFileIconsTableModule
: public wxModule
1506 DECLARE_DYNAMIC_CLASS(wxFileIconsTableModule
)
1508 wxFileIconsTableModule() {}
1509 bool OnInit() { wxTheFileIconsTable
= new wxFileIconsTable
; return true; }
1512 wxDELETE(wxTheFileIconsTable
);
1516 IMPLEMENT_DYNAMIC_CLASS(wxFileIconsTableModule
, wxModule
)
1518 class wxFileIconEntry
: public wxObject
1521 wxFileIconEntry(int i
) { iconid
= i
; }
1526 wxFileIconsTable::wxFileIconsTable()
1529 m_smallImageList
= NULL
;
1532 wxFileIconsTable::~wxFileIconsTable()
1536 WX_CLEAR_HASH_TABLE(*m_HashTable
);
1539 if (m_smallImageList
) delete m_smallImageList
;
1542 // delayed initialization - wait until first use (wxArtProv not created yet)
1543 void wxFileIconsTable::Create()
1545 wxCHECK_RET(!m_smallImageList
&& !m_HashTable
, wxT("creating icons twice"));
1546 m_HashTable
= new wxHashTable(wxKEY_STRING
);
1547 m_smallImageList
= new wxImageList(16, 16);
1550 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER
,
1554 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER_OPEN
,
1559 // GTK24 uses this icon in the file open dialog
1560 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_HARDDISK
,
1564 m_smallImageList
->Add(wxIcon(file_icons_tbl_computer_xpm
));
1567 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_HARDDISK
,
1571 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_CDROM
,
1575 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FLOPPY
,
1579 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_REMOVABLE
,
1583 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE
,
1587 if (GetIconID(wxEmptyString
, wxT("application/x-executable")) == file
)
1589 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE
,
1592 delete m_HashTable
->Get(wxT("exe"));
1593 m_HashTable
->Delete(wxT("exe"));
1594 m_HashTable
->Put(wxT("exe"), new wxFileIconEntry(executable
));
1596 /* else put into list by GetIconID
1597 (KDE defines application/x-executable for *.exe and has nice icon)
1601 wxImageList
*wxFileIconsTable::GetSmallImageList()
1603 if (!m_smallImageList
)
1606 return m_smallImageList
;
1609 #if wxUSE_MIMETYPE && wxUSE_IMAGE && (!defined(__WINDOWS__) || wxUSE_WXDIB)
1610 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
1611 // one icon and we won't resize it
1613 static wxBitmap
CreateAntialiasedBitmap(const wxImage
& img
)
1615 const unsigned int size
= 16;
1617 wxImage
smallimg (size
, size
);
1618 unsigned char *p1
, *p2
, *ps
;
1619 unsigned char mr
= img
.GetMaskRed(),
1620 mg
= img
.GetMaskGreen(),
1621 mb
= img
.GetMaskBlue();
1624 unsigned sr
, sg
, sb
, smask
;
1626 p1
= img
.GetData(), p2
= img
.GetData() + 3 * size
*2, ps
= smallimg
.GetData();
1627 smallimg
.SetMaskColour(mr
, mr
, mr
);
1629 for (y
= 0; y
< size
; y
++)
1631 for (x
= 0; x
< size
; x
++)
1633 sr
= sg
= sb
= smask
= 0;
1634 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1635 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1638 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1639 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1642 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1643 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1646 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1647 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1652 ps
[0] = ps
[1] = ps
[2] = mr
;
1655 ps
[0] = (unsigned char)(sr
>> 2);
1656 ps
[1] = (unsigned char)(sg
>> 2);
1657 ps
[2] = (unsigned char)(sb
>> 2);
1661 p1
+= size
*2 * 3, p2
+= size
*2 * 3;
1664 return wxBitmap(smallimg
);
1667 // This function is currently not unused anymore
1669 // finds empty borders and return non-empty area of image:
1670 static wxImage
CutEmptyBorders(const wxImage
& img
)
1672 unsigned char mr
= img
.GetMaskRed(),
1673 mg
= img
.GetMaskGreen(),
1674 mb
= img
.GetMaskBlue();
1675 unsigned char *dt
= img
.GetData(), *dttmp
;
1676 unsigned w
= img
.GetWidth(), h
= img
.GetHeight();
1678 unsigned top
, bottom
, left
, right
, i
;
1681 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
1682 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = false; break;}
1684 for (empt
= true, top
= 0; empt
&& top
< h
; top
++)
1687 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1690 for (empt
= true, bottom
= h
-1; empt
&& bottom
> top
; bottom
--)
1692 MK_DTTMP(0, bottom
);
1693 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1696 for (empt
= true, left
= 0; empt
&& left
< w
; left
++)
1699 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1702 for (empt
= true, right
= w
-1; empt
&& right
> left
; right
--)
1705 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1708 top
--, left
--, bottom
++, right
++;
1710 return img
.GetSubImage(wxRect(left
, top
, right
- left
+ 1, bottom
- top
+ 1));
1714 #endif // wxUSE_MIMETYPE
1716 int wxFileIconsTable::GetIconID(const wxString
& extension
, const wxString
& mime
)
1718 if (!m_smallImageList
)
1722 if (!extension
.empty())
1724 wxFileIconEntry
*entry
= (wxFileIconEntry
*) m_HashTable
->Get(extension
);
1725 if (entry
) return (entry
-> iconid
);
1728 wxFileType
*ft
= (mime
.empty()) ?
1729 wxTheMimeTypesManager
-> GetFileTypeFromExtension(extension
) :
1730 wxTheMimeTypesManager
-> GetFileTypeFromMimeType(mime
);
1732 wxIconLocation iconLoc
;
1737 if ( ft
&& ft
->GetIcon(&iconLoc
) )
1739 ic
= wxIcon( iconLoc
);
1748 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1753 bmp
.CopyFromIcon(ic
);
1758 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1762 const unsigned int size
= 16;
1764 int treeid
= m_smallImageList
->GetImageCount();
1765 if ((bmp
.GetWidth() == (int) size
) && (bmp
.GetHeight() == (int) size
))
1767 m_smallImageList
->Add(bmp
);
1769 #if wxUSE_IMAGE && (!defined(__WINDOWS__) || wxUSE_WXDIB)
1772 wxImage img
= bmp
.ConvertToImage();
1774 if ((img
.GetWidth() != size
*2) || (img
.GetHeight() != size
*2))
1775 // m_smallImageList->Add(CreateAntialiasedBitmap(CutEmptyBorders(img).Rescale(size*2, size*2)));
1776 m_smallImageList
->Add(CreateAntialiasedBitmap(img
.Rescale(size
*2, size
*2)));
1778 m_smallImageList
->Add(CreateAntialiasedBitmap(img
));
1780 #endif // wxUSE_IMAGE
1782 m_HashTable
->Put(extension
, new wxFileIconEntry(treeid
));
1785 #else // !wxUSE_MIMETYPE
1788 if (extension
== wxT("exe"))
1792 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
1795 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG