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
);
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
.SetItem(event
.GetItem());
709 changedEvent
.SetClientObject(m_treeCtrl
->GetItemData(event
.GetItem()));
711 GetEventHandler()->SafelyProcessEvent(changedEvent
);
715 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent
&event
)
717 wxTreeItemId parentId
= event
.GetItem();
719 // VS: this is needed because the event handler is called from wxTreeCtrl
720 // ctor when wxTR_HIDE_ROOT was specified
722 if (!m_rootId
.IsOk())
723 m_rootId
= m_treeCtrl
->GetRootItem();
728 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent
&event
)
730 CollapseDir(event
.GetItem());
733 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId
)
737 wxDirItemData
*data
= GetItemData(parentId
);
738 if (!data
->m_isExpanded
)
741 data
->m_isExpanded
= false;
743 m_treeCtrl
->Freeze();
744 if (parentId
!= m_treeCtrl
->GetRootItem())
745 m_treeCtrl
->CollapseAndReset(parentId
);
746 m_treeCtrl
->DeleteChildren(parentId
);
750 void wxGenericDirCtrl::PopulateNode(wxTreeItemId parentId
)
752 wxDirItemData
*data
= GetItemData(parentId
);
754 if (data
->m_isExpanded
)
757 data
->m_isExpanded
= true;
759 if (parentId
== m_treeCtrl
->GetRootItem())
767 wxString search
,path
,filename
;
769 wxString
dirName(data
->m_path
);
771 #if (defined(__WINDOWS__) && !defined(__WXWINCE__)) || defined(__DOS__) || defined(__OS2__)
772 // Check if this is a root directory and if so,
773 // whether the drive is avaiable.
774 if (!wxIsDriveAvailable(dirName
))
776 data
->m_isExpanded
= false;
777 //wxMessageBox(wxT("Sorry, this drive is not available."));
782 // This may take a longish time. Go to busy cursor
785 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
786 if (dirName
.Last() == ':')
787 dirName
+= wxString(wxFILE_SEP_PATH
);
791 wxArrayString filenames
;
794 wxString eachFilename
;
801 int style
= wxDIR_DIRS
;
802 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
803 if (d
.GetFirst(& eachFilename
, wxEmptyString
, style
))
807 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
809 dirs
.Add(eachFilename
);
812 while (d
.GetNext(&eachFilename
));
815 dirs
.Sort(wxDirCtrlStringCompareFunction
);
817 // Now do the filenames -- but only if we're allowed to
818 if (!HasFlag(wxDIRCTRL_DIR_ONLY
))
824 int style
= wxDIR_FILES
;
825 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
826 // Process each filter (ex: "JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg")
827 wxStringTokenizer strTok
;
829 strTok
.SetString(m_currentFilterStr
,wxT(";"));
830 while(strTok
.HasMoreTokens())
832 curFilter
= strTok
.GetNextToken();
833 if (d
.GetFirst(& eachFilename
, curFilter
, style
))
837 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
839 filenames
.Add(eachFilename
);
842 while (d
.GetNext(& eachFilename
));
846 filenames
.Sort(wxDirCtrlStringCompareFunction
);
849 // Now we really know whether we have any children so tell the tree control
851 m_treeCtrl
->SetItemHasChildren(parentId
, !dirs
.empty() || !filenames
.empty());
853 // Add the sorted dirs
855 for (i
= 0; i
< dirs
.GetCount(); i
++)
857 eachFilename
= dirs
[i
];
859 if (!wxEndsWithPathSeparator(path
))
860 path
+= wxString(wxFILE_SEP_PATH
);
861 path
+= eachFilename
;
863 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,true);
864 wxTreeItemId treeid
= AppendItem( parentId
, eachFilename
,
865 wxFileIconsTable::folder
, -1, dir_item
);
866 m_treeCtrl
->SetItemImage( treeid
, wxFileIconsTable::folder_open
,
867 wxTreeItemIcon_Expanded
);
869 // assume that it does have children by default as it can take a long
870 // time to really check for this (think remote drives...)
872 // and if we're wrong, we'll correct the icon later if
873 // the user really tries to open this item
874 m_treeCtrl
->SetItemHasChildren(treeid
);
877 // Add the sorted filenames
878 if (!HasFlag(wxDIRCTRL_DIR_ONLY
))
880 for (i
= 0; i
< filenames
.GetCount(); i
++)
882 eachFilename
= filenames
[i
];
884 if (!wxEndsWithPathSeparator(path
))
885 path
+= wxString(wxFILE_SEP_PATH
);
886 path
+= eachFilename
;
887 //path = dirName + wxString(wxT("/")) + eachFilename;
888 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,false);
889 int image_id
= wxFileIconsTable::file
;
890 if (eachFilename
.Find(wxT('.')) != wxNOT_FOUND
)
891 image_id
= wxTheFileIconsTable
->GetIconID(eachFilename
.AfterLast(wxT('.')));
892 (void) AppendItem( parentId
, eachFilename
, image_id
, -1, dir_item
);
897 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId
)
899 // ExpandDir() will not actually expand the tree node, just populate it
900 PopulateNode(parentId
);
903 void wxGenericDirCtrl::ReCreateTree()
905 CollapseDir(m_treeCtrl
->GetRootItem());
909 void wxGenericDirCtrl::CollapseTree()
911 wxTreeItemIdValue cookie
;
912 wxTreeItemId child
= m_treeCtrl
->GetFirstChild(m_rootId
, cookie
);
916 child
= m_treeCtrl
->GetNextChild(m_rootId
, cookie
);
920 // Find the child that matches the first part of 'path'.
921 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
922 // then the child for /usr is returned.
923 wxTreeItemId
wxGenericDirCtrl::FindChild(wxTreeItemId parentId
, const wxString
& path
, bool& done
)
925 wxString
path2(path
);
927 // Make sure all separators are as per the current platform
928 path2
.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH
));
929 path2
.Replace(wxT("/"), wxString(wxFILE_SEP_PATH
));
931 // Append a separator to foil bogus substring matching
932 path2
+= wxString(wxFILE_SEP_PATH
);
934 // In MSW or PM, case is not significant
935 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
939 wxTreeItemIdValue cookie
;
940 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
941 while (childId
.IsOk())
943 wxDirItemData
* data
= GetItemData(childId
);
945 if (data
&& !data
->m_path
.empty())
947 wxString
childPath(data
->m_path
);
948 if (!wxEndsWithPathSeparator(childPath
))
949 childPath
+= wxString(wxFILE_SEP_PATH
);
951 // In MSW and PM, case is not significant
952 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
953 childPath
.MakeLower();
956 if (childPath
.length() <= path2
.length())
958 wxString path3
= path2
.Mid(0, childPath
.length());
959 if (childPath
== path3
)
961 if (path3
.length() == path2
.length())
970 childId
= m_treeCtrl
->GetNextChild(parentId
, cookie
);
972 wxTreeItemId invalid
;
976 // Try to expand as much of the given path as possible,
977 // and select the given tree item.
978 bool wxGenericDirCtrl::ExpandPath(const wxString
& path
)
981 wxTreeItemId treeid
= FindChild(m_rootId
, path
, done
);
982 wxTreeItemId lastId
= treeid
; // The last non-zero treeid
983 while (treeid
.IsOk() && !done
)
987 treeid
= FindChild(treeid
, path
, done
);
994 wxDirItemData
*data
= GetItemData(lastId
);
997 m_treeCtrl
->Expand(lastId
);
999 if (HasFlag(wxDIRCTRL_SELECT_FIRST
) && data
->m_isDir
)
1001 // Find the first file in this directory
1002 wxTreeItemIdValue cookie
;
1003 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(lastId
, cookie
);
1004 bool selectedChild
= false;
1005 while (childId
.IsOk())
1007 data
= GetItemData(childId
);
1009 if (data
&& data
->m_path
!= wxEmptyString
&& !data
->m_isDir
)
1011 m_treeCtrl
->SelectItem(childId
);
1012 m_treeCtrl
->EnsureVisible(childId
);
1013 selectedChild
= true;
1016 childId
= m_treeCtrl
->GetNextChild(lastId
, cookie
);
1020 m_treeCtrl
->SelectItem(lastId
);
1021 m_treeCtrl
->EnsureVisible(lastId
);
1026 m_treeCtrl
->SelectItem(lastId
);
1027 m_treeCtrl
->EnsureVisible(lastId
);
1034 bool wxGenericDirCtrl::CollapsePath(const wxString
& path
)
1037 wxTreeItemId treeid
= FindChild(m_rootId
, path
, done
);
1038 wxTreeItemId lastId
= treeid
; // The last non-zero treeid
1040 while ( treeid
.IsOk() && !done
)
1042 CollapseDir(treeid
);
1044 treeid
= FindChild(treeid
, path
, done
);
1046 if ( treeid
.IsOk() )
1050 if ( !lastId
.IsOk() )
1053 m_treeCtrl
->SelectItem(lastId
);
1054 m_treeCtrl
->EnsureVisible(lastId
);
1059 wxDirItemData
* wxGenericDirCtrl::GetItemData(wxTreeItemId itemId
)
1061 return static_cast<wxDirItemData
*>(m_treeCtrl
->GetItemData(itemId
));
1064 wxString
wxGenericDirCtrl::GetPath(wxTreeItemId itemId
) const
1066 const wxDirItemData
*
1067 data
= static_cast<wxDirItemData
*>(m_treeCtrl
->GetItemData(itemId
));
1069 return data
->m_path
;
1072 wxString
wxGenericDirCtrl::GetPath() const
1074 // Allow calling GetPath() in multiple selection from OnSelFilter
1075 if (m_treeCtrl
->HasFlag(wxTR_MULTIPLE
))
1077 wxArrayTreeItemIds items
;
1078 m_treeCtrl
->GetSelections(items
);
1079 if (items
.size() > 0)
1081 // return first string only
1082 wxTreeItemId treeid
= items
[0];
1083 return GetPath(treeid
);
1086 return wxEmptyString
;
1089 wxTreeItemId treeid
= m_treeCtrl
->GetSelection();
1092 return GetPath(treeid
);
1095 return wxEmptyString
;
1098 void wxGenericDirCtrl::GetPaths(wxArrayString
& paths
) const
1102 wxArrayTreeItemIds items
;
1103 m_treeCtrl
->GetSelections(items
);
1104 for ( unsigned n
= 0; n
< items
.size(); n
++ )
1106 wxTreeItemId treeid
= items
[n
];
1107 paths
.push_back(GetPath(treeid
));
1111 wxString
wxGenericDirCtrl::GetFilePath() const
1113 wxTreeItemId treeid
= m_treeCtrl
->GetSelection();
1116 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(treeid
);
1118 return wxEmptyString
;
1120 return data
->m_path
;
1123 return wxEmptyString
;
1126 void wxGenericDirCtrl::GetFilePaths(wxArrayString
& paths
) const
1130 wxArrayTreeItemIds items
;
1131 m_treeCtrl
->GetSelections(items
);
1132 for ( unsigned n
= 0; n
< items
.size(); n
++ )
1134 wxTreeItemId treeid
= items
[n
];
1135 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(treeid
);
1136 if ( !data
->m_isDir
)
1137 paths
.Add(data
->m_path
);
1141 void wxGenericDirCtrl::SetPath(const wxString
& path
)
1143 m_defaultPath
= path
;
1148 void wxGenericDirCtrl::SelectPath(const wxString
& path
, bool select
)
1151 wxTreeItemId treeid
= FindChild(m_rootId
, path
, done
);
1152 wxTreeItemId lastId
= treeid
; // The last non-zero treeid
1153 while ( treeid
.IsOk() && !done
)
1155 treeid
= FindChild(treeid
, path
, done
);
1156 if ( treeid
.IsOk() )
1159 if ( !lastId
.IsOk() )
1164 m_treeCtrl
->SelectItem(treeid
, select
);
1168 void wxGenericDirCtrl::SelectPaths(const wxArrayString
& paths
)
1170 if ( HasFlag(wxDIRCTRL_MULTIPLE
) )
1173 for ( unsigned n
= 0; n
< paths
.size(); n
++ )
1175 SelectPath(paths
[n
]);
1180 void wxGenericDirCtrl::UnselectAll()
1182 m_treeCtrl
->UnselectAll();
1187 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId treeid
, int dirFlags
, wxArrayString
& filenames
)
1189 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(treeid
);
1191 // This may take a longish time. Go to busy cursor
1196 wxString search
,path
,filename
;
1198 wxString
dirName(data
->m_path
);
1200 #if defined(__WINDOWS__) || defined(__OS2__)
1201 if (dirName
.Last() == ':')
1202 dirName
+= wxString(wxFILE_SEP_PATH
);
1206 wxString eachFilename
;
1213 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, dirFlags
))
1217 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
1219 filenames
.Add(eachFilename
);
1222 while (d
.GetNext(& eachFilename
)) ;
1228 void wxGenericDirCtrl::SetFilterIndex(int n
)
1230 m_currentFilter
= n
;
1233 if (ExtractWildcard(m_filter
, n
, f
, d
))
1234 m_currentFilterStr
= f
;
1237 m_currentFilterStr
= wxT("*");
1239 m_currentFilterStr
= wxT("*.*");
1243 void wxGenericDirCtrl::SetFilter(const wxString
& filter
)
1247 if (!filter
.empty() && !m_filterListCtrl
)
1248 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
);
1249 else if (filter
.empty() && m_filterListCtrl
)
1251 m_filterListCtrl
->Destroy();
1252 m_filterListCtrl
= NULL
;
1256 if (ExtractWildcard(m_filter
, m_currentFilter
, f
, d
))
1257 m_currentFilterStr
= f
;
1260 m_currentFilterStr
= wxT("*");
1262 m_currentFilterStr
= wxT("*.*");
1264 // current filter index is meaningless after filter change, set it to zero
1266 if (m_filterListCtrl
)
1267 m_filterListCtrl
->FillFilterList(m_filter
, 0);
1270 // Extract description and actual filter from overall filter string
1271 bool wxGenericDirCtrl::ExtractWildcard(const wxString
& filterStr
, int n
, wxString
& filter
, wxString
& description
)
1273 wxArrayString filters
, descriptions
;
1274 int count
= wxParseCommonDialogsFilter(filterStr
, descriptions
, filters
);
1275 if (count
> 0 && n
< count
)
1277 filter
= filters
[n
];
1278 description
= descriptions
[n
];
1286 void wxGenericDirCtrl::DoResize()
1288 wxSize sz
= GetClientSize();
1289 int verticalSpacing
= 3;
1293 if (m_filterListCtrl
)
1295 filterSz
= m_filterListCtrl
->GetSize();
1296 sz
.y
-= (filterSz
.y
+ verticalSpacing
);
1298 m_treeCtrl
->SetSize(0, 0, sz
.x
, sz
.y
);
1299 if (m_filterListCtrl
)
1301 m_filterListCtrl
->SetSize(0, sz
.y
+ verticalSpacing
, sz
.x
, filterSz
.y
);
1302 // Don't know why, but this needs refreshing after a resize (wxMSW)
1303 m_filterListCtrl
->Refresh();
1309 void wxGenericDirCtrl::OnSize(wxSizeEvent
& WXUNUSED(event
))
1314 wxTreeItemId
wxGenericDirCtrl::AppendItem (const wxTreeItemId
& parent
,
1315 const wxString
& text
,
1316 int image
, int selectedImage
,
1317 wxTreeItemData
* data
)
1319 wxTreeCtrl
*treeCtrl
= GetTreeCtrl ();
1321 wxASSERT (treeCtrl
);
1325 return treeCtrl
->AppendItem (parent
, text
, image
, selectedImage
, data
);
1329 return wxTreeItemId();
1334 //-----------------------------------------------------------------------------
1335 // wxDirFilterListCtrl
1336 //-----------------------------------------------------------------------------
1338 IMPLEMENT_CLASS(wxDirFilterListCtrl
, wxChoice
)
1340 BEGIN_EVENT_TABLE(wxDirFilterListCtrl
, wxChoice
)
1341 EVT_CHOICE(wxID_ANY
, wxDirFilterListCtrl::OnSelFilter
)
1344 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl
* parent
,
1345 const wxWindowID treeid
,
1352 // by default our border style is determined by the style of our parent
1353 if ( !(style
& wxBORDER_MASK
) )
1355 style
|= parent
->HasFlag(wxDIRCTRL_3D_INTERNAL
) ? wxBORDER_SUNKEN
1359 return wxChoice::Create(parent
, treeid
, pos
, size
, 0, NULL
, style
);
1362 void wxDirFilterListCtrl::Init()
1367 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent
& WXUNUSED(event
))
1369 int sel
= GetSelection();
1371 if (m_dirCtrl
->HasFlag(wxDIRCTRL_MULTIPLE
))
1373 wxArrayString paths
;
1374 m_dirCtrl
->GetPaths(paths
);
1376 m_dirCtrl
->SetFilterIndex(sel
);
1378 // If the filter has changed, the view is out of date, so
1379 // collapse the tree.
1380 m_dirCtrl
->ReCreateTree();
1382 // Expand and select the previously selected paths
1383 for (unsigned int i
= 0; i
< paths
.GetCount(); i
++)
1385 m_dirCtrl
->ExpandPath(paths
.Item(i
));
1390 wxString currentPath
= m_dirCtrl
->GetPath();
1392 m_dirCtrl
->SetFilterIndex(sel
);
1393 m_dirCtrl
->ReCreateTree();
1395 // Try to restore the selection, or at least the directory
1396 m_dirCtrl
->ExpandPath(currentPath
);
1400 void wxDirFilterListCtrl::FillFilterList(const wxString
& filter
, int defaultFilter
)
1403 wxArrayString descriptions
, filters
;
1404 size_t n
= (size_t) wxParseCommonDialogsFilter(filter
, descriptions
, filters
);
1406 if (n
> 0 && defaultFilter
< (int) n
)
1408 for (size_t i
= 0; i
< n
; i
++)
1409 Append(descriptions
[i
]);
1410 SetSelection(defaultFilter
);
1413 #endif // wxUSE_DIRDLG
1415 #if wxUSE_DIRDLG || wxUSE_FILEDLG
1417 // ----------------------------------------------------------------------------
1418 // wxFileIconsTable icons
1419 // ----------------------------------------------------------------------------
1422 /* Computer (c) Julian Smart */
1423 static const char* const file_icons_tbl_computer_xpm
[] = {
1424 /* columns rows colors chars-per-pixel */
1488 // ----------------------------------------------------------------------------
1489 // wxFileIconsTable & friends
1490 // ----------------------------------------------------------------------------
1492 // global instance of a wxFileIconsTable
1493 wxFileIconsTable
* wxTheFileIconsTable
= NULL
;
1495 // A module to allow icons table cleanup
1497 class wxFileIconsTableModule
: public wxModule
1499 DECLARE_DYNAMIC_CLASS(wxFileIconsTableModule
)
1501 wxFileIconsTableModule() {}
1502 bool OnInit() { wxTheFileIconsTable
= new wxFileIconsTable
; return true; }
1505 wxDELETE(wxTheFileIconsTable
);
1509 IMPLEMENT_DYNAMIC_CLASS(wxFileIconsTableModule
, wxModule
)
1511 class wxFileIconEntry
: public wxObject
1514 wxFileIconEntry(int i
) { iconid
= i
; }
1519 wxFileIconsTable::wxFileIconsTable()
1522 m_smallImageList
= NULL
;
1525 wxFileIconsTable::~wxFileIconsTable()
1529 WX_CLEAR_HASH_TABLE(*m_HashTable
);
1532 if (m_smallImageList
) delete m_smallImageList
;
1535 // delayed initialization - wait until first use (wxArtProv not created yet)
1536 void wxFileIconsTable::Create()
1538 wxCHECK_RET(!m_smallImageList
&& !m_HashTable
, wxT("creating icons twice"));
1539 m_HashTable
= new wxHashTable(wxKEY_STRING
);
1540 m_smallImageList
= new wxImageList(16, 16);
1543 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER
,
1547 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER_OPEN
,
1552 // GTK24 uses this icon in the file open dialog
1553 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_HARDDISK
,
1557 m_smallImageList
->Add(wxIcon(file_icons_tbl_computer_xpm
));
1560 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_HARDDISK
,
1564 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_CDROM
,
1568 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FLOPPY
,
1572 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_REMOVABLE
,
1576 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE
,
1580 if (GetIconID(wxEmptyString
, wxT("application/x-executable")) == file
)
1582 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE
,
1585 delete m_HashTable
->Get(wxT("exe"));
1586 m_HashTable
->Delete(wxT("exe"));
1587 m_HashTable
->Put(wxT("exe"), new wxFileIconEntry(executable
));
1589 /* else put into list by GetIconID
1590 (KDE defines application/x-executable for *.exe and has nice icon)
1594 wxImageList
*wxFileIconsTable::GetSmallImageList()
1596 if (!m_smallImageList
)
1599 return m_smallImageList
;
1602 #if wxUSE_MIMETYPE && wxUSE_IMAGE && (!defined(__WINDOWS__) || wxUSE_WXDIB)
1603 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
1604 // one icon and we won't resize it
1606 static wxBitmap
CreateAntialiasedBitmap(const wxImage
& img
)
1608 const unsigned int size
= 16;
1610 wxImage
smallimg (size
, size
);
1611 unsigned char *p1
, *p2
, *ps
;
1612 unsigned char mr
= img
.GetMaskRed(),
1613 mg
= img
.GetMaskGreen(),
1614 mb
= img
.GetMaskBlue();
1617 unsigned sr
, sg
, sb
, smask
;
1619 p1
= img
.GetData(), p2
= img
.GetData() + 3 * size
*2, ps
= smallimg
.GetData();
1620 smallimg
.SetMaskColour(mr
, mr
, mr
);
1622 for (y
= 0; y
< size
; y
++)
1624 for (x
= 0; x
< size
; x
++)
1626 sr
= sg
= sb
= smask
= 0;
1627 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1628 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1631 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1632 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1635 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1636 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1639 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1640 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1645 ps
[0] = ps
[1] = ps
[2] = mr
;
1648 ps
[0] = (unsigned char)(sr
>> 2);
1649 ps
[1] = (unsigned char)(sg
>> 2);
1650 ps
[2] = (unsigned char)(sb
>> 2);
1654 p1
+= size
*2 * 3, p2
+= size
*2 * 3;
1657 return wxBitmap(smallimg
);
1660 // This function is currently not unused anymore
1662 // finds empty borders and return non-empty area of image:
1663 static wxImage
CutEmptyBorders(const wxImage
& img
)
1665 unsigned char mr
= img
.GetMaskRed(),
1666 mg
= img
.GetMaskGreen(),
1667 mb
= img
.GetMaskBlue();
1668 unsigned char *dt
= img
.GetData(), *dttmp
;
1669 unsigned w
= img
.GetWidth(), h
= img
.GetHeight();
1671 unsigned top
, bottom
, left
, right
, i
;
1674 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
1675 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = false; break;}
1677 for (empt
= true, top
= 0; empt
&& top
< h
; top
++)
1680 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1683 for (empt
= true, bottom
= h
-1; empt
&& bottom
> top
; bottom
--)
1685 MK_DTTMP(0, bottom
);
1686 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1689 for (empt
= true, left
= 0; empt
&& left
< w
; left
++)
1692 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1695 for (empt
= true, right
= w
-1; empt
&& right
> left
; right
--)
1698 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1701 top
--, left
--, bottom
++, right
++;
1703 return img
.GetSubImage(wxRect(left
, top
, right
- left
+ 1, bottom
- top
+ 1));
1707 #endif // wxUSE_MIMETYPE
1709 int wxFileIconsTable::GetIconID(const wxString
& extension
, const wxString
& mime
)
1711 if (!m_smallImageList
)
1715 if (!extension
.empty())
1717 wxFileIconEntry
*entry
= (wxFileIconEntry
*) m_HashTable
->Get(extension
);
1718 if (entry
) return (entry
-> iconid
);
1721 wxFileType
*ft
= (mime
.empty()) ?
1722 wxTheMimeTypesManager
-> GetFileTypeFromExtension(extension
) :
1723 wxTheMimeTypesManager
-> GetFileTypeFromMimeType(mime
);
1725 wxIconLocation iconLoc
;
1730 if ( ft
&& ft
->GetIcon(&iconLoc
) )
1732 ic
= wxIcon( iconLoc
);
1741 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1746 bmp
.CopyFromIcon(ic
);
1751 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1755 const unsigned int size
= 16;
1757 int treeid
= m_smallImageList
->GetImageCount();
1758 if ((bmp
.GetWidth() == (int) size
) && (bmp
.GetHeight() == (int) size
))
1760 m_smallImageList
->Add(bmp
);
1762 #if wxUSE_IMAGE && (!defined(__WINDOWS__) || wxUSE_WXDIB)
1765 wxImage img
= bmp
.ConvertToImage();
1767 if ((img
.GetWidth() != size
*2) || (img
.GetHeight() != size
*2))
1768 // m_smallImageList->Add(CreateAntialiasedBitmap(CutEmptyBorders(img).Rescale(size*2, size*2)));
1769 m_smallImageList
->Add(CreateAntialiasedBitmap(img
.Rescale(size
*2, size
*2)));
1771 m_smallImageList
->Add(CreateAntialiasedBitmap(img
));
1773 #endif // wxUSE_IMAGE
1775 m_HashTable
->Put(extension
, new wxFileIconEntry(treeid
));
1778 #else // !wxUSE_MIMETYPE
1781 if (extension
== wxT("exe"))
1785 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
1788 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG