1 /////////////////////////////////////////////////////////////////////////////
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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
13 #pragma implementation "dirctrlg.h"
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
23 #if wxUSE_DIRDLG || wxUSE_FILEDLG
25 #include "wx/generic/dirctrlg.h"
26 #include "wx/module.h"
28 #include "wx/button.h"
29 #include "wx/layout.h"
30 #include "wx/msgdlg.h"
31 #include "wx/textctrl.h"
32 #include "wx/textdlg.h"
33 #include "wx/filefn.h"
34 #include "wx/cmndata.h"
35 #include "wx/gdicmn.h"
37 #include "wx/imaglist.h"
41 #include "wx/tokenzr.h"
43 #include "wx/settings.h"
44 #include "wx/artprov.h"
46 #include "wx/mimetype.h"
48 #include "wx/choice.h"
51 #include "wx/statline.h"
54 #if defined(__WXMAC__)
55 #include "wx/mac/private.h" // includes mac headers
60 #include "wx/msw/winundef.h"
62 // FIXME - Mingw32 1.0 has both _getdrive() and _chdrive(). For now, let's assume
63 // older releases don't, but it should be verified and the checks modified
65 #if !defined(__GNUWIN32__) || (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
66 #if !defined(__WXWINCE__)
75 #if defined(__OS2__) || defined(__DOS__)
85 extern bool wxIsDriveAvailable(const wxString
& dirName
);
88 #if defined(__WXMAC__)
89 # include "MoreFilesX.h"
96 // If compiled under Windows, this macro can cause problems
101 // ----------------------------------------------------------------------------
102 // wxGetAvailableDrives, for WINDOWS, DOS, OS2, MAC, UNIX (returns "/")
103 // ----------------------------------------------------------------------------
105 size_t wxGetAvailableDrives(wxArrayString
&paths
, wxArrayString
&names
, wxArrayInt
&icon_ids
)
107 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
110 // No logical drives; return "\"
111 paths
.Add(wxT("\\"));
112 names
.Add(wxT("\\"));
113 icon_ids
.Add(wxFileIconsTable::computer
);
114 #elif defined(__WIN32__)
115 wxChar driveBuffer
[256];
116 size_t n
= (size_t) GetLogicalDriveStrings(255, driveBuffer
);
121 path
.Printf(wxT("%c:\\"), driveBuffer
[i
]);
122 name
.Printf(wxT("%c:"), driveBuffer
[i
]);
125 int driveType
= ::GetDriveType(path
);
128 case DRIVE_REMOVABLE
:
129 if (path
== wxT("a:\\") || path
== wxT("b:\\"))
130 imageId
= wxFileIconsTable::floppy
;
132 imageId
= wxFileIconsTable::removeable
;
135 imageId
= wxFileIconsTable::cdrom
;
140 imageId
= wxFileIconsTable::drive
;
146 icon_ids
.Add(imageId
);
148 while (driveBuffer
[i
] != wxT('\0'))
151 if (driveBuffer
[i
] == wxT('\0'))
154 #elif defined(__OS2__)
156 ULONG ulDriveNum
= 0;
157 ULONG ulDriveMap
= 0;
158 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
164 if (ulDriveMap
& ( 1 << i
))
167 path
.Printf(wxT("%c:\\"), 'A' + i
);
168 name
.Printf(wxT("%c:"), 'A' + i
);
171 if (path
== wxT("A:\\") || path
== wxT("B:\\"))
172 imageId
= wxFileIconsTable::floppy
;
174 imageId
= wxFileIconsTable::drive
;
177 icon_ids
.Add(imageId
);
182 #else // !__WIN32__, !__OS2__
185 /* If we can switch to the drive, it exists. */
186 for( drive
= 1; drive
<= 26; drive
++ )
189 path
.Printf(wxT("%c:\\"), (char) (drive
+ 'a' - 1));
190 name
.Printf(wxT("%c:"), (char) (drive
+ 'A' - 1));
192 if (wxIsDriveAvailable(path
))
196 icon_ids
.Add((drive
<= 2) ? wxFileIconsTable::floppy
: wxFileIconsTable::drive
);
199 #endif // __WIN32__/!__WIN32__
201 #elif defined(__WXMAC__)
203 ItemCount volumeIndex
= 1;
206 while( noErr
== err
)
208 HFSUniStr255 volumeName
;
210 FSVolumeInfo volumeInfo
;
211 err
= FSGetVolumeInfo(0, volumeIndex
, NULL
, kFSVolInfoFlags
, &volumeInfo
, &volumeName
, &fsRef
);
214 wxString path
= wxMacFSRefToPath( &fsRef
) ;
215 wxString name
= wxMacHFSUniStrToString( &volumeName
) ;
217 if ( (volumeInfo
.flags
& kFSVolFlagSoftwareLockedMask
) || (volumeInfo
.flags
& kFSVolFlagHardwareLockedMask
) )
219 icon_ids
.Add(wxFileIconsTable::cdrom
);
223 icon_ids
.Add(wxFileIconsTable::drive
);
225 // todo other removable
233 #elif defined(__UNIX__)
236 icon_ids
.Add(wxFileIconsTable::computer
);
238 #error "Unsupported platform in wxGenericDirCtrl!"
240 wxASSERT_MSG( (paths
.GetCount() == names
.GetCount()), wxT("The number of paths and their human readable names should be equal in number."));
241 wxASSERT_MSG( (paths
.GetCount() == icon_ids
.GetCount()), wxT("Wrong number of icons for available drives."));
242 return paths
.GetCount();
245 // ----------------------------------------------------------------------------
246 // wxIsDriveAvailable
247 // ----------------------------------------------------------------------------
251 bool wxIsDriveAvailable(const wxString
& dirName
)
253 // FIXME_MGL - this method leads to hang up under Watcom for some reason
255 if ( dirName
.Len() == 3 && dirName
[1u] == wxT(':') )
257 wxString
dirNameLower(dirName
.Lower());
258 // VS: always return true for removable media, since Win95 doesn't
259 // like it when MS-DOS app accesses empty floppy drive
260 return (dirNameLower
[0u] == wxT('a') ||
261 dirNameLower
[0u] == wxT('b') ||
262 wxPathExists(dirNameLower
));
269 #elif defined(__WINDOWS__) || defined(__OS2__)
271 int setdrive(int drive
)
276 #elif defined(__GNUWIN32__) && \
277 (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
278 return _chdrive(drive
);
282 if (drive
< 1 || drive
> 31)
284 newdrive
[0] = (wxChar
)(wxT('A') + drive
- 1);
285 newdrive
[1] = wxT(':');
287 newdrive
[2] = wxT('\\');
288 newdrive
[3] = wxT('\0');
290 newdrive
[2] = wxT('\0');
292 #if defined(__WXMSW__)
293 if (::SetCurrentDirectory(newdrive
))
295 // VA doesn't know what LPSTR is and has its own set
296 if (!DosSetCurrentDir((PSZ
)newdrive
))
304 bool wxIsDriveAvailable(const wxString
& dirName
)
307 wxUnusedVar(dirName
);
311 UINT errorMode
= SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOOPENFILEERRORBOX
);
315 // Check if this is a root directory and if so,
316 // whether the drive is available.
317 if (dirName
.Len() == 3 && dirName
[(size_t)1] == wxT(':'))
319 wxString
dirNameLower(dirName
.Lower());
320 #if defined(__GNUWIN32__) && !(defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
321 success
= wxPathExists(dirNameLower
);
324 // Avoid changing to drive since no media may be inserted.
325 if (dirNameLower
[(size_t)0] == 'a' || dirNameLower
[(size_t)0] == 'b')
328 int currentDrive
= _getdrive();
329 int thisDrive
= (int) (dirNameLower
[(size_t)0] - 'a' + 1) ;
330 int err
= setdrive( thisDrive
) ;
331 setdrive( currentDrive
);
340 (void) SetErrorMode(errorMode
);
346 #endif // __WINDOWS__ || __OS2__
348 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG
354 // Function which is called by quick sort. We want to override the default wxArrayString behaviour,
355 // and sort regardless of case.
356 static int wxCMPFUNC_CONV
wxDirCtrlStringCompareFunction(const wxString
& strFirst
, const wxString
& strSecond
)
358 return strFirst
.CmpNoCase(strSecond
);
361 //-----------------------------------------------------------------------------
363 //-----------------------------------------------------------------------------
365 wxDirItemData::wxDirItemData(const wxString
& path
, const wxString
& name
,
370 /* Insert logic to detect hidden files here
371 * In UnixLand we just check whether the first char is a dot
372 * For FileNameFromPath read LastDirNameInThisPath ;-) */
373 // m_isHidden = (bool)(wxFileNameFromPath(*m_path)[0] == '.');
375 m_isExpanded
= false;
379 void wxDirItemData::SetNewDirName(const wxString
& path
)
382 m_name
= wxFileNameFromPath(path
);
385 bool wxDirItemData::HasSubDirs() const
393 if ( !dir
.Open(m_path
) )
397 return dir
.HasSubDirs();
400 bool wxDirItemData::HasFiles(const wxString
& WXUNUSED(spec
)) const
408 if ( !dir
.Open(m_path
) )
412 return dir
.HasFiles();
415 //-----------------------------------------------------------------------------
417 //-----------------------------------------------------------------------------
420 #if wxUSE_EXTENDED_RTTI
421 WX_DEFINE_FLAGS( wxGenericDirCtrlStyle
)
423 wxBEGIN_FLAGS( wxGenericDirCtrlStyle
)
424 // new style border flags, we put them first to
425 // use them for streaming out
426 wxFLAGS_MEMBER(wxBORDER_SIMPLE
)
427 wxFLAGS_MEMBER(wxBORDER_SUNKEN
)
428 wxFLAGS_MEMBER(wxBORDER_DOUBLE
)
429 wxFLAGS_MEMBER(wxBORDER_RAISED
)
430 wxFLAGS_MEMBER(wxBORDER_STATIC
)
431 wxFLAGS_MEMBER(wxBORDER_NONE
)
433 // old style border flags
434 wxFLAGS_MEMBER(wxSIMPLE_BORDER
)
435 wxFLAGS_MEMBER(wxSUNKEN_BORDER
)
436 wxFLAGS_MEMBER(wxDOUBLE_BORDER
)
437 wxFLAGS_MEMBER(wxRAISED_BORDER
)
438 wxFLAGS_MEMBER(wxSTATIC_BORDER
)
439 wxFLAGS_MEMBER(wxBORDER
)
441 // standard window styles
442 wxFLAGS_MEMBER(wxTAB_TRAVERSAL
)
443 wxFLAGS_MEMBER(wxCLIP_CHILDREN
)
444 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW
)
445 wxFLAGS_MEMBER(wxWANTS_CHARS
)
446 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE
)
447 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB
)
448 wxFLAGS_MEMBER(wxVSCROLL
)
449 wxFLAGS_MEMBER(wxHSCROLL
)
451 wxFLAGS_MEMBER(wxDIRCTRL_DIR_ONLY
)
452 wxFLAGS_MEMBER(wxDIRCTRL_3D_INTERNAL
)
453 wxFLAGS_MEMBER(wxDIRCTRL_SELECT_FIRST
)
454 wxFLAGS_MEMBER(wxDIRCTRL_SHOW_FILTERS
)
456 wxEND_FLAGS( wxGenericDirCtrlStyle
)
458 IMPLEMENT_DYNAMIC_CLASS_XTI(wxGenericDirCtrl
, wxControl
,"wx/dirctrl.h")
460 wxBEGIN_PROPERTIES_TABLE(wxGenericDirCtrl
)
461 wxHIDE_PROPERTY( Children
)
462 wxPROPERTY( DefaultPath
, wxString
, SetDefaultPath
, GetDefaultPath
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
463 wxPROPERTY( Filter
, wxString
, SetFilter
, GetFilter
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
464 wxPROPERTY( DefaultFilter
, int , SetFilterIndex
, GetFilterIndex
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
465 wxPROPERTY_FLAGS( WindowStyle
, wxGenericDirCtrlStyle
, long, SetWindowStyleFlag
, GetWindowStyleFlag
, EMPTY_MACROVALUE
, 0, wxT("Helpstring"), wxT("group") )
466 wxEND_PROPERTIES_TABLE()
468 wxBEGIN_HANDLERS_TABLE(wxGenericDirCtrl
)
469 wxEND_HANDLERS_TABLE()
471 wxCONSTRUCTOR_8( wxGenericDirCtrl
, wxWindow
* , Parent
, wxWindowID
, Id
, wxString
, DefaultPath
,
472 wxPoint
, Position
, wxSize
, Size
, long , WindowStyle
, wxString
, Filter
, int , DefaultFilter
)
474 IMPLEMENT_DYNAMIC_CLASS(wxGenericDirCtrl
, wxControl
)
477 BEGIN_EVENT_TABLE(wxGenericDirCtrl
, wxControl
)
478 EVT_TREE_ITEM_EXPANDING (wxID_TREECTRL
, wxGenericDirCtrl::OnExpandItem
)
479 EVT_TREE_ITEM_COLLAPSED (wxID_TREECTRL
, wxGenericDirCtrl::OnCollapseItem
)
480 EVT_TREE_BEGIN_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnBeginEditItem
)
481 EVT_TREE_END_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnEndEditItem
)
482 EVT_SIZE (wxGenericDirCtrl::OnSize
)
485 wxGenericDirCtrl::wxGenericDirCtrl(void)
490 void wxGenericDirCtrl::ExpandRoot()
492 ExpandDir(m_rootId
); // automatically expand first level
494 // Expand and select the default path
495 if (!m_defaultPath
.empty())
497 ExpandPath(m_defaultPath
);
502 // On Unix, there's only one node under the (hidden) root node. It
503 // represents the / path, so the user would always have to expand it;
504 // let's do it ourselves
505 ExpandPath( wxT("/") );
510 bool wxGenericDirCtrl::Create(wxWindow
*parent
,
516 const wxString
& filter
,
518 const wxString
& name
)
520 if (!wxControl::Create(parent
, id
, pos
, size
, style
, wxDefaultValidator
, name
))
523 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE
));
527 long treeStyle
= wxTR_HAS_BUTTONS
| wxTR_HIDE_ROOT
;
530 treeStyle
|= wxTR_NO_LINES
;
533 if (style
& wxDIRCTRL_EDIT_LABELS
)
534 treeStyle
|= wxTR_EDIT_LABELS
;
536 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
537 treeStyle
|= wxNO_BORDER
;
539 treeStyle
|= wxBORDER_SUNKEN
;
541 long filterStyle
= 0;
542 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
543 filterStyle
|= wxNO_BORDER
;
545 filterStyle
|= wxBORDER_SUNKEN
;
547 m_treeCtrl
= CreateTreeCtrl(this, wxID_TREECTRL
,
548 wxPoint(0,0), GetClientSize(), treeStyle
);
550 if (!filter
.empty() && (style
& wxDIRCTRL_SHOW_FILTERS
))
551 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
, wxDefaultPosition
, wxDefaultSize
, filterStyle
);
556 if (m_filter
.empty())
560 m_filter
= wxT("*.*");
563 SetFilterIndex(defaultFilter
);
565 if (m_filterListCtrl
)
566 m_filterListCtrl
->FillFilterList(filter
, defaultFilter
);
568 m_treeCtrl
->SetImageList(wxTheFileIconsTable
->GetSmallImageList());
570 m_showHidden
= false;
571 wxDirItemData
* rootData
= new wxDirItemData(wxEmptyString
, wxEmptyString
, true);
575 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
576 rootName
= _("Computer");
578 rootName
= _("Sections");
581 m_rootId
= m_treeCtrl
->AddRoot( rootName
, 3, -1, rootData
);
582 m_treeCtrl
->SetItemHasChildren(m_rootId
);
592 wxGenericDirCtrl::~wxGenericDirCtrl()
596 void wxGenericDirCtrl::Init()
598 m_showHidden
= false;
600 m_currentFilterStr
= wxEmptyString
; // Default: any file
602 m_filterListCtrl
= NULL
;
605 wxTreeCtrl
* wxGenericDirCtrl::CreateTreeCtrl(wxWindow
*parent
, wxWindowID id
, const wxPoint
& pos
, const wxSize
& size
, long treeStyle
)
607 return new wxTreeCtrl(parent
, id
, pos
, size
, treeStyle
);
610 void wxGenericDirCtrl::ShowHidden( bool show
)
614 wxString path
= GetPath();
620 wxGenericDirCtrl::AddSection(const wxString
& path
, const wxString
& name
, int imageId
)
622 wxDirItemData
*dir_item
= new wxDirItemData(path
,name
,true);
624 wxTreeItemId id
= AppendItem( m_rootId
, name
, imageId
, -1, dir_item
);
626 m_treeCtrl
->SetItemHasChildren(id
);
631 void wxGenericDirCtrl::SetupSections()
633 wxArrayString paths
, names
;
636 size_t n
, count
= wxGetAvailableDrives(paths
, names
, icons
);
639 wxString home
= wxGetHomeDir();
640 AddSection( home
, _("Home directory"), 1);
641 home
+= wxT("/Desktop");
642 AddSection( home
, _("Desktop"), 1);
645 for (n
= 0; n
< count
; n
++)
646 AddSection(paths
[n
], names
[n
], icons
[n
]);
649 void wxGenericDirCtrl::OnBeginEditItem(wxTreeEvent
&event
)
651 // don't rename the main entry "Sections"
652 if (event
.GetItem() == m_rootId
)
658 // don't rename the individual sections
659 if (m_treeCtrl
->GetItemParent( event
.GetItem() ) == m_rootId
)
666 void wxGenericDirCtrl::OnEndEditItem(wxTreeEvent
&event
)
668 if ((event
.GetLabel().empty()) ||
669 (event
.GetLabel() == _(".")) ||
670 (event
.GetLabel() == _("..")) ||
671 (event
.GetLabel().Find(wxT('/')) != wxNOT_FOUND
) ||
672 (event
.GetLabel().Find(wxT('\\')) != wxNOT_FOUND
) ||
673 (event
.GetLabel().Find(wxT('|')) != wxNOT_FOUND
))
675 wxMessageDialog
dialog(this, _("Illegal directory name."), _("Error"), wxOK
| wxICON_ERROR
);
681 wxTreeItemId id
= event
.GetItem();
682 wxDirItemData
*data
= (wxDirItemData
*)m_treeCtrl
->GetItemData( id
);
685 wxString
new_name( wxPathOnly( data
->m_path
) );
686 new_name
+= wxString(wxFILE_SEP_PATH
);
687 new_name
+= event
.GetLabel();
691 if (wxFileExists(new_name
))
693 wxMessageDialog
dialog(this, _("File name exists already."), _("Error"), wxOK
| wxICON_ERROR
);
698 if (wxRenameFile(data
->m_path
,new_name
))
700 data
->SetNewDirName( new_name
);
704 wxMessageDialog
dialog(this, _("Operation not permitted."), _("Error"), wxOK
| wxICON_ERROR
);
710 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent
&event
)
712 wxTreeItemId parentId
= event
.GetItem();
714 // VS: this is needed because the event handler is called from wxTreeCtrl
715 // ctor when wxTR_HIDE_ROOT was specified
717 if (!m_rootId
.IsOk())
719 m_rootId
= m_treeCtrl
->GetRootItem();
724 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent
&event
)
726 CollapseDir(event
.GetItem());
729 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId
)
733 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
734 if (!data
->m_isExpanded
)
737 data
->m_isExpanded
= false;
738 wxTreeItemIdValue cookie
;
739 /* Workaround because DeleteChildren has disapeared (why?) and
740 * CollapseAndReset doesn't work as advertised (deletes parent too) */
741 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
744 m_treeCtrl
->Delete(child
);
745 /* Not GetNextChild below, because the cookie mechanism can't
746 * handle disappearing children! */
747 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
749 if (parentId
!= m_treeCtrl
->GetRootItem())
750 m_treeCtrl
->Collapse(parentId
);
753 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId
)
755 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
757 if (data
->m_isExpanded
)
760 data
->m_isExpanded
= true;
762 if (parentId
== m_treeCtrl
->GetRootItem())
770 wxString search
,path
,filename
;
772 wxString
dirName(data
->m_path
);
774 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
775 // Check if this is a root directory and if so,
776 // whether the drive is avaiable.
777 if (!wxIsDriveAvailable(dirName
))
779 data
->m_isExpanded
= false;
780 //wxMessageBox(wxT("Sorry, this drive is not available."));
785 // This may take a longish time. Go to busy cursor
788 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
789 if (dirName
.Last() == ':')
790 dirName
+= wxString(wxFILE_SEP_PATH
);
794 wxArrayString filenames
;
797 wxString eachFilename
;
804 int style
= wxDIR_DIRS
;
805 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
806 if (d
.GetFirst(& eachFilename
, wxEmptyString
, style
))
810 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
812 dirs
.Add(eachFilename
);
815 while (d
.GetNext(&eachFilename
));
818 dirs
.Sort(wxDirCtrlStringCompareFunction
);
820 // Now do the filenames -- but only if we're allowed to
821 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
829 int style
= wxDIR_FILES
;
830 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
831 // Process each filter (ex: "JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg")
832 wxStringTokenizer strTok
;
834 strTok
.SetString(m_currentFilterStr
,wxT(";"));
835 while(strTok
.HasMoreTokens())
837 curFilter
= strTok
.GetNextToken();
838 if (d
.GetFirst(& eachFilename
, curFilter
, style
))
842 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
844 filenames
.Add(eachFilename
);
847 while (d
.GetNext(& eachFilename
));
851 filenames
.Sort(wxDirCtrlStringCompareFunction
);
854 // Add the sorted dirs
856 for (i
= 0; i
< dirs
.Count(); i
++)
858 wxString
eachFilename(dirs
[i
]);
860 if (!wxEndsWithPathSeparator(path
))
861 path
+= wxString(wxFILE_SEP_PATH
);
862 path
+= eachFilename
;
864 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,true);
865 wxTreeItemId id
= AppendItem( parentId
, eachFilename
,
866 wxFileIconsTable::folder
, -1, dir_item
);
867 m_treeCtrl
->SetItemImage( id
, wxFileIconsTable::folder_open
,
868 wxTreeItemIcon_Expanded
);
870 // Has this got any children? If so, make it expandable.
871 // (There are two situations when a dir has children: either it
872 // has subdirectories or it contains files that weren't filtered
873 // out. The latter only applies to dirctrl with files.)
874 if ( dir_item
->HasSubDirs() ||
875 (((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0) &&
876 dir_item
->HasFiles(m_currentFilterStr
)) )
878 m_treeCtrl
->SetItemHasChildren(id
);
882 // Add the sorted filenames
883 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
885 for (i
= 0; i
< filenames
.Count(); i
++)
887 wxString
eachFilename(filenames
[i
]);
889 if (!wxEndsWithPathSeparator(path
))
890 path
+= wxString(wxFILE_SEP_PATH
);
891 path
+= eachFilename
;
892 //path = dirName + wxString(wxT("/")) + eachFilename;
893 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,false);
894 int image_id
= wxFileIconsTable::file
;
895 if (eachFilename
.Find(wxT('.')) != wxNOT_FOUND
)
896 image_id
= wxTheFileIconsTable
->GetIconID(eachFilename
.AfterLast(wxT('.')));
897 (void) AppendItem( parentId
, eachFilename
, image_id
, -1, dir_item
);
902 void wxGenericDirCtrl::ReCreateTree()
904 CollapseDir(m_treeCtrl
->GetRootItem());
908 void wxGenericDirCtrl::CollapseTree()
910 wxTreeItemIdValue cookie
;
911 wxTreeItemId child
= m_treeCtrl
->GetFirstChild(m_rootId
, cookie
);
915 child
= m_treeCtrl
->GetNextChild(m_rootId
, cookie
);
919 // Find the child that matches the first part of 'path'.
920 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
921 // then the child for /usr is returned.
922 wxTreeItemId
wxGenericDirCtrl::FindChild(wxTreeItemId parentId
, const wxString
& path
, bool& done
)
924 wxString
path2(path
);
926 // Make sure all separators are as per the current platform
927 path2
.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH
));
928 path2
.Replace(wxT("/"), wxString(wxFILE_SEP_PATH
));
930 // Append a separator to foil bogus substring matching
931 path2
+= wxString(wxFILE_SEP_PATH
);
933 // In MSW or PM, case is not significant
934 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
938 wxTreeItemIdValue cookie
;
939 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
940 while (childId
.IsOk())
942 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
944 if (data
&& !data
->m_path
.empty())
946 wxString
childPath(data
->m_path
);
947 if (!wxEndsWithPathSeparator(childPath
))
948 childPath
+= wxString(wxFILE_SEP_PATH
);
950 // In MSW and PM, case is not significant
951 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
952 childPath
.MakeLower();
955 if (childPath
.Len() <= path2
.Len())
957 wxString path3
= path2
.Mid(0, childPath
.Len());
958 if (childPath
== path3
)
960 if (path3
.Len() == path2
.Len())
969 childId
= m_treeCtrl
->GetNextChild(parentId
, cookie
);
971 wxTreeItemId invalid
;
975 // Try to expand as much of the given path as possible,
976 // and select the given tree item.
977 bool wxGenericDirCtrl::ExpandPath(const wxString
& path
)
980 wxTreeItemId id
= FindChild(m_rootId
, path
, done
);
981 wxTreeItemId lastId
= id
; // The last non-zero id
982 while (id
.IsOk() && !done
)
986 id
= FindChild(id
, path
, done
);
992 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(lastId
);
995 m_treeCtrl
->Expand(lastId
);
997 if ((GetWindowStyle() & wxDIRCTRL_SELECT_FIRST
) && data
->m_isDir
)
999 // Find the first file in this directory
1000 wxTreeItemIdValue cookie
;
1001 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(lastId
, cookie
);
1002 bool selectedChild
= false;
1003 while (childId
.IsOk())
1005 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
1007 if (data
&& data
->m_path
!= wxEmptyString
&& !data
->m_isDir
)
1009 m_treeCtrl
->SelectItem(childId
);
1010 m_treeCtrl
->EnsureVisible(childId
);
1011 selectedChild
= true;
1014 childId
= m_treeCtrl
->GetNextChild(lastId
, cookie
);
1018 m_treeCtrl
->SelectItem(lastId
);
1019 m_treeCtrl
->EnsureVisible(lastId
);
1024 m_treeCtrl
->SelectItem(lastId
);
1025 m_treeCtrl
->EnsureVisible(lastId
);
1034 wxString
wxGenericDirCtrl::GetPath() const
1036 wxTreeItemId id
= m_treeCtrl
->GetSelection();
1039 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1040 return data
->m_path
;
1043 return wxEmptyString
;
1046 wxString
wxGenericDirCtrl::GetFilePath() const
1048 wxTreeItemId id
= m_treeCtrl
->GetSelection();
1051 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1053 return wxEmptyString
;
1055 return data
->m_path
;
1058 return wxEmptyString
;
1061 void wxGenericDirCtrl::SetPath(const wxString
& path
)
1063 m_defaultPath
= path
;
1070 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId id
, int dirFlags
, wxArrayString
& filenames
)
1072 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1074 // This may take a longish time. Go to busy cursor
1079 wxString search
,path
,filename
;
1081 wxString
dirName(data
->m_path
);
1083 #if defined(__WXMSW__) || defined(__OS2__)
1084 if (dirName
.Last() == ':')
1085 dirName
+= wxString(wxFILE_SEP_PATH
);
1089 wxString eachFilename
;
1096 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, dirFlags
))
1100 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
1102 filenames
.Add(eachFilename
);
1105 while (d
.GetNext(& eachFilename
)) ;
1111 void wxGenericDirCtrl::SetFilterIndex(int n
)
1113 m_currentFilter
= n
;
1116 if (ExtractWildcard(m_filter
, n
, f
, d
))
1117 m_currentFilterStr
= f
;
1120 m_currentFilterStr
= wxT("*");
1122 m_currentFilterStr
= wxT("*.*");
1126 void wxGenericDirCtrl::SetFilter(const wxString
& filter
)
1131 if (ExtractWildcard(m_filter
, m_currentFilter
, f
, d
))
1132 m_currentFilterStr
= f
;
1135 m_currentFilterStr
= wxT("*");
1137 m_currentFilterStr
= wxT("*.*");
1141 // Extract description and actual filter from overall filter string
1142 bool wxGenericDirCtrl::ExtractWildcard(const wxString
& filterStr
, int n
, wxString
& filter
, wxString
& description
)
1144 wxArrayString filters
, descriptions
;
1145 int count
= wxParseCommonDialogsFilter(filterStr
, descriptions
, filters
);
1146 if (count
> 0 && n
< count
)
1148 filter
= filters
[n
];
1149 description
= descriptions
[n
];
1156 #if WXWIN_COMPATIBILITY_2_4
1157 // Parses the global filter, returning the number of filters.
1158 // Returns 0 if none or if there's a problem.
1159 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpg"
1160 int wxGenericDirCtrl::ParseFilter(const wxString
& filterStr
, wxArrayString
& filters
, wxArrayString
& descriptions
)
1162 return wxParseCommonDialogsFilter(filterStr
, descriptions
, filters
);
1164 #endif // WXWIN_COMPATIBILITY_2_4
1166 void wxGenericDirCtrl::DoResize()
1168 wxSize sz
= GetClientSize();
1169 int verticalSpacing
= 3;
1173 if (m_filterListCtrl
)
1176 // For some reason, this is required in order for the
1177 // correct control height to always be returned, rather
1178 // than the drop-down list height which is sometimes returned.
1179 wxSize oldSize
= m_filterListCtrl
->GetSize();
1180 m_filterListCtrl
->SetSize(wxDefaultCoord
,
1184 wxSIZE_USE_EXISTING
);
1185 m_filterListCtrl
->SetSize(wxDefaultCoord
,
1189 wxSIZE_USE_EXISTING
);
1191 filterSz
= m_filterListCtrl
->GetSize();
1192 sz
.y
-= (filterSz
.y
+ verticalSpacing
);
1194 m_treeCtrl
->SetSize(0, 0, sz
.x
, sz
.y
);
1195 if (m_filterListCtrl
)
1197 m_filterListCtrl
->SetSize(0, sz
.y
+ verticalSpacing
, sz
.x
, filterSz
.y
);
1198 // Don't know why, but this needs refreshing after a resize (wxMSW)
1199 m_filterListCtrl
->Refresh();
1205 void wxGenericDirCtrl::OnSize(wxSizeEvent
& WXUNUSED(event
))
1210 wxTreeItemId
wxGenericDirCtrl::AppendItem (const wxTreeItemId
& parent
,
1211 const wxString
& text
,
1212 int image
, int selectedImage
,
1213 wxTreeItemData
* data
)
1215 wxTreeCtrl
*treeCtrl
= GetTreeCtrl ();
1217 wxASSERT (treeCtrl
);
1221 return treeCtrl
->AppendItem (parent
, text
, image
, selectedImage
, data
);
1225 return wxTreeItemId();
1230 //-----------------------------------------------------------------------------
1231 // wxDirFilterListCtrl
1232 //-----------------------------------------------------------------------------
1234 IMPLEMENT_CLASS(wxDirFilterListCtrl
, wxChoice
)
1236 BEGIN_EVENT_TABLE(wxDirFilterListCtrl
, wxChoice
)
1237 EVT_CHOICE(wxID_ANY
, wxDirFilterListCtrl::OnSelFilter
)
1240 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl
* parent
, const wxWindowID id
,
1246 return wxChoice::Create(parent
, id
, pos
, size
, 0, NULL
, style
);
1249 void wxDirFilterListCtrl::Init()
1254 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent
& WXUNUSED(event
))
1256 int sel
= GetSelection();
1258 wxString currentPath
= m_dirCtrl
->GetPath();
1260 m_dirCtrl
->SetFilterIndex(sel
);
1262 // If the filter has changed, the view is out of date, so
1263 // collapse the tree.
1264 m_dirCtrl
->ReCreateTree();
1266 // Try to restore the selection, or at least the directory
1267 m_dirCtrl
->ExpandPath(currentPath
);
1270 void wxDirFilterListCtrl::FillFilterList(const wxString
& filter
, int defaultFilter
)
1273 wxArrayString descriptions
, filters
;
1274 size_t n
= (size_t) wxParseCommonDialogsFilter(filter
, descriptions
, filters
);
1276 if (n
> 0 && defaultFilter
< (int) n
)
1278 for (size_t i
= 0; i
< n
; i
++)
1279 Append(descriptions
[i
]);
1280 SetSelection(defaultFilter
);
1283 #endif // wxUSE_DIRDLG
1285 #if wxUSE_DIRDLG || wxUSE_FILEDLG
1287 // ----------------------------------------------------------------------------
1288 // wxFileIconsTable icons
1289 // ----------------------------------------------------------------------------
1293 static const char * file_icons_tbl_computer_xpm
[] = {
1318 #endif // GTK+ < 2.4
1320 // ----------------------------------------------------------------------------
1321 // wxFileIconsTable & friends
1322 // ----------------------------------------------------------------------------
1324 // global instance of a wxFileIconsTable
1325 wxFileIconsTable
* wxTheFileIconsTable
= (wxFileIconsTable
*)NULL
;
1327 // A module to allow icons table cleanup
1329 class wxFileIconsTableModule
: public wxModule
1331 DECLARE_DYNAMIC_CLASS(wxFileIconsTableModule
)
1333 wxFileIconsTableModule() {}
1334 bool OnInit() { wxTheFileIconsTable
= new wxFileIconsTable
; return true; }
1337 if (wxTheFileIconsTable
)
1339 delete wxTheFileIconsTable
;
1340 wxTheFileIconsTable
= NULL
;
1345 IMPLEMENT_DYNAMIC_CLASS(wxFileIconsTableModule
, wxModule
)
1347 class wxFileIconEntry
: public wxObject
1350 wxFileIconEntry(int i
) { id
= i
; }
1355 wxFileIconsTable::wxFileIconsTable()
1358 m_smallImageList
= NULL
;
1361 wxFileIconsTable::~wxFileIconsTable()
1365 WX_CLEAR_HASH_TABLE(*m_HashTable
);
1368 if (m_smallImageList
) delete m_smallImageList
;
1371 // delayed initialization - wait until first use (wxArtProv not created yet)
1372 void wxFileIconsTable::Create()
1374 wxCHECK_RET(!m_smallImageList
&& !m_HashTable
, wxT("creating icons twice"));
1375 m_HashTable
= new wxHashTable(wxKEY_STRING
);
1376 m_smallImageList
= new wxImageList(16, 16);
1379 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER
,
1383 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER_OPEN
,
1388 // GTK24 uses this icon in the file open dialog
1389 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_HARDDISK
,
1393 m_smallImageList
->Add(wxIcon(file_icons_tbl_computer_xpm
));
1396 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_HARDDISK
,
1400 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_CDROM
,
1404 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FLOPPY
,
1408 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_REMOVABLE
,
1412 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE
,
1416 if (GetIconID(wxEmptyString
, _T("application/x-executable")) == file
)
1418 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE
,
1421 delete m_HashTable
->Get(_T("exe"));
1422 m_HashTable
->Delete(_T("exe"));
1423 m_HashTable
->Put(_T("exe"), new wxFileIconEntry(executable
));
1425 /* else put into list by GetIconID
1426 (KDE defines application/x-executable for *.exe and has nice icon)
1430 wxImageList
*wxFileIconsTable::GetSmallImageList()
1432 if (!m_smallImageList
)
1435 return m_smallImageList
;
1438 #if wxUSE_MIMETYPE && wxUSE_IMAGE
1439 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
1440 // one icon and we won't resize it
1442 static wxBitmap
CreateAntialiasedBitmap(const wxImage
& img
)
1444 const unsigned int size
= 16;
1446 wxImage
smallimg (size
, size
);
1447 unsigned char *p1
, *p2
, *ps
;
1448 unsigned char mr
= img
.GetMaskRed(),
1449 mg
= img
.GetMaskGreen(),
1450 mb
= img
.GetMaskBlue();
1453 unsigned sr
, sg
, sb
, smask
;
1455 p1
= img
.GetData(), p2
= img
.GetData() + 3 * size
*2, ps
= smallimg
.GetData();
1456 smallimg
.SetMaskColour(mr
, mr
, mr
);
1458 for (y
= 0; y
< size
; y
++)
1460 for (x
= 0; x
< size
; x
++)
1462 sr
= sg
= sb
= smask
= 0;
1463 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1464 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1467 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1468 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1471 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1472 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1475 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1476 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1481 ps
[0] = ps
[1] = ps
[2] = mr
;
1484 ps
[0] = (unsigned char)(sr
>> 2);
1485 ps
[1] = (unsigned char)(sg
>> 2);
1486 ps
[2] = (unsigned char)(sb
>> 2);
1490 p1
+= size
*2 * 3, p2
+= size
*2 * 3;
1493 return wxBitmap(smallimg
);
1496 // This function is currently not unused anymore
1498 // finds empty borders and return non-empty area of image:
1499 static wxImage
CutEmptyBorders(const wxImage
& img
)
1501 unsigned char mr
= img
.GetMaskRed(),
1502 mg
= img
.GetMaskGreen(),
1503 mb
= img
.GetMaskBlue();
1504 unsigned char *dt
= img
.GetData(), *dttmp
;
1505 unsigned w
= img
.GetWidth(), h
= img
.GetHeight();
1507 unsigned top
, bottom
, left
, right
, i
;
1510 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
1511 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = false; break;}
1513 for (empt
= true, top
= 0; empt
&& top
< h
; top
++)
1516 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1519 for (empt
= true, bottom
= h
-1; empt
&& bottom
> top
; bottom
--)
1521 MK_DTTMP(0, bottom
);
1522 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1525 for (empt
= true, left
= 0; empt
&& left
< w
; left
++)
1528 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1531 for (empt
= true, right
= w
-1; empt
&& right
> left
; right
--)
1534 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1537 top
--, left
--, bottom
++, right
++;
1539 return img
.GetSubImage(wxRect(left
, top
, right
- left
+ 1, bottom
- top
+ 1));
1543 #endif // wxUSE_MIMETYPE
1545 int wxFileIconsTable::GetIconID(const wxString
& extension
, const wxString
& mime
)
1547 if (!m_smallImageList
)
1551 if (!extension
.empty())
1553 wxFileIconEntry
*entry
= (wxFileIconEntry
*) m_HashTable
->Get(extension
);
1554 if (entry
) return (entry
-> id
);
1557 wxFileType
*ft
= (mime
.empty()) ?
1558 wxTheMimeTypesManager
-> GetFileTypeFromExtension(extension
) :
1559 wxTheMimeTypesManager
-> GetFileTypeFromMimeType(mime
);
1561 wxIconLocation iconLoc
;
1566 if ( ft
&& ft
->GetIcon(&iconLoc
) )
1568 ic
= wxIcon( iconLoc
);
1577 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1582 bmp
.CopyFromIcon(ic
);
1587 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1591 const unsigned int size
= 16;
1593 int id
= m_smallImageList
->GetImageCount();
1594 if ((bmp
.GetWidth() == (int) size
) && (bmp
.GetHeight() == (int) size
))
1596 m_smallImageList
->Add(bmp
);
1601 wxImage img
= bmp
.ConvertToImage();
1603 if ((img
.GetWidth() != size
*2) || (img
.GetHeight() != size
*2))
1604 // m_smallImageList->Add(CreateAntialiasedBitmap(CutEmptyBorders(img).Rescale(size*2, size*2)));
1605 m_smallImageList
->Add(CreateAntialiasedBitmap(img
.Rescale(size
*2, size
*2)));
1607 m_smallImageList
->Add(CreateAntialiasedBitmap(img
));
1609 #endif // wxUSE_IMAGE
1611 m_HashTable
->Put(extension
, new wxFileIconEntry(id
));
1614 #else // !wxUSE_MIMETYPE
1617 if (extension
== wxT("exe"))
1621 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
1624 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG