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"
22 #include "wx/module.h"
24 #include "wx/button.h"
25 #include "wx/layout.h"
26 #include "wx/msgdlg.h"
27 #include "wx/textctrl.h"
28 #include "wx/textdlg.h"
29 #include "wx/filefn.h"
30 #include "wx/cmndata.h"
31 #include "wx/gdicmn.h"
33 #include "wx/imaglist.h"
37 #include "wx/tokenzr.h"
39 #include "wx/settings.h"
40 #include "wx/artprov.h"
42 #include "wx/mimetype.h"
44 #include "wx/choice.h"
47 #include "wx/statline.h"
50 #if defined(__WXMAC__)
51 #include "wx/mac/private.h" // includes mac headers
56 #include "wx/msw/winundef.h"
58 // FIXME - Mingw32 1.0 has both _getdrive() and _chdrive(). For now, let's assume
59 // older releases don't, but it should be verified and the checks modified
61 #if !defined(__GNUWIN32__) || (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
62 #if !defined(__WXWINCE__)
71 #if defined(__OS2__) || defined(__DOS__)
81 extern bool wxIsDriveAvailable(const wxString
& dirName
);
84 #if defined(__WXMAC__)
85 # include "MoreFilesX.h"
92 // If compiled under Windows, this macro can cause problems
97 // ----------------------------------------------------------------------------
98 // wxGetAvailableDrives, for WINDOWS, DOS, OS2, MAC, UNIX (returns "/")
99 // ----------------------------------------------------------------------------
101 size_t wxGetAvailableDrives(wxArrayString
&paths
, wxArrayString
&names
, wxArrayInt
&icon_ids
)
103 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
106 // No logical drives; return "\"
107 paths
.Add(wxT("\\"));
108 names
.Add(wxT("\\"));
109 icon_ids
.Add(wxFileIconsTable::computer
);
110 #elif defined(__WIN32__)
111 wxChar driveBuffer
[256];
112 size_t n
= (size_t) GetLogicalDriveStrings(255, driveBuffer
);
117 path
.Printf(wxT("%c:\\"), driveBuffer
[i
]);
118 name
.Printf(wxT("%c:"), driveBuffer
[i
]);
121 int driveType
= ::GetDriveType(path
);
124 case DRIVE_REMOVABLE
:
125 if (path
== wxT("a:\\") || path
== wxT("b:\\"))
126 imageId
= wxFileIconsTable::floppy
;
128 imageId
= wxFileIconsTable::removeable
;
131 imageId
= wxFileIconsTable::cdrom
;
136 imageId
= wxFileIconsTable::drive
;
142 icon_ids
.Add(imageId
);
144 while (driveBuffer
[i
] != wxT('\0'))
147 if (driveBuffer
[i
] == wxT('\0'))
150 #elif defined(__OS2__)
152 ULONG ulDriveNum
= 0;
153 ULONG ulDriveMap
= 0;
154 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
160 if (ulDriveMap
& ( 1 << i
))
163 path
.Printf(wxT("%c:\\"), 'A' + i
);
164 name
.Printf(wxT("%c:"), 'A' + i
);
166 // Note: If _filesys is unsupported by some compilers,
167 // we can always replace it by DosQueryFSAttach
168 char filesysname
[20];
170 ULONG cbBuffer
= sizeof(filesysname
);
171 PFSQBUFFER2 pfsqBuffer
= (PFSQBUFFER2
)filesysname
;
172 APIRET rc
= ::DosQueryFSAttach(name
.fn_str(),0,FSAIL_QUERYNAME
,pfsqBuffer
,&cbBuffer
);
175 filesysname
[0] = '\0';
178 _filesys(name
.fn_str(), filesysname
, sizeof(filesysname
));
180 /* FAT, LAN, HPFS, CDFS, NFS */
182 if (path
== wxT("A:\\") || path
== wxT("B:\\"))
183 imageId
= wxFileIconsTable::floppy
;
184 else if (!strcmp(filesysname
, "CDFS"))
185 imageId
= wxFileIconsTable::cdrom
;
186 else if (!strcmp(filesysname
, "LAN") ||
187 !strcmp(filesysname
, "NFS"))
188 imageId
= wxFileIconsTable::drive
;
190 imageId
= wxFileIconsTable::drive
;
193 icon_ids
.Add(imageId
);
198 #else // !__WIN32__, !__OS2__
201 /* If we can switch to the drive, it exists. */
202 for( drive
= 1; drive
<= 26; drive
++ )
205 path
.Printf(wxT("%c:\\"), (char) (drive
+ 'a' - 1));
206 name
.Printf(wxT("%c:"), (char) (drive
+ 'A' - 1));
208 if (wxIsDriveAvailable(path
))
212 icon_ids
.Add((drive
<= 2) ? wxFileIconsTable::floppy
: wxFileIconsTable::drive
);
215 #endif // __WIN32__/!__WIN32__
217 #elif defined(__WXMAC__)
219 ItemCount volumeIndex
= 1;
222 while( noErr
== err
)
224 HFSUniStr255 volumeName
;
226 FSVolumeInfo volumeInfo
;
227 err
= FSGetVolumeInfo(0, volumeIndex
, NULL
, kFSVolInfoFlags
, &volumeInfo
, &volumeName
, &fsRef
);
230 wxString path
= wxMacFSRefToPath( &fsRef
) ;
231 wxString name
= wxMacHFSUniStrToString( &volumeName
) ;
233 if ( (volumeInfo
.flags
& kFSVolFlagSoftwareLockedMask
) || (volumeInfo
.flags
& kFSVolFlagHardwareLockedMask
) )
235 icon_ids
.Add(wxFileIconsTable::cdrom
);
239 icon_ids
.Add(wxFileIconsTable::drive
);
241 // todo other removable
249 #elif defined(__UNIX__)
252 icon_ids
.Add(wxFileIconsTable::computer
);
254 #error "Unsupported platform in wxGenericDirCtrl!"
256 wxASSERT_MSG( (paths
.GetCount() == names
.GetCount()), wxT("The number of paths and their human readable names should be equal in number."));
257 wxASSERT_MSG( (paths
.GetCount() == icon_ids
.GetCount()), wxT("Wrong number of icons for available drives."));
258 return paths
.GetCount();
261 // ----------------------------------------------------------------------------
262 // wxIsDriveAvailable
263 // ----------------------------------------------------------------------------
267 bool wxIsDriveAvailable(const wxString
& dirName
)
269 // FIXME_MGL - this method leads to hang up under Watcom for some reason
271 wxUnusedVar(dirName
);
273 if ( dirName
.Len() == 3 && dirName
[1u] == wxT(':') )
275 wxString
dirNameLower(dirName
.Lower());
276 // VS: always return true for removable media, since Win95 doesn't
277 // like it when MS-DOS app accesses empty floppy drive
278 return (dirNameLower
[0u] == wxT('a') ||
279 dirNameLower
[0u] == wxT('b') ||
280 wxDirExists(dirNameLower
));
287 #elif defined(__WINDOWS__) || defined(__OS2__)
289 int setdrive(int WXUNUSED_IN_WINCE(drive
))
293 #elif defined(__GNUWIN32__) && \
294 (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
295 return _chdrive(drive
);
299 if (drive
< 1 || drive
> 31)
301 newdrive
[0] = (wxChar
)(wxT('A') + drive
- 1);
302 newdrive
[1] = wxT(':');
304 newdrive
[2] = wxT('\\');
305 newdrive
[3] = wxT('\0');
307 newdrive
[2] = wxT('\0');
309 #if defined(__WXMSW__)
310 if (::SetCurrentDirectory(newdrive
))
312 // VA doesn't know what LPSTR is and has its own set
313 if (!DosSetCurrentDir((PSZ
)newdrive
))
321 bool wxIsDriveAvailable(const wxString
& WXUNUSED_IN_WINCE(dirName
))
327 UINT errorMode
= SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOOPENFILEERRORBOX
);
331 // Check if this is a root directory and if so,
332 // whether the drive is available.
333 if (dirName
.Len() == 3 && dirName
[(size_t)1] == wxT(':'))
335 wxString
dirNameLower(dirName
.Lower());
336 #if defined(__GNUWIN32__) && !(defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
337 success
= wxDirExists(dirNameLower
);
340 // Avoid changing to drive since no media may be inserted.
341 if (dirNameLower
[(size_t)0] == 'a' || dirNameLower
[(size_t)0] == 'b')
344 int currentDrive
= _getdrive();
345 int thisDrive
= (int) (dirNameLower
[(size_t)0] - 'a' + 1) ;
346 int err
= setdrive( thisDrive
) ;
347 setdrive( currentDrive
);
356 (void) SetErrorMode(errorMode
);
362 #endif // __WINDOWS__ || __OS2__
364 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG
370 // Function which is called by quick sort. We want to override the default wxArrayString behaviour,
371 // and sort regardless of case.
372 static int wxCMPFUNC_CONV
wxDirCtrlStringCompareFunction(const wxString
& strFirst
, const wxString
& strSecond
)
374 return strFirst
.CmpNoCase(strSecond
);
377 //-----------------------------------------------------------------------------
379 //-----------------------------------------------------------------------------
381 wxDirItemData::wxDirItemData(const wxString
& path
, const wxString
& name
,
386 /* Insert logic to detect hidden files here
387 * In UnixLand we just check whether the first char is a dot
388 * For FileNameFromPath read LastDirNameInThisPath ;-) */
389 // m_isHidden = (bool)(wxFileNameFromPath(*m_path)[0] == '.');
391 m_isExpanded
= false;
395 void wxDirItemData::SetNewDirName(const wxString
& path
)
398 m_name
= wxFileNameFromPath(path
);
401 bool wxDirItemData::HasSubDirs() const
409 if ( !dir
.Open(m_path
) )
413 return dir
.HasSubDirs();
416 bool wxDirItemData::HasFiles(const wxString
& WXUNUSED(spec
)) const
424 if ( !dir
.Open(m_path
) )
428 return dir
.HasFiles();
431 //-----------------------------------------------------------------------------
433 //-----------------------------------------------------------------------------
436 #if wxUSE_EXTENDED_RTTI
437 WX_DEFINE_FLAGS( wxGenericDirCtrlStyle
)
439 wxBEGIN_FLAGS( wxGenericDirCtrlStyle
)
440 // new style border flags, we put them first to
441 // use them for streaming out
442 wxFLAGS_MEMBER(wxBORDER_SIMPLE
)
443 wxFLAGS_MEMBER(wxBORDER_SUNKEN
)
444 wxFLAGS_MEMBER(wxBORDER_DOUBLE
)
445 wxFLAGS_MEMBER(wxBORDER_RAISED
)
446 wxFLAGS_MEMBER(wxBORDER_STATIC
)
447 wxFLAGS_MEMBER(wxBORDER_NONE
)
449 // old style border flags
450 wxFLAGS_MEMBER(wxSIMPLE_BORDER
)
451 wxFLAGS_MEMBER(wxSUNKEN_BORDER
)
452 wxFLAGS_MEMBER(wxDOUBLE_BORDER
)
453 wxFLAGS_MEMBER(wxRAISED_BORDER
)
454 wxFLAGS_MEMBER(wxSTATIC_BORDER
)
455 wxFLAGS_MEMBER(wxBORDER
)
457 // standard window styles
458 wxFLAGS_MEMBER(wxTAB_TRAVERSAL
)
459 wxFLAGS_MEMBER(wxCLIP_CHILDREN
)
460 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW
)
461 wxFLAGS_MEMBER(wxWANTS_CHARS
)
462 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE
)
463 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB
)
464 wxFLAGS_MEMBER(wxVSCROLL
)
465 wxFLAGS_MEMBER(wxHSCROLL
)
467 wxFLAGS_MEMBER(wxDIRCTRL_DIR_ONLY
)
468 wxFLAGS_MEMBER(wxDIRCTRL_3D_INTERNAL
)
469 wxFLAGS_MEMBER(wxDIRCTRL_SELECT_FIRST
)
470 wxFLAGS_MEMBER(wxDIRCTRL_SHOW_FILTERS
)
472 wxEND_FLAGS( wxGenericDirCtrlStyle
)
474 IMPLEMENT_DYNAMIC_CLASS_XTI(wxGenericDirCtrl
, wxControl
,"wx/dirctrl.h")
476 wxBEGIN_PROPERTIES_TABLE(wxGenericDirCtrl
)
477 wxHIDE_PROPERTY( Children
)
478 wxPROPERTY( DefaultPath
, wxString
, SetDefaultPath
, GetDefaultPath
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
479 wxPROPERTY( Filter
, wxString
, SetFilter
, GetFilter
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
480 wxPROPERTY( DefaultFilter
, int , SetFilterIndex
, GetFilterIndex
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
481 wxPROPERTY_FLAGS( WindowStyle
, wxGenericDirCtrlStyle
, long, SetWindowStyleFlag
, GetWindowStyleFlag
, EMPTY_MACROVALUE
, 0, wxT("Helpstring"), wxT("group") )
482 wxEND_PROPERTIES_TABLE()
484 wxBEGIN_HANDLERS_TABLE(wxGenericDirCtrl
)
485 wxEND_HANDLERS_TABLE()
487 wxCONSTRUCTOR_8( wxGenericDirCtrl
, wxWindow
* , Parent
, wxWindowID
, Id
, wxString
, DefaultPath
,
488 wxPoint
, Position
, wxSize
, Size
, long , WindowStyle
, wxString
, Filter
, int , DefaultFilter
)
490 IMPLEMENT_DYNAMIC_CLASS(wxGenericDirCtrl
, wxControl
)
493 BEGIN_EVENT_TABLE(wxGenericDirCtrl
, wxControl
)
494 EVT_TREE_ITEM_EXPANDING (wxID_TREECTRL
, wxGenericDirCtrl::OnExpandItem
)
495 EVT_TREE_ITEM_COLLAPSED (wxID_TREECTRL
, wxGenericDirCtrl::OnCollapseItem
)
496 EVT_TREE_BEGIN_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnBeginEditItem
)
497 EVT_TREE_END_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnEndEditItem
)
498 EVT_SIZE (wxGenericDirCtrl::OnSize
)
501 wxGenericDirCtrl::wxGenericDirCtrl(void)
506 void wxGenericDirCtrl::ExpandRoot()
508 ExpandDir(m_rootId
); // automatically expand first level
510 // Expand and select the default path
511 if (!m_defaultPath
.empty())
513 ExpandPath(m_defaultPath
);
518 // On Unix, there's only one node under the (hidden) root node. It
519 // represents the / path, so the user would always have to expand it;
520 // let's do it ourselves
521 ExpandPath( wxT("/") );
526 bool wxGenericDirCtrl::Create(wxWindow
*parent
,
532 const wxString
& filter
,
534 const wxString
& name
)
536 if (!wxControl::Create(parent
, id
, pos
, size
, style
, wxDefaultValidator
, name
))
539 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE
));
543 long treeStyle
= wxTR_HAS_BUTTONS
;
545 // On Windows CE, if you hide the root, you get a crash when
546 // attempting to access data for children of the root item.
548 treeStyle
|= wxTR_HIDE_ROOT
;
552 treeStyle
|= wxTR_NO_LINES
;
555 if (style
& wxDIRCTRL_EDIT_LABELS
)
556 treeStyle
|= wxTR_EDIT_LABELS
;
558 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
559 treeStyle
|= wxNO_BORDER
;
561 treeStyle
|= wxBORDER_SUNKEN
;
563 long filterStyle
= 0;
564 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
565 filterStyle
|= wxNO_BORDER
;
567 filterStyle
|= wxBORDER_SUNKEN
;
569 m_treeCtrl
= CreateTreeCtrl(this, wxID_TREECTRL
,
570 wxPoint(0,0), GetClientSize(), treeStyle
);
572 if (!filter
.empty() && (style
& wxDIRCTRL_SHOW_FILTERS
))
573 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
, wxDefaultPosition
, wxDefaultSize
, filterStyle
);
578 if (m_filter
.empty())
582 m_filter
= wxT("*.*");
585 SetFilterIndex(defaultFilter
);
587 if (m_filterListCtrl
)
588 m_filterListCtrl
->FillFilterList(filter
, defaultFilter
);
590 m_treeCtrl
->SetImageList(wxTheFileIconsTable
->GetSmallImageList());
592 m_showHidden
= false;
593 wxDirItemData
* rootData
= new wxDirItemData(wxEmptyString
, wxEmptyString
, true);
597 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
598 rootName
= _("Computer");
600 rootName
= _("Sections");
603 m_rootId
= m_treeCtrl
->AddRoot( rootName
, 3, -1, rootData
);
604 m_treeCtrl
->SetItemHasChildren(m_rootId
);
614 wxGenericDirCtrl::~wxGenericDirCtrl()
618 void wxGenericDirCtrl::Init()
620 m_showHidden
= false;
622 m_currentFilterStr
= wxEmptyString
; // Default: any file
624 m_filterListCtrl
= NULL
;
627 wxTreeCtrl
* wxGenericDirCtrl::CreateTreeCtrl(wxWindow
*parent
, wxWindowID id
, const wxPoint
& pos
, const wxSize
& size
, long treeStyle
)
629 return new wxTreeCtrl(parent
, id
, pos
, size
, treeStyle
);
632 void wxGenericDirCtrl::ShowHidden( bool show
)
636 wxString path
= GetPath();
642 wxGenericDirCtrl::AddSection(const wxString
& path
, const wxString
& name
, int imageId
)
644 wxDirItemData
*dir_item
= new wxDirItemData(path
,name
,true);
646 wxTreeItemId id
= AppendItem( m_rootId
, name
, imageId
, -1, dir_item
);
648 m_treeCtrl
->SetItemHasChildren(id
);
653 void wxGenericDirCtrl::SetupSections()
655 wxArrayString paths
, names
;
658 size_t n
, count
= wxGetAvailableDrives(paths
, names
, icons
);
661 wxString home
= wxGetHomeDir();
662 AddSection( home
, _("Home directory"), 1);
663 home
+= wxT("/Desktop");
664 AddSection( home
, _("Desktop"), 1);
667 for (n
= 0; n
< count
; n
++)
668 AddSection(paths
[n
], names
[n
], icons
[n
]);
671 void wxGenericDirCtrl::OnBeginEditItem(wxTreeEvent
&event
)
673 // don't rename the main entry "Sections"
674 if (event
.GetItem() == m_rootId
)
680 // don't rename the individual sections
681 if (m_treeCtrl
->GetItemParent( event
.GetItem() ) == m_rootId
)
688 void wxGenericDirCtrl::OnEndEditItem(wxTreeEvent
&event
)
690 if ((event
.GetLabel().empty()) ||
691 (event
.GetLabel() == _(".")) ||
692 (event
.GetLabel() == _("..")) ||
693 (event
.GetLabel().Find(wxT('/')) != wxNOT_FOUND
) ||
694 (event
.GetLabel().Find(wxT('\\')) != wxNOT_FOUND
) ||
695 (event
.GetLabel().Find(wxT('|')) != wxNOT_FOUND
))
697 wxMessageDialog
dialog(this, _("Illegal directory name."), _("Error"), wxOK
| wxICON_ERROR
);
703 wxTreeItemId id
= event
.GetItem();
704 wxDirItemData
*data
= (wxDirItemData
*)m_treeCtrl
->GetItemData( id
);
707 wxString
new_name( wxPathOnly( data
->m_path
) );
708 new_name
+= wxString(wxFILE_SEP_PATH
);
709 new_name
+= event
.GetLabel();
713 if (wxFileExists(new_name
))
715 wxMessageDialog
dialog(this, _("File name exists already."), _("Error"), wxOK
| wxICON_ERROR
);
720 if (wxRenameFile(data
->m_path
,new_name
))
722 data
->SetNewDirName( new_name
);
726 wxMessageDialog
dialog(this, _("Operation not permitted."), _("Error"), wxOK
| wxICON_ERROR
);
732 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent
&event
)
734 wxTreeItemId parentId
= event
.GetItem();
736 // VS: this is needed because the event handler is called from wxTreeCtrl
737 // ctor when wxTR_HIDE_ROOT was specified
739 if (!m_rootId
.IsOk())
741 m_rootId
= m_treeCtrl
->GetRootItem();
746 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent
&event
)
748 CollapseDir(event
.GetItem());
751 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId
)
755 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
756 if (!data
->m_isExpanded
)
759 data
->m_isExpanded
= false;
760 wxTreeItemIdValue cookie
;
761 /* Workaround because DeleteChildren has disapeared (why?) and
762 * CollapseAndReset doesn't work as advertised (deletes parent too) */
763 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
766 m_treeCtrl
->Delete(child
);
767 /* Not GetNextChild below, because the cookie mechanism can't
768 * handle disappearing children! */
769 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
771 if (parentId
!= m_treeCtrl
->GetRootItem())
772 m_treeCtrl
->Collapse(parentId
);
775 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId
)
777 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
779 if (data
->m_isExpanded
)
782 data
->m_isExpanded
= true;
784 if (parentId
== m_treeCtrl
->GetRootItem())
792 wxString search
,path
,filename
;
794 wxString
dirName(data
->m_path
);
796 #if (defined(__WINDOWS__) && !defined(__WXWINCE__)) || defined(__DOS__) || defined(__OS2__)
797 // Check if this is a root directory and if so,
798 // whether the drive is avaiable.
799 if (!wxIsDriveAvailable(dirName
))
801 data
->m_isExpanded
= false;
802 //wxMessageBox(wxT("Sorry, this drive is not available."));
807 // This may take a longish time. Go to busy cursor
810 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
811 if (dirName
.Last() == ':')
812 dirName
+= wxString(wxFILE_SEP_PATH
);
816 wxArrayString filenames
;
819 wxString eachFilename
;
826 int style
= wxDIR_DIRS
;
827 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
828 if (d
.GetFirst(& eachFilename
, wxEmptyString
, style
))
832 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
834 dirs
.Add(eachFilename
);
837 while (d
.GetNext(&eachFilename
));
840 dirs
.Sort(wxDirCtrlStringCompareFunction
);
842 // Now do the filenames -- but only if we're allowed to
843 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
849 int style
= wxDIR_FILES
;
850 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
851 // Process each filter (ex: "JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg")
852 wxStringTokenizer strTok
;
854 strTok
.SetString(m_currentFilterStr
,wxT(";"));
855 while(strTok
.HasMoreTokens())
857 curFilter
= strTok
.GetNextToken();
858 if (d
.GetFirst(& eachFilename
, curFilter
, style
))
862 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
864 filenames
.Add(eachFilename
);
867 while (d
.GetNext(& eachFilename
));
871 filenames
.Sort(wxDirCtrlStringCompareFunction
);
874 // Add the sorted dirs
876 for (i
= 0; i
< dirs
.Count(); i
++)
878 eachFilename
= dirs
[i
];
880 if (!wxEndsWithPathSeparator(path
))
881 path
+= wxString(wxFILE_SEP_PATH
);
882 path
+= eachFilename
;
884 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,true);
885 wxTreeItemId id
= AppendItem( parentId
, eachFilename
,
886 wxFileIconsTable::folder
, -1, dir_item
);
887 m_treeCtrl
->SetItemImage( id
, wxFileIconsTable::folder_open
,
888 wxTreeItemIcon_Expanded
);
890 // Has this got any children? If so, make it expandable.
891 // (There are two situations when a dir has children: either it
892 // has subdirectories or it contains files that weren't filtered
893 // out. The latter only applies to dirctrl with files.)
894 if ( dir_item
->HasSubDirs() ||
895 (((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0) &&
896 dir_item
->HasFiles(m_currentFilterStr
)) )
898 m_treeCtrl
->SetItemHasChildren(id
);
902 // Add the sorted filenames
903 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
905 for (i
= 0; i
< filenames
.Count(); i
++)
907 eachFilename
= filenames
[i
];
909 if (!wxEndsWithPathSeparator(path
))
910 path
+= wxString(wxFILE_SEP_PATH
);
911 path
+= eachFilename
;
912 //path = dirName + wxString(wxT("/")) + eachFilename;
913 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,false);
914 int image_id
= wxFileIconsTable::file
;
915 if (eachFilename
.Find(wxT('.')) != wxNOT_FOUND
)
916 image_id
= wxTheFileIconsTable
->GetIconID(eachFilename
.AfterLast(wxT('.')));
917 (void) AppendItem( parentId
, eachFilename
, image_id
, -1, dir_item
);
922 void wxGenericDirCtrl::ReCreateTree()
924 CollapseDir(m_treeCtrl
->GetRootItem());
928 void wxGenericDirCtrl::CollapseTree()
930 wxTreeItemIdValue cookie
;
931 wxTreeItemId child
= m_treeCtrl
->GetFirstChild(m_rootId
, cookie
);
935 child
= m_treeCtrl
->GetNextChild(m_rootId
, cookie
);
939 // Find the child that matches the first part of 'path'.
940 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
941 // then the child for /usr is returned.
942 wxTreeItemId
wxGenericDirCtrl::FindChild(wxTreeItemId parentId
, const wxString
& path
, bool& done
)
944 wxString
path2(path
);
946 // Make sure all separators are as per the current platform
947 path2
.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH
));
948 path2
.Replace(wxT("/"), wxString(wxFILE_SEP_PATH
));
950 // Append a separator to foil bogus substring matching
951 path2
+= wxString(wxFILE_SEP_PATH
);
953 // In MSW or PM, case is not significant
954 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
958 wxTreeItemIdValue cookie
;
959 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
960 while (childId
.IsOk())
962 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
964 if (data
&& !data
->m_path
.empty())
966 wxString
childPath(data
->m_path
);
967 if (!wxEndsWithPathSeparator(childPath
))
968 childPath
+= wxString(wxFILE_SEP_PATH
);
970 // In MSW and PM, case is not significant
971 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
972 childPath
.MakeLower();
975 if (childPath
.Len() <= path2
.Len())
977 wxString path3
= path2
.Mid(0, childPath
.Len());
978 if (childPath
== path3
)
980 if (path3
.Len() == path2
.Len())
989 childId
= m_treeCtrl
->GetNextChild(parentId
, cookie
);
991 wxTreeItemId invalid
;
995 // Try to expand as much of the given path as possible,
996 // and select the given tree item.
997 bool wxGenericDirCtrl::ExpandPath(const wxString
& path
)
1000 wxTreeItemId id
= FindChild(m_rootId
, path
, done
);
1001 wxTreeItemId lastId
= id
; // The last non-zero id
1002 while (id
.IsOk() && !done
)
1006 id
= FindChild(id
, path
, done
);
1013 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(lastId
);
1016 m_treeCtrl
->Expand(lastId
);
1018 if ((GetWindowStyle() & wxDIRCTRL_SELECT_FIRST
) && data
->m_isDir
)
1020 // Find the first file in this directory
1021 wxTreeItemIdValue cookie
;
1022 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(lastId
, cookie
);
1023 bool selectedChild
= false;
1024 while (childId
.IsOk())
1026 data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
1028 if (data
&& data
->m_path
!= wxEmptyString
&& !data
->m_isDir
)
1030 m_treeCtrl
->SelectItem(childId
);
1031 m_treeCtrl
->EnsureVisible(childId
);
1032 selectedChild
= true;
1035 childId
= m_treeCtrl
->GetNextChild(lastId
, cookie
);
1039 m_treeCtrl
->SelectItem(lastId
);
1040 m_treeCtrl
->EnsureVisible(lastId
);
1045 m_treeCtrl
->SelectItem(lastId
);
1046 m_treeCtrl
->EnsureVisible(lastId
);
1052 wxString
wxGenericDirCtrl::GetPath() const
1054 wxTreeItemId id
= m_treeCtrl
->GetSelection();
1057 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1058 return data
->m_path
;
1061 return wxEmptyString
;
1064 wxString
wxGenericDirCtrl::GetFilePath() const
1066 wxTreeItemId id
= m_treeCtrl
->GetSelection();
1069 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1071 return wxEmptyString
;
1073 return data
->m_path
;
1076 return wxEmptyString
;
1079 void wxGenericDirCtrl::SetPath(const wxString
& path
)
1081 m_defaultPath
= path
;
1088 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId id
, int dirFlags
, wxArrayString
& filenames
)
1090 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1092 // This may take a longish time. Go to busy cursor
1097 wxString search
,path
,filename
;
1099 wxString
dirName(data
->m_path
);
1101 #if defined(__WXMSW__) || defined(__OS2__)
1102 if (dirName
.Last() == ':')
1103 dirName
+= wxString(wxFILE_SEP_PATH
);
1107 wxString eachFilename
;
1114 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, dirFlags
))
1118 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
1120 filenames
.Add(eachFilename
);
1123 while (d
.GetNext(& eachFilename
)) ;
1129 void wxGenericDirCtrl::SetFilterIndex(int n
)
1131 m_currentFilter
= n
;
1134 if (ExtractWildcard(m_filter
, n
, f
, d
))
1135 m_currentFilterStr
= f
;
1138 m_currentFilterStr
= wxT("*");
1140 m_currentFilterStr
= wxT("*.*");
1144 void wxGenericDirCtrl::SetFilter(const wxString
& filter
)
1149 if (ExtractWildcard(m_filter
, m_currentFilter
, f
, d
))
1150 m_currentFilterStr
= f
;
1153 m_currentFilterStr
= wxT("*");
1155 m_currentFilterStr
= wxT("*.*");
1159 // Extract description and actual filter from overall filter string
1160 bool wxGenericDirCtrl::ExtractWildcard(const wxString
& filterStr
, int n
, wxString
& filter
, wxString
& description
)
1162 wxArrayString filters
, descriptions
;
1163 int count
= wxParseCommonDialogsFilter(filterStr
, descriptions
, filters
);
1164 if (count
> 0 && n
< count
)
1166 filter
= filters
[n
];
1167 description
= descriptions
[n
];
1174 #if WXWIN_COMPATIBILITY_2_4
1175 // Parses the global filter, returning the number of filters.
1176 // Returns 0 if none or if there's a problem.
1177 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpg"
1178 int wxGenericDirCtrl::ParseFilter(const wxString
& filterStr
, wxArrayString
& filters
, wxArrayString
& descriptions
)
1180 return wxParseCommonDialogsFilter(filterStr
, descriptions
, filters
);
1182 #endif // WXWIN_COMPATIBILITY_2_4
1184 void wxGenericDirCtrl::DoResize()
1186 wxSize sz
= GetClientSize();
1187 int verticalSpacing
= 3;
1191 if (m_filterListCtrl
)
1193 filterSz
= m_filterListCtrl
->GetSize();
1194 sz
.y
-= (filterSz
.y
+ verticalSpacing
);
1196 m_treeCtrl
->SetSize(0, 0, sz
.x
, sz
.y
);
1197 if (m_filterListCtrl
)
1199 m_filterListCtrl
->SetSize(0, sz
.y
+ verticalSpacing
, sz
.x
, filterSz
.y
);
1200 // Don't know why, but this needs refreshing after a resize (wxMSW)
1201 m_filterListCtrl
->Refresh();
1207 void wxGenericDirCtrl::OnSize(wxSizeEvent
& WXUNUSED(event
))
1212 wxTreeItemId
wxGenericDirCtrl::AppendItem (const wxTreeItemId
& parent
,
1213 const wxString
& text
,
1214 int image
, int selectedImage
,
1215 wxTreeItemData
* data
)
1217 wxTreeCtrl
*treeCtrl
= GetTreeCtrl ();
1219 wxASSERT (treeCtrl
);
1223 return treeCtrl
->AppendItem (parent
, text
, image
, selectedImage
, data
);
1227 return wxTreeItemId();
1232 //-----------------------------------------------------------------------------
1233 // wxDirFilterListCtrl
1234 //-----------------------------------------------------------------------------
1236 IMPLEMENT_CLASS(wxDirFilterListCtrl
, wxChoice
)
1238 BEGIN_EVENT_TABLE(wxDirFilterListCtrl
, wxChoice
)
1239 EVT_CHOICE(wxID_ANY
, wxDirFilterListCtrl::OnSelFilter
)
1242 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl
* parent
, const wxWindowID id
,
1248 return wxChoice::Create(parent
, id
, pos
, size
, 0, NULL
, style
);
1251 void wxDirFilterListCtrl::Init()
1256 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent
& WXUNUSED(event
))
1258 int sel
= GetSelection();
1260 wxString currentPath
= m_dirCtrl
->GetPath();
1262 m_dirCtrl
->SetFilterIndex(sel
);
1264 // If the filter has changed, the view is out of date, so
1265 // collapse the tree.
1266 m_dirCtrl
->ReCreateTree();
1268 // Try to restore the selection, or at least the directory
1269 m_dirCtrl
->ExpandPath(currentPath
);
1272 void wxDirFilterListCtrl::FillFilterList(const wxString
& filter
, int defaultFilter
)
1275 wxArrayString descriptions
, filters
;
1276 size_t n
= (size_t) wxParseCommonDialogsFilter(filter
, descriptions
, filters
);
1278 if (n
> 0 && defaultFilter
< (int) n
)
1280 for (size_t i
= 0; i
< n
; i
++)
1281 Append(descriptions
[i
]);
1282 SetSelection(defaultFilter
);
1285 #endif // wxUSE_DIRDLG
1287 #if wxUSE_DIRDLG || wxUSE_FILEDLG
1289 // ----------------------------------------------------------------------------
1290 // wxFileIconsTable icons
1291 // ----------------------------------------------------------------------------
1294 /* Computer (c) Julian Smart */
1295 static const char * file_icons_tbl_computer_xpm
[] = {
1296 /* columns rows colors chars-per-pixel */
1358 #endif // GTK+ < 2.4
1360 // ----------------------------------------------------------------------------
1361 // wxFileIconsTable & friends
1362 // ----------------------------------------------------------------------------
1364 // global instance of a wxFileIconsTable
1365 wxFileIconsTable
* wxTheFileIconsTable
= (wxFileIconsTable
*)NULL
;
1367 // A module to allow icons table cleanup
1369 class wxFileIconsTableModule
: public wxModule
1371 DECLARE_DYNAMIC_CLASS(wxFileIconsTableModule
)
1373 wxFileIconsTableModule() {}
1374 bool OnInit() { wxTheFileIconsTable
= new wxFileIconsTable
; return true; }
1377 if (wxTheFileIconsTable
)
1379 delete wxTheFileIconsTable
;
1380 wxTheFileIconsTable
= NULL
;
1385 IMPLEMENT_DYNAMIC_CLASS(wxFileIconsTableModule
, wxModule
)
1387 class wxFileIconEntry
: public wxObject
1390 wxFileIconEntry(int i
) { id
= i
; }
1395 wxFileIconsTable::wxFileIconsTable()
1398 m_smallImageList
= NULL
;
1401 wxFileIconsTable::~wxFileIconsTable()
1405 WX_CLEAR_HASH_TABLE(*m_HashTable
);
1408 if (m_smallImageList
) delete m_smallImageList
;
1411 // delayed initialization - wait until first use (wxArtProv not created yet)
1412 void wxFileIconsTable::Create()
1414 wxCHECK_RET(!m_smallImageList
&& !m_HashTable
, wxT("creating icons twice"));
1415 m_HashTable
= new wxHashTable(wxKEY_STRING
);
1416 m_smallImageList
= new wxImageList(16, 16);
1419 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER
,
1423 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER_OPEN
,
1428 // GTK24 uses this icon in the file open dialog
1429 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_HARDDISK
,
1433 m_smallImageList
->Add(wxIcon(file_icons_tbl_computer_xpm
));
1436 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_HARDDISK
,
1440 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_CDROM
,
1444 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FLOPPY
,
1448 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_REMOVABLE
,
1452 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE
,
1456 if (GetIconID(wxEmptyString
, _T("application/x-executable")) == file
)
1458 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE
,
1461 delete m_HashTable
->Get(_T("exe"));
1462 m_HashTable
->Delete(_T("exe"));
1463 m_HashTable
->Put(_T("exe"), new wxFileIconEntry(executable
));
1465 /* else put into list by GetIconID
1466 (KDE defines application/x-executable for *.exe and has nice icon)
1470 wxImageList
*wxFileIconsTable::GetSmallImageList()
1472 if (!m_smallImageList
)
1475 return m_smallImageList
;
1478 #if wxUSE_MIMETYPE && wxUSE_IMAGE
1479 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
1480 // one icon and we won't resize it
1482 static wxBitmap
CreateAntialiasedBitmap(const wxImage
& img
)
1484 const unsigned int size
= 16;
1486 wxImage
smallimg (size
, size
);
1487 unsigned char *p1
, *p2
, *ps
;
1488 unsigned char mr
= img
.GetMaskRed(),
1489 mg
= img
.GetMaskGreen(),
1490 mb
= img
.GetMaskBlue();
1493 unsigned sr
, sg
, sb
, smask
;
1495 p1
= img
.GetData(), p2
= img
.GetData() + 3 * size
*2, ps
= smallimg
.GetData();
1496 smallimg
.SetMaskColour(mr
, mr
, mr
);
1498 for (y
= 0; y
< size
; y
++)
1500 for (x
= 0; x
< size
; x
++)
1502 sr
= sg
= sb
= smask
= 0;
1503 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1504 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1507 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1508 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1511 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1512 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1515 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1516 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1521 ps
[0] = ps
[1] = ps
[2] = mr
;
1524 ps
[0] = (unsigned char)(sr
>> 2);
1525 ps
[1] = (unsigned char)(sg
>> 2);
1526 ps
[2] = (unsigned char)(sb
>> 2);
1530 p1
+= size
*2 * 3, p2
+= size
*2 * 3;
1533 return wxBitmap(smallimg
);
1536 // This function is currently not unused anymore
1538 // finds empty borders and return non-empty area of image:
1539 static wxImage
CutEmptyBorders(const wxImage
& img
)
1541 unsigned char mr
= img
.GetMaskRed(),
1542 mg
= img
.GetMaskGreen(),
1543 mb
= img
.GetMaskBlue();
1544 unsigned char *dt
= img
.GetData(), *dttmp
;
1545 unsigned w
= img
.GetWidth(), h
= img
.GetHeight();
1547 unsigned top
, bottom
, left
, right
, i
;
1550 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
1551 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = false; break;}
1553 for (empt
= true, top
= 0; empt
&& top
< h
; top
++)
1556 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1559 for (empt
= true, bottom
= h
-1; empt
&& bottom
> top
; bottom
--)
1561 MK_DTTMP(0, bottom
);
1562 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1565 for (empt
= true, left
= 0; empt
&& left
< w
; left
++)
1568 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1571 for (empt
= true, right
= w
-1; empt
&& right
> left
; right
--)
1574 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1577 top
--, left
--, bottom
++, right
++;
1579 return img
.GetSubImage(wxRect(left
, top
, right
- left
+ 1, bottom
- top
+ 1));
1583 #endif // wxUSE_MIMETYPE
1585 int wxFileIconsTable::GetIconID(const wxString
& extension
, const wxString
& mime
)
1587 if (!m_smallImageList
)
1591 if (!extension
.empty())
1593 wxFileIconEntry
*entry
= (wxFileIconEntry
*) m_HashTable
->Get(extension
);
1594 if (entry
) return (entry
-> id
);
1597 wxFileType
*ft
= (mime
.empty()) ?
1598 wxTheMimeTypesManager
-> GetFileTypeFromExtension(extension
) :
1599 wxTheMimeTypesManager
-> GetFileTypeFromMimeType(mime
);
1601 wxIconLocation iconLoc
;
1606 if ( ft
&& ft
->GetIcon(&iconLoc
) )
1608 ic
= wxIcon( iconLoc
);
1617 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1622 bmp
.CopyFromIcon(ic
);
1627 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1631 const unsigned int size
= 16;
1633 int id
= m_smallImageList
->GetImageCount();
1634 if ((bmp
.GetWidth() == (int) size
) && (bmp
.GetHeight() == (int) size
))
1636 m_smallImageList
->Add(bmp
);
1641 wxImage img
= bmp
.ConvertToImage();
1643 if ((img
.GetWidth() != size
*2) || (img
.GetHeight() != size
*2))
1644 // m_smallImageList->Add(CreateAntialiasedBitmap(CutEmptyBorders(img).Rescale(size*2, size*2)));
1645 m_smallImageList
->Add(CreateAntialiasedBitmap(img
.Rescale(size
*2, size
*2)));
1647 m_smallImageList
->Add(CreateAntialiasedBitmap(img
));
1649 #endif // wxUSE_IMAGE
1651 m_HashTable
->Put(extension
, new wxFileIconEntry(id
));
1654 #else // !wxUSE_MIMETYPE
1657 if (extension
== wxT("exe"))
1661 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
1664 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG