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 if ( dirName
.Len() == 3 && dirName
[1u] == wxT(':') )
273 wxString
dirNameLower(dirName
.Lower());
274 // VS: always return true for removable media, since Win95 doesn't
275 // like it when MS-DOS app accesses empty floppy drive
276 return (dirNameLower
[0u] == wxT('a') ||
277 dirNameLower
[0u] == wxT('b') ||
278 wxDirExists(dirNameLower
));
285 #elif defined(__WINDOWS__) || defined(__OS2__)
287 int setdrive(int WXUNUSED_IN_WINCE(drive
))
291 #elif defined(__GNUWIN32__) && \
292 (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
293 return _chdrive(drive
);
297 if (drive
< 1 || drive
> 31)
299 newdrive
[0] = (wxChar
)(wxT('A') + drive
- 1);
300 newdrive
[1] = wxT(':');
302 newdrive
[2] = wxT('\\');
303 newdrive
[3] = wxT('\0');
305 newdrive
[2] = wxT('\0');
307 #if defined(__WXMSW__)
308 if (::SetCurrentDirectory(newdrive
))
310 // VA doesn't know what LPSTR is and has its own set
311 if (!DosSetCurrentDir((PSZ
)newdrive
))
319 bool wxIsDriveAvailable(const wxString
& WXUNUSED_IN_WINCE(dirName
))
325 UINT errorMode
= SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOOPENFILEERRORBOX
);
329 // Check if this is a root directory and if so,
330 // whether the drive is available.
331 if (dirName
.Len() == 3 && dirName
[(size_t)1] == wxT(':'))
333 wxString
dirNameLower(dirName
.Lower());
334 #if defined(__GNUWIN32__) && !(defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
335 success
= wxDirExists(dirNameLower
);
338 // Avoid changing to drive since no media may be inserted.
339 if (dirNameLower
[(size_t)0] == 'a' || dirNameLower
[(size_t)0] == 'b')
342 int currentDrive
= _getdrive();
343 int thisDrive
= (int) (dirNameLower
[(size_t)0] - 'a' + 1) ;
344 int err
= setdrive( thisDrive
) ;
345 setdrive( currentDrive
);
354 (void) SetErrorMode(errorMode
);
360 #endif // __WINDOWS__ || __OS2__
362 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG
368 // Function which is called by quick sort. We want to override the default wxArrayString behaviour,
369 // and sort regardless of case.
370 static int wxCMPFUNC_CONV
wxDirCtrlStringCompareFunction(const wxString
& strFirst
, const wxString
& strSecond
)
372 return strFirst
.CmpNoCase(strSecond
);
375 //-----------------------------------------------------------------------------
377 //-----------------------------------------------------------------------------
379 wxDirItemData::wxDirItemData(const wxString
& path
, const wxString
& name
,
384 /* Insert logic to detect hidden files here
385 * In UnixLand we just check whether the first char is a dot
386 * For FileNameFromPath read LastDirNameInThisPath ;-) */
387 // m_isHidden = (bool)(wxFileNameFromPath(*m_path)[0] == '.');
389 m_isExpanded
= false;
393 void wxDirItemData::SetNewDirName(const wxString
& path
)
396 m_name
= wxFileNameFromPath(path
);
399 bool wxDirItemData::HasSubDirs() const
407 if ( !dir
.Open(m_path
) )
411 return dir
.HasSubDirs();
414 bool wxDirItemData::HasFiles(const wxString
& WXUNUSED(spec
)) const
422 if ( !dir
.Open(m_path
) )
426 return dir
.HasFiles();
429 //-----------------------------------------------------------------------------
431 //-----------------------------------------------------------------------------
434 #if wxUSE_EXTENDED_RTTI
435 WX_DEFINE_FLAGS( wxGenericDirCtrlStyle
)
437 wxBEGIN_FLAGS( wxGenericDirCtrlStyle
)
438 // new style border flags, we put them first to
439 // use them for streaming out
440 wxFLAGS_MEMBER(wxBORDER_SIMPLE
)
441 wxFLAGS_MEMBER(wxBORDER_SUNKEN
)
442 wxFLAGS_MEMBER(wxBORDER_DOUBLE
)
443 wxFLAGS_MEMBER(wxBORDER_RAISED
)
444 wxFLAGS_MEMBER(wxBORDER_STATIC
)
445 wxFLAGS_MEMBER(wxBORDER_NONE
)
447 // old style border flags
448 wxFLAGS_MEMBER(wxSIMPLE_BORDER
)
449 wxFLAGS_MEMBER(wxSUNKEN_BORDER
)
450 wxFLAGS_MEMBER(wxDOUBLE_BORDER
)
451 wxFLAGS_MEMBER(wxRAISED_BORDER
)
452 wxFLAGS_MEMBER(wxSTATIC_BORDER
)
453 wxFLAGS_MEMBER(wxBORDER
)
455 // standard window styles
456 wxFLAGS_MEMBER(wxTAB_TRAVERSAL
)
457 wxFLAGS_MEMBER(wxCLIP_CHILDREN
)
458 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW
)
459 wxFLAGS_MEMBER(wxWANTS_CHARS
)
460 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE
)
461 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB
)
462 wxFLAGS_MEMBER(wxVSCROLL
)
463 wxFLAGS_MEMBER(wxHSCROLL
)
465 wxFLAGS_MEMBER(wxDIRCTRL_DIR_ONLY
)
466 wxFLAGS_MEMBER(wxDIRCTRL_3D_INTERNAL
)
467 wxFLAGS_MEMBER(wxDIRCTRL_SELECT_FIRST
)
468 wxFLAGS_MEMBER(wxDIRCTRL_SHOW_FILTERS
)
470 wxEND_FLAGS( wxGenericDirCtrlStyle
)
472 IMPLEMENT_DYNAMIC_CLASS_XTI(wxGenericDirCtrl
, wxControl
,"wx/dirctrl.h")
474 wxBEGIN_PROPERTIES_TABLE(wxGenericDirCtrl
)
475 wxHIDE_PROPERTY( Children
)
476 wxPROPERTY( DefaultPath
, wxString
, SetDefaultPath
, GetDefaultPath
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
477 wxPROPERTY( Filter
, wxString
, SetFilter
, GetFilter
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
478 wxPROPERTY( DefaultFilter
, int , SetFilterIndex
, GetFilterIndex
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
479 wxPROPERTY_FLAGS( WindowStyle
, wxGenericDirCtrlStyle
, long, SetWindowStyleFlag
, GetWindowStyleFlag
, EMPTY_MACROVALUE
, 0, wxT("Helpstring"), wxT("group") )
480 wxEND_PROPERTIES_TABLE()
482 wxBEGIN_HANDLERS_TABLE(wxGenericDirCtrl
)
483 wxEND_HANDLERS_TABLE()
485 wxCONSTRUCTOR_8( wxGenericDirCtrl
, wxWindow
* , Parent
, wxWindowID
, Id
, wxString
, DefaultPath
,
486 wxPoint
, Position
, wxSize
, Size
, long , WindowStyle
, wxString
, Filter
, int , DefaultFilter
)
488 IMPLEMENT_DYNAMIC_CLASS(wxGenericDirCtrl
, wxControl
)
491 BEGIN_EVENT_TABLE(wxGenericDirCtrl
, wxControl
)
492 EVT_TREE_ITEM_EXPANDING (wxID_TREECTRL
, wxGenericDirCtrl::OnExpandItem
)
493 EVT_TREE_ITEM_COLLAPSED (wxID_TREECTRL
, wxGenericDirCtrl::OnCollapseItem
)
494 EVT_TREE_BEGIN_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnBeginEditItem
)
495 EVT_TREE_END_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnEndEditItem
)
496 EVT_SIZE (wxGenericDirCtrl::OnSize
)
499 wxGenericDirCtrl::wxGenericDirCtrl(void)
504 void wxGenericDirCtrl::ExpandRoot()
506 ExpandDir(m_rootId
); // automatically expand first level
508 // Expand and select the default path
509 if (!m_defaultPath
.empty())
511 ExpandPath(m_defaultPath
);
516 // On Unix, there's only one node under the (hidden) root node. It
517 // represents the / path, so the user would always have to expand it;
518 // let's do it ourselves
519 ExpandPath( wxT("/") );
524 bool wxGenericDirCtrl::Create(wxWindow
*parent
,
530 const wxString
& filter
,
532 const wxString
& name
)
534 if (!wxControl::Create(parent
, id
, pos
, size
, style
, wxDefaultValidator
, name
))
537 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE
));
541 long treeStyle
= wxTR_HAS_BUTTONS
;
543 // On Windows CE, if you hide the root, you get a crash when
544 // attempting to access data for children of the root item.
546 treeStyle
|= wxTR_HIDE_ROOT
;
550 treeStyle
|= wxTR_NO_LINES
;
553 if (style
& wxDIRCTRL_EDIT_LABELS
)
554 treeStyle
|= wxTR_EDIT_LABELS
;
556 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
557 treeStyle
|= wxNO_BORDER
;
559 treeStyle
|= wxBORDER_SUNKEN
;
561 long filterStyle
= 0;
562 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
563 filterStyle
|= wxNO_BORDER
;
565 filterStyle
|= wxBORDER_SUNKEN
;
567 m_treeCtrl
= CreateTreeCtrl(this, wxID_TREECTRL
,
568 wxPoint(0,0), GetClientSize(), treeStyle
);
570 if (!filter
.empty() && (style
& wxDIRCTRL_SHOW_FILTERS
))
571 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
, wxDefaultPosition
, wxDefaultSize
, filterStyle
);
576 if (m_filter
.empty())
580 m_filter
= wxT("*.*");
583 SetFilterIndex(defaultFilter
);
585 if (m_filterListCtrl
)
586 m_filterListCtrl
->FillFilterList(filter
, defaultFilter
);
588 m_treeCtrl
->SetImageList(wxTheFileIconsTable
->GetSmallImageList());
590 m_showHidden
= false;
591 wxDirItemData
* rootData
= new wxDirItemData(wxEmptyString
, wxEmptyString
, true);
595 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
596 rootName
= _("Computer");
598 rootName
= _("Sections");
601 m_rootId
= m_treeCtrl
->AddRoot( rootName
, 3, -1, rootData
);
602 m_treeCtrl
->SetItemHasChildren(m_rootId
);
612 wxGenericDirCtrl::~wxGenericDirCtrl()
616 void wxGenericDirCtrl::Init()
618 m_showHidden
= false;
620 m_currentFilterStr
= wxEmptyString
; // Default: any file
622 m_filterListCtrl
= NULL
;
625 wxTreeCtrl
* wxGenericDirCtrl::CreateTreeCtrl(wxWindow
*parent
, wxWindowID id
, const wxPoint
& pos
, const wxSize
& size
, long treeStyle
)
627 return new wxTreeCtrl(parent
, id
, pos
, size
, treeStyle
);
630 void wxGenericDirCtrl::ShowHidden( bool show
)
634 wxString path
= GetPath();
640 wxGenericDirCtrl::AddSection(const wxString
& path
, const wxString
& name
, int imageId
)
642 wxDirItemData
*dir_item
= new wxDirItemData(path
,name
,true);
644 wxTreeItemId id
= AppendItem( m_rootId
, name
, imageId
, -1, dir_item
);
646 m_treeCtrl
->SetItemHasChildren(id
);
651 void wxGenericDirCtrl::SetupSections()
653 wxArrayString paths
, names
;
656 size_t n
, count
= wxGetAvailableDrives(paths
, names
, icons
);
659 wxString home
= wxGetHomeDir();
660 AddSection( home
, _("Home directory"), 1);
661 home
+= wxT("/Desktop");
662 AddSection( home
, _("Desktop"), 1);
665 for (n
= 0; n
< count
; n
++)
666 AddSection(paths
[n
], names
[n
], icons
[n
]);
669 void wxGenericDirCtrl::OnBeginEditItem(wxTreeEvent
&event
)
671 // don't rename the main entry "Sections"
672 if (event
.GetItem() == m_rootId
)
678 // don't rename the individual sections
679 if (m_treeCtrl
->GetItemParent( event
.GetItem() ) == m_rootId
)
686 void wxGenericDirCtrl::OnEndEditItem(wxTreeEvent
&event
)
688 if ((event
.GetLabel().empty()) ||
689 (event
.GetLabel() == _(".")) ||
690 (event
.GetLabel() == _("..")) ||
691 (event
.GetLabel().Find(wxT('/')) != wxNOT_FOUND
) ||
692 (event
.GetLabel().Find(wxT('\\')) != wxNOT_FOUND
) ||
693 (event
.GetLabel().Find(wxT('|')) != wxNOT_FOUND
))
695 wxMessageDialog
dialog(this, _("Illegal directory name."), _("Error"), wxOK
| wxICON_ERROR
);
701 wxTreeItemId id
= event
.GetItem();
702 wxDirItemData
*data
= (wxDirItemData
*)m_treeCtrl
->GetItemData( id
);
705 wxString
new_name( wxPathOnly( data
->m_path
) );
706 new_name
+= wxString(wxFILE_SEP_PATH
);
707 new_name
+= event
.GetLabel();
711 if (wxFileExists(new_name
))
713 wxMessageDialog
dialog(this, _("File name exists already."), _("Error"), wxOK
| wxICON_ERROR
);
718 if (wxRenameFile(data
->m_path
,new_name
))
720 data
->SetNewDirName( new_name
);
724 wxMessageDialog
dialog(this, _("Operation not permitted."), _("Error"), wxOK
| wxICON_ERROR
);
730 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent
&event
)
732 wxTreeItemId parentId
= event
.GetItem();
734 // VS: this is needed because the event handler is called from wxTreeCtrl
735 // ctor when wxTR_HIDE_ROOT was specified
737 if (!m_rootId
.IsOk())
739 m_rootId
= m_treeCtrl
->GetRootItem();
744 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent
&event
)
746 CollapseDir(event
.GetItem());
749 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId
)
753 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
754 if (!data
->m_isExpanded
)
757 data
->m_isExpanded
= false;
758 wxTreeItemIdValue cookie
;
759 /* Workaround because DeleteChildren has disapeared (why?) and
760 * CollapseAndReset doesn't work as advertised (deletes parent too) */
761 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
764 m_treeCtrl
->Delete(child
);
765 /* Not GetNextChild below, because the cookie mechanism can't
766 * handle disappearing children! */
767 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
769 if (parentId
!= m_treeCtrl
->GetRootItem())
770 m_treeCtrl
->Collapse(parentId
);
773 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId
)
775 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
777 if (data
->m_isExpanded
)
780 data
->m_isExpanded
= true;
782 if (parentId
== m_treeCtrl
->GetRootItem())
790 wxString search
,path
,filename
;
792 wxString
dirName(data
->m_path
);
794 #if (defined(__WINDOWS__) && !defined(__WXWINCE__)) || defined(__DOS__) || defined(__OS2__)
795 // Check if this is a root directory and if so,
796 // whether the drive is avaiable.
797 if (!wxIsDriveAvailable(dirName
))
799 data
->m_isExpanded
= false;
800 //wxMessageBox(wxT("Sorry, this drive is not available."));
805 // This may take a longish time. Go to busy cursor
808 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
809 if (dirName
.Last() == ':')
810 dirName
+= wxString(wxFILE_SEP_PATH
);
814 wxArrayString filenames
;
817 wxString eachFilename
;
824 int style
= wxDIR_DIRS
;
825 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
826 if (d
.GetFirst(& eachFilename
, wxEmptyString
, style
))
830 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
832 dirs
.Add(eachFilename
);
835 while (d
.GetNext(&eachFilename
));
838 dirs
.Sort(wxDirCtrlStringCompareFunction
);
840 // Now do the filenames -- but only if we're allowed to
841 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
847 int style
= wxDIR_FILES
;
848 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
849 // Process each filter (ex: "JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg")
850 wxStringTokenizer strTok
;
852 strTok
.SetString(m_currentFilterStr
,wxT(";"));
853 while(strTok
.HasMoreTokens())
855 curFilter
= strTok
.GetNextToken();
856 if (d
.GetFirst(& eachFilename
, curFilter
, style
))
860 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
862 filenames
.Add(eachFilename
);
865 while (d
.GetNext(& eachFilename
));
869 filenames
.Sort(wxDirCtrlStringCompareFunction
);
872 // Add the sorted dirs
874 for (i
= 0; i
< dirs
.Count(); i
++)
876 eachFilename
= dirs
[i
];
878 if (!wxEndsWithPathSeparator(path
))
879 path
+= wxString(wxFILE_SEP_PATH
);
880 path
+= eachFilename
;
882 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,true);
883 wxTreeItemId id
= AppendItem( parentId
, eachFilename
,
884 wxFileIconsTable::folder
, -1, dir_item
);
885 m_treeCtrl
->SetItemImage( id
, wxFileIconsTable::folder_open
,
886 wxTreeItemIcon_Expanded
);
888 // Has this got any children? If so, make it expandable.
889 // (There are two situations when a dir has children: either it
890 // has subdirectories or it contains files that weren't filtered
891 // out. The latter only applies to dirctrl with files.)
892 if ( dir_item
->HasSubDirs() ||
893 (((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0) &&
894 dir_item
->HasFiles(m_currentFilterStr
)) )
896 m_treeCtrl
->SetItemHasChildren(id
);
900 // Add the sorted filenames
901 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
903 for (i
= 0; i
< filenames
.Count(); i
++)
905 eachFilename
= filenames
[i
];
907 if (!wxEndsWithPathSeparator(path
))
908 path
+= wxString(wxFILE_SEP_PATH
);
909 path
+= eachFilename
;
910 //path = dirName + wxString(wxT("/")) + eachFilename;
911 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,false);
912 int image_id
= wxFileIconsTable::file
;
913 if (eachFilename
.Find(wxT('.')) != wxNOT_FOUND
)
914 image_id
= wxTheFileIconsTable
->GetIconID(eachFilename
.AfterLast(wxT('.')));
915 (void) AppendItem( parentId
, eachFilename
, image_id
, -1, dir_item
);
920 void wxGenericDirCtrl::ReCreateTree()
922 CollapseDir(m_treeCtrl
->GetRootItem());
926 void wxGenericDirCtrl::CollapseTree()
928 wxTreeItemIdValue cookie
;
929 wxTreeItemId child
= m_treeCtrl
->GetFirstChild(m_rootId
, cookie
);
933 child
= m_treeCtrl
->GetNextChild(m_rootId
, cookie
);
937 // Find the child that matches the first part of 'path'.
938 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
939 // then the child for /usr is returned.
940 wxTreeItemId
wxGenericDirCtrl::FindChild(wxTreeItemId parentId
, const wxString
& path
, bool& done
)
942 wxString
path2(path
);
944 // Make sure all separators are as per the current platform
945 path2
.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH
));
946 path2
.Replace(wxT("/"), wxString(wxFILE_SEP_PATH
));
948 // Append a separator to foil bogus substring matching
949 path2
+= wxString(wxFILE_SEP_PATH
);
951 // In MSW or PM, case is not significant
952 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
956 wxTreeItemIdValue cookie
;
957 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
958 while (childId
.IsOk())
960 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
962 if (data
&& !data
->m_path
.empty())
964 wxString
childPath(data
->m_path
);
965 if (!wxEndsWithPathSeparator(childPath
))
966 childPath
+= wxString(wxFILE_SEP_PATH
);
968 // In MSW and PM, case is not significant
969 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
970 childPath
.MakeLower();
973 if (childPath
.Len() <= path2
.Len())
975 wxString path3
= path2
.Mid(0, childPath
.Len());
976 if (childPath
== path3
)
978 if (path3
.Len() == path2
.Len())
987 childId
= m_treeCtrl
->GetNextChild(parentId
, cookie
);
989 wxTreeItemId invalid
;
993 // Try to expand as much of the given path as possible,
994 // and select the given tree item.
995 bool wxGenericDirCtrl::ExpandPath(const wxString
& path
)
998 wxTreeItemId id
= FindChild(m_rootId
, path
, done
);
999 wxTreeItemId lastId
= id
; // The last non-zero id
1000 while (id
.IsOk() && !done
)
1004 id
= FindChild(id
, path
, done
);
1011 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(lastId
);
1014 m_treeCtrl
->Expand(lastId
);
1016 if ((GetWindowStyle() & wxDIRCTRL_SELECT_FIRST
) && data
->m_isDir
)
1018 // Find the first file in this directory
1019 wxTreeItemIdValue cookie
;
1020 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(lastId
, cookie
);
1021 bool selectedChild
= false;
1022 while (childId
.IsOk())
1024 data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
1026 if (data
&& data
->m_path
!= wxEmptyString
&& !data
->m_isDir
)
1028 m_treeCtrl
->SelectItem(childId
);
1029 m_treeCtrl
->EnsureVisible(childId
);
1030 selectedChild
= true;
1033 childId
= m_treeCtrl
->GetNextChild(lastId
, cookie
);
1037 m_treeCtrl
->SelectItem(lastId
);
1038 m_treeCtrl
->EnsureVisible(lastId
);
1043 m_treeCtrl
->SelectItem(lastId
);
1044 m_treeCtrl
->EnsureVisible(lastId
);
1050 wxString
wxGenericDirCtrl::GetPath() const
1052 wxTreeItemId id
= m_treeCtrl
->GetSelection();
1055 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1056 return data
->m_path
;
1059 return wxEmptyString
;
1062 wxString
wxGenericDirCtrl::GetFilePath() const
1064 wxTreeItemId id
= m_treeCtrl
->GetSelection();
1067 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1069 return wxEmptyString
;
1071 return data
->m_path
;
1074 return wxEmptyString
;
1077 void wxGenericDirCtrl::SetPath(const wxString
& path
)
1079 m_defaultPath
= path
;
1086 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId id
, int dirFlags
, wxArrayString
& filenames
)
1088 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1090 // This may take a longish time. Go to busy cursor
1095 wxString search
,path
,filename
;
1097 wxString
dirName(data
->m_path
);
1099 #if defined(__WXMSW__) || defined(__OS2__)
1100 if (dirName
.Last() == ':')
1101 dirName
+= wxString(wxFILE_SEP_PATH
);
1105 wxString eachFilename
;
1112 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, dirFlags
))
1116 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
1118 filenames
.Add(eachFilename
);
1121 while (d
.GetNext(& eachFilename
)) ;
1127 void wxGenericDirCtrl::SetFilterIndex(int n
)
1129 m_currentFilter
= n
;
1132 if (ExtractWildcard(m_filter
, n
, f
, d
))
1133 m_currentFilterStr
= f
;
1136 m_currentFilterStr
= wxT("*");
1138 m_currentFilterStr
= wxT("*.*");
1142 void wxGenericDirCtrl::SetFilter(const wxString
& filter
)
1147 if (ExtractWildcard(m_filter
, m_currentFilter
, f
, d
))
1148 m_currentFilterStr
= f
;
1151 m_currentFilterStr
= wxT("*");
1153 m_currentFilterStr
= wxT("*.*");
1157 // Extract description and actual filter from overall filter string
1158 bool wxGenericDirCtrl::ExtractWildcard(const wxString
& filterStr
, int n
, wxString
& filter
, wxString
& description
)
1160 wxArrayString filters
, descriptions
;
1161 int count
= wxParseCommonDialogsFilter(filterStr
, descriptions
, filters
);
1162 if (count
> 0 && n
< count
)
1164 filter
= filters
[n
];
1165 description
= descriptions
[n
];
1172 #if WXWIN_COMPATIBILITY_2_4
1173 // Parses the global filter, returning the number of filters.
1174 // Returns 0 if none or if there's a problem.
1175 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpg"
1176 int wxGenericDirCtrl::ParseFilter(const wxString
& filterStr
, wxArrayString
& filters
, wxArrayString
& descriptions
)
1178 return wxParseCommonDialogsFilter(filterStr
, descriptions
, filters
);
1180 #endif // WXWIN_COMPATIBILITY_2_4
1182 void wxGenericDirCtrl::DoResize()
1184 wxSize sz
= GetClientSize();
1185 int verticalSpacing
= 3;
1189 if (m_filterListCtrl
)
1192 // For some reason, this is required in order for the
1193 // correct control height to always be returned, rather
1194 // than the drop-down list height which is sometimes returned.
1195 wxSize oldSize
= m_filterListCtrl
->GetSize();
1196 m_filterListCtrl
->SetSize(wxDefaultCoord
,
1200 wxSIZE_USE_EXISTING
);
1201 m_filterListCtrl
->SetSize(wxDefaultCoord
,
1205 wxSIZE_USE_EXISTING
);
1207 filterSz
= m_filterListCtrl
->GetSize();
1208 sz
.y
-= (filterSz
.y
+ verticalSpacing
);
1210 m_treeCtrl
->SetSize(0, 0, sz
.x
, sz
.y
);
1211 if (m_filterListCtrl
)
1213 m_filterListCtrl
->SetSize(0, sz
.y
+ verticalSpacing
, sz
.x
, filterSz
.y
);
1214 // Don't know why, but this needs refreshing after a resize (wxMSW)
1215 m_filterListCtrl
->Refresh();
1221 void wxGenericDirCtrl::OnSize(wxSizeEvent
& WXUNUSED(event
))
1226 wxTreeItemId
wxGenericDirCtrl::AppendItem (const wxTreeItemId
& parent
,
1227 const wxString
& text
,
1228 int image
, int selectedImage
,
1229 wxTreeItemData
* data
)
1231 wxTreeCtrl
*treeCtrl
= GetTreeCtrl ();
1233 wxASSERT (treeCtrl
);
1237 return treeCtrl
->AppendItem (parent
, text
, image
, selectedImage
, data
);
1241 return wxTreeItemId();
1246 //-----------------------------------------------------------------------------
1247 // wxDirFilterListCtrl
1248 //-----------------------------------------------------------------------------
1250 IMPLEMENT_CLASS(wxDirFilterListCtrl
, wxChoice
)
1252 BEGIN_EVENT_TABLE(wxDirFilterListCtrl
, wxChoice
)
1253 EVT_CHOICE(wxID_ANY
, wxDirFilterListCtrl::OnSelFilter
)
1256 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl
* parent
, const wxWindowID id
,
1262 return wxChoice::Create(parent
, id
, pos
, size
, 0, NULL
, style
);
1265 void wxDirFilterListCtrl::Init()
1270 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent
& WXUNUSED(event
))
1272 int sel
= GetSelection();
1274 wxString currentPath
= m_dirCtrl
->GetPath();
1276 m_dirCtrl
->SetFilterIndex(sel
);
1278 // If the filter has changed, the view is out of date, so
1279 // collapse the tree.
1280 m_dirCtrl
->ReCreateTree();
1282 // Try to restore the selection, or at least the directory
1283 m_dirCtrl
->ExpandPath(currentPath
);
1286 void wxDirFilterListCtrl::FillFilterList(const wxString
& filter
, int defaultFilter
)
1289 wxArrayString descriptions
, filters
;
1290 size_t n
= (size_t) wxParseCommonDialogsFilter(filter
, descriptions
, filters
);
1292 if (n
> 0 && defaultFilter
< (int) n
)
1294 for (size_t i
= 0; i
< n
; i
++)
1295 Append(descriptions
[i
]);
1296 SetSelection(defaultFilter
);
1299 #endif // wxUSE_DIRDLG
1301 #if wxUSE_DIRDLG || wxUSE_FILEDLG
1303 // ----------------------------------------------------------------------------
1304 // wxFileIconsTable icons
1305 // ----------------------------------------------------------------------------
1308 /* Computer (c) Julian Smart */
1309 static const char * file_icons_tbl_computer_xpm
[] = {
1310 /* columns rows colors chars-per-pixel */
1372 #endif // GTK+ < 2.4
1374 // ----------------------------------------------------------------------------
1375 // wxFileIconsTable & friends
1376 // ----------------------------------------------------------------------------
1378 // global instance of a wxFileIconsTable
1379 wxFileIconsTable
* wxTheFileIconsTable
= (wxFileIconsTable
*)NULL
;
1381 // A module to allow icons table cleanup
1383 class wxFileIconsTableModule
: public wxModule
1385 DECLARE_DYNAMIC_CLASS(wxFileIconsTableModule
)
1387 wxFileIconsTableModule() {}
1388 bool OnInit() { wxTheFileIconsTable
= new wxFileIconsTable
; return true; }
1391 if (wxTheFileIconsTable
)
1393 delete wxTheFileIconsTable
;
1394 wxTheFileIconsTable
= NULL
;
1399 IMPLEMENT_DYNAMIC_CLASS(wxFileIconsTableModule
, wxModule
)
1401 class wxFileIconEntry
: public wxObject
1404 wxFileIconEntry(int i
) { id
= i
; }
1409 wxFileIconsTable::wxFileIconsTable()
1412 m_smallImageList
= NULL
;
1415 wxFileIconsTable::~wxFileIconsTable()
1419 WX_CLEAR_HASH_TABLE(*m_HashTable
);
1422 if (m_smallImageList
) delete m_smallImageList
;
1425 // delayed initialization - wait until first use (wxArtProv not created yet)
1426 void wxFileIconsTable::Create()
1428 wxCHECK_RET(!m_smallImageList
&& !m_HashTable
, wxT("creating icons twice"));
1429 m_HashTable
= new wxHashTable(wxKEY_STRING
);
1430 m_smallImageList
= new wxImageList(16, 16);
1433 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER
,
1437 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER_OPEN
,
1442 // GTK24 uses this icon in the file open dialog
1443 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_HARDDISK
,
1447 m_smallImageList
->Add(wxIcon(file_icons_tbl_computer_xpm
));
1450 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_HARDDISK
,
1454 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_CDROM
,
1458 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FLOPPY
,
1462 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_REMOVABLE
,
1466 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE
,
1470 if (GetIconID(wxEmptyString
, _T("application/x-executable")) == file
)
1472 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE
,
1475 delete m_HashTable
->Get(_T("exe"));
1476 m_HashTable
->Delete(_T("exe"));
1477 m_HashTable
->Put(_T("exe"), new wxFileIconEntry(executable
));
1479 /* else put into list by GetIconID
1480 (KDE defines application/x-executable for *.exe and has nice icon)
1484 wxImageList
*wxFileIconsTable::GetSmallImageList()
1486 if (!m_smallImageList
)
1489 return m_smallImageList
;
1492 #if wxUSE_MIMETYPE && wxUSE_IMAGE
1493 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
1494 // one icon and we won't resize it
1496 static wxBitmap
CreateAntialiasedBitmap(const wxImage
& img
)
1498 const unsigned int size
= 16;
1500 wxImage
smallimg (size
, size
);
1501 unsigned char *p1
, *p2
, *ps
;
1502 unsigned char mr
= img
.GetMaskRed(),
1503 mg
= img
.GetMaskGreen(),
1504 mb
= img
.GetMaskBlue();
1507 unsigned sr
, sg
, sb
, smask
;
1509 p1
= img
.GetData(), p2
= img
.GetData() + 3 * size
*2, ps
= smallimg
.GetData();
1510 smallimg
.SetMaskColour(mr
, mr
, mr
);
1512 for (y
= 0; y
< size
; y
++)
1514 for (x
= 0; x
< size
; x
++)
1516 sr
= sg
= sb
= smask
= 0;
1517 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1518 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1521 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1522 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1525 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1526 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1529 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1530 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1535 ps
[0] = ps
[1] = ps
[2] = mr
;
1538 ps
[0] = (unsigned char)(sr
>> 2);
1539 ps
[1] = (unsigned char)(sg
>> 2);
1540 ps
[2] = (unsigned char)(sb
>> 2);
1544 p1
+= size
*2 * 3, p2
+= size
*2 * 3;
1547 return wxBitmap(smallimg
);
1550 // This function is currently not unused anymore
1552 // finds empty borders and return non-empty area of image:
1553 static wxImage
CutEmptyBorders(const wxImage
& img
)
1555 unsigned char mr
= img
.GetMaskRed(),
1556 mg
= img
.GetMaskGreen(),
1557 mb
= img
.GetMaskBlue();
1558 unsigned char *dt
= img
.GetData(), *dttmp
;
1559 unsigned w
= img
.GetWidth(), h
= img
.GetHeight();
1561 unsigned top
, bottom
, left
, right
, i
;
1564 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
1565 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = false; break;}
1567 for (empt
= true, top
= 0; empt
&& top
< h
; top
++)
1570 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1573 for (empt
= true, bottom
= h
-1; empt
&& bottom
> top
; bottom
--)
1575 MK_DTTMP(0, bottom
);
1576 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1579 for (empt
= true, left
= 0; empt
&& left
< w
; left
++)
1582 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1585 for (empt
= true, right
= w
-1; empt
&& right
> left
; right
--)
1588 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1591 top
--, left
--, bottom
++, right
++;
1593 return img
.GetSubImage(wxRect(left
, top
, right
- left
+ 1, bottom
- top
+ 1));
1597 #endif // wxUSE_MIMETYPE
1599 int wxFileIconsTable::GetIconID(const wxString
& extension
, const wxString
& mime
)
1601 if (!m_smallImageList
)
1605 if (!extension
.empty())
1607 wxFileIconEntry
*entry
= (wxFileIconEntry
*) m_HashTable
->Get(extension
);
1608 if (entry
) return (entry
-> id
);
1611 wxFileType
*ft
= (mime
.empty()) ?
1612 wxTheMimeTypesManager
-> GetFileTypeFromExtension(extension
) :
1613 wxTheMimeTypesManager
-> GetFileTypeFromMimeType(mime
);
1615 wxIconLocation iconLoc
;
1620 if ( ft
&& ft
->GetIcon(&iconLoc
) )
1622 ic
= wxIcon( iconLoc
);
1631 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1636 bmp
.CopyFromIcon(ic
);
1641 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1645 const unsigned int size
= 16;
1647 int id
= m_smallImageList
->GetImageCount();
1648 if ((bmp
.GetWidth() == (int) size
) && (bmp
.GetHeight() == (int) size
))
1650 m_smallImageList
->Add(bmp
);
1655 wxImage img
= bmp
.ConvertToImage();
1657 if ((img
.GetWidth() != size
*2) || (img
.GetHeight() != size
*2))
1658 // m_smallImageList->Add(CreateAntialiasedBitmap(CutEmptyBorders(img).Rescale(size*2, size*2)));
1659 m_smallImageList
->Add(CreateAntialiasedBitmap(img
.Rescale(size
*2, size
*2)));
1661 m_smallImageList
->Add(CreateAntialiasedBitmap(img
));
1663 #endif // wxUSE_IMAGE
1665 m_HashTable
->Put(extension
, new wxFileIconEntry(id
));
1668 #else // !wxUSE_MIMETYPE
1671 if (extension
== wxT("exe"))
1675 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
1678 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG