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
61 // FIXME - Mingw32 1.0 has both _getdrive() and _chdrive(). For now, let's assume
62 // older releases don't, but it should be verified and the checks modified
64 #if !defined(__GNUWIN32__) || (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
65 #if !defined(__WXWINCE__)
74 #if defined(__OS2__) || defined(__DOS__)
84 extern bool wxIsDriveAvailable(const wxString
& dirName
);
87 #if defined(__WXMAC__)
89 # include "MoreFilesX.h"
91 # include "MoreFilesExtras.h"
99 // If compiled under Windows, this macro can cause problems
104 // ----------------------------------------------------------------------------
105 // wxGetAvailableDrives, for WINDOWS, DOS, OS2, MAC, UNIX (returns "/")
106 // ----------------------------------------------------------------------------
108 size_t wxGetAvailableDrives(wxArrayString
&paths
, wxArrayString
&names
, wxArrayInt
&icon_ids
)
110 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
113 // No logical drives; return "\"
114 paths
.Add(wxT("\\"));
115 names
.Add(wxT("\\"));
117 #elif defined(__WIN32__)
118 wxChar driveBuffer
[256];
119 size_t n
= (size_t) GetLogicalDriveStrings(255, driveBuffer
);
124 path
.Printf(wxT("%c:\\"), driveBuffer
[i
]);
125 name
.Printf(wxT("%c:"), driveBuffer
[i
]);
128 int driveType
= ::GetDriveType(path
);
131 case DRIVE_REMOVABLE
:
132 if (path
== wxT("a:\\") || path
== wxT("b:\\"))
133 imageId
= wxFileIconsTable::floppy
;
135 imageId
= wxFileIconsTable::removeable
;
138 imageId
= wxFileIconsTable::cdrom
;
143 imageId
= wxFileIconsTable::drive
;
149 icon_ids
.Add(imageId
);
151 while (driveBuffer
[i
] != wxT('\0'))
154 if (driveBuffer
[i
] == wxT('\0'))
157 #elif defined(__OS2__)
159 ULONG ulDriveNum
= 0;
160 ULONG ulDriveMap
= 0;
161 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
167 if (ulDriveMap
& ( 1 << i
))
170 path
.Printf(wxT("%c:\\"), 'A' + i
);
171 name
.Printf(wxT("%c:"), 'A' + i
);
174 if (path
== wxT("A:\\") || path
== wxT("B:\\"))
175 imageId
= wxFileIconsTable::floppy
;
177 imageId
= wxFileIconsTable::drive
;
180 icon_ids
.Add(imageId
);
185 #else // !__WIN32__, !__OS2__
188 /* If we can switch to the drive, it exists. */
189 for( drive
= 1; drive
<= 26; drive
++ )
192 path
.Printf(wxT("%c:\\"), (char) (drive
+ 'a' - 1));
193 name
.Printf(wxT("%c:"), (char) (drive
+ 'A' - 1));
195 if (wxIsDriveAvailable(path
))
199 icon_ids
.Add((drive
<= 2) ? wxFileIconsTable::floppy
: wxFileIconsTable::drive
);
202 #endif // __WIN32__/!__WIN32__
204 #elif defined(__WXMAC__)
207 ItemCount theVolCount
;
208 char thePath
[FILENAME_MAX
];
210 if (FSGetMountedVolumes(&theVolRefs
, &theVolCount
) == noErr
) {
212 ::HLock( (Handle
)theVolRefs
) ;
213 for (index
= 0; index
< theVolCount
; ++index
) {
214 // get the POSIX path associated with the FSRef
215 if ( FSRefMakePath(&((*theVolRefs
)[index
]),
216 (UInt8
*)thePath
, sizeof(thePath
)) != noErr
) {
219 // add path separator at end if necessary
220 wxString
path( thePath
, wxConvLocal
) ;
221 if (path
.Last() != wxFILE_SEP_PATH
) {
222 path
+= wxFILE_SEP_PATH
;
224 // get Mac volume name for display
225 FSVolumeRefNum vRefNum
;
226 HFSUniStr255 volumeName
;
228 if ( FSGetVRefNum(&((*theVolRefs
)[index
]), &vRefNum
) != noErr
) {
231 if ( FSGetVInfo(vRefNum
, &volumeName
, NULL
, NULL
) != noErr
) {
234 // get C string from Unicode HFS name
235 // see: http://developer.apple.com/carbon/tipsandtricks.html
236 CFStringRef cfstr
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
239 // Do something with str
240 char *cstr
= NewPtr(CFStringGetLength(cfstr
) + 1);
241 if (( cstr
== NULL
) ||
242 !CFStringGetCString(cfstr
, cstr
, CFStringGetLength(cfstr
) + 1,
243 kCFStringEncodingMacRoman
))
248 wxString
name( cstr
, wxConvLocal
);
252 GetVolParmsInfoBuffer volParmsInfo
;
254 if ( FSGetVolParms(vRefNum
, sizeof(volParmsInfo
), &volParmsInfo
, &actualSize
) != noErr
) {
261 if ( VolIsEjectable(&volParmsInfo
) )
262 icon_ids
.Add(wxFileIconsTable::cdrom
);
264 icon_ids
.Add(wxFileIconsTable::drive
);
266 ::HUnlock( (Handle
)theVolRefs
);
267 ::DisposeHandle( (Handle
)theVolRefs
);
274 short actualCount
= 0 ;
275 if (OnLine(&volume
, 1, &actualCount
, &index
) != noErr
|| actualCount
==0)
280 wxString name
= wxMacFSSpec2MacFilename( &volume
);
281 paths
.Add(name
+ wxFILE_SEP_PATH
);
283 icon_ids
.Add(wxFileIconsTable::drive
);
287 #elif defined(__UNIX__)
290 icon_ids
.Add(wxFileIconsTable::computer
);
292 #error "Unsupported platform in wxGenericDirCtrl!"
294 return paths
.GetCount();
297 // ----------------------------------------------------------------------------
298 // wxIsDriveAvailable
299 // ----------------------------------------------------------------------------
303 bool wxIsDriveAvailable(const wxString
& dirName
)
305 // FIXME_MGL - this method leads to hang up under Watcom for some reason
307 if ( dirName
.Len() == 3 && dirName
[1u] == wxT(':') )
309 wxString
dirNameLower(dirName
.Lower());
310 // VS: always return true for removable media, since Win95 doesn't
311 // like it when MS-DOS app accesses empty floppy drive
312 return (dirNameLower
[0u] == wxT('a') ||
313 dirNameLower
[0u] == wxT('b') ||
314 wxPathExists(dirNameLower
));
321 #elif defined(__WINDOWS__) || defined(__OS2__)
323 int setdrive(int drive
)
327 #elif defined(__GNUWIN32__) && \
328 (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
329 return _chdrive(drive
);
333 if (drive
< 1 || drive
> 31)
335 newdrive
[0] = (wxChar
)(wxT('A') + drive
- 1);
336 newdrive
[1] = wxT(':');
338 newdrive
[2] = wxT('\\');
339 newdrive
[3] = wxT('\0');
341 newdrive
[2] = wxT('\0');
343 #if defined(__WXMSW__)
344 if (::SetCurrentDirectory(newdrive
))
346 // VA doesn't know what LPSTR is and has its own set
347 if (!DosSetCurrentDir((PSZ
)newdrive
))
355 bool wxIsDriveAvailable(const wxString
& dirName
)
361 UINT errorMode
= SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOOPENFILEERRORBOX
);
365 // Check if this is a root directory and if so,
366 // whether the drive is available.
367 if (dirName
.Len() == 3 && dirName
[(size_t)1] == wxT(':'))
369 wxString
dirNameLower(dirName
.Lower());
370 #if defined(__GNUWIN32__) && !(defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
371 success
= wxPathExists(dirNameLower
);
374 // Avoid changing to drive since no media may be inserted.
375 if (dirNameLower
[(size_t)0] == 'a' || dirNameLower
[(size_t)0] == 'b')
378 int currentDrive
= _getdrive();
379 int thisDrive
= (int) (dirNameLower
[(size_t)0] - 'a' + 1) ;
380 int err
= setdrive( thisDrive
) ;
381 setdrive( currentDrive
);
390 (void) SetErrorMode(errorMode
);
396 #endif // __WINDOWS__ || __OS2__
398 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG
404 // Function which is called by quick sort. We want to override the default wxArrayString behaviour,
405 // and sort regardless of case.
406 static int wxCMPFUNC_CONV
wxDirCtrlStringCompareFunction(wxString
* strFirst
, wxString
* strSecond
)
408 return strFirst
->CmpNoCase(*strSecond
);
411 //-----------------------------------------------------------------------------
413 //-----------------------------------------------------------------------------
415 wxDirItemData::wxDirItemData(const wxString
& path
, const wxString
& name
,
420 /* Insert logic to detect hidden files here
421 * In UnixLand we just check whether the first char is a dot
422 * For FileNameFromPath read LastDirNameInThisPath ;-) */
423 // m_isHidden = (bool)(wxFileNameFromPath(*m_path)[0] == '.');
425 m_isExpanded
= false;
429 wxDirItemData::~wxDirItemData()
433 void wxDirItemData::SetNewDirName(const wxString
& path
)
436 m_name
= wxFileNameFromPath(path
);
439 bool wxDirItemData::HasSubDirs() const
441 if (m_path
.IsEmpty())
447 if ( !dir
.Open(m_path
) )
451 return dir
.HasSubDirs();
454 bool wxDirItemData::HasFiles(const wxString
& WXUNUSED(spec
)) const
456 if (m_path
.IsEmpty())
462 if ( !dir
.Open(m_path
) )
466 return dir
.HasFiles();
469 //-----------------------------------------------------------------------------
471 //-----------------------------------------------------------------------------
474 #if wxUSE_EXTENDED_RTTI
475 WX_DEFINE_FLAGS( wxGenericDirCtrlStyle
)
477 wxBEGIN_FLAGS( wxGenericDirCtrlStyle
)
478 // new style border flags, we put them first to
479 // use them for streaming out
480 wxFLAGS_MEMBER(wxBORDER_SIMPLE
)
481 wxFLAGS_MEMBER(wxBORDER_SUNKEN
)
482 wxFLAGS_MEMBER(wxBORDER_DOUBLE
)
483 wxFLAGS_MEMBER(wxBORDER_RAISED
)
484 wxFLAGS_MEMBER(wxBORDER_STATIC
)
485 wxFLAGS_MEMBER(wxBORDER_NONE
)
487 // old style border flags
488 wxFLAGS_MEMBER(wxSIMPLE_BORDER
)
489 wxFLAGS_MEMBER(wxSUNKEN_BORDER
)
490 wxFLAGS_MEMBER(wxDOUBLE_BORDER
)
491 wxFLAGS_MEMBER(wxRAISED_BORDER
)
492 wxFLAGS_MEMBER(wxSTATIC_BORDER
)
493 wxFLAGS_MEMBER(wxBORDER
)
495 // standard window styles
496 wxFLAGS_MEMBER(wxTAB_TRAVERSAL
)
497 wxFLAGS_MEMBER(wxCLIP_CHILDREN
)
498 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW
)
499 wxFLAGS_MEMBER(wxWANTS_CHARS
)
500 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE
)
501 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB
)
502 wxFLAGS_MEMBER(wxVSCROLL
)
503 wxFLAGS_MEMBER(wxHSCROLL
)
505 wxFLAGS_MEMBER(wxDIRCTRL_DIR_ONLY
)
506 wxFLAGS_MEMBER(wxDIRCTRL_3D_INTERNAL
)
507 wxFLAGS_MEMBER(wxDIRCTRL_SELECT_FIRST
)
508 wxFLAGS_MEMBER(wxDIRCTRL_SHOW_FILTERS
)
510 wxEND_FLAGS( wxGenericDirCtrlStyle
)
512 IMPLEMENT_DYNAMIC_CLASS_XTI(wxGenericDirCtrl
, wxControl
,"wx/dirctrl.h")
514 wxBEGIN_PROPERTIES_TABLE(wxGenericDirCtrl
)
515 wxHIDE_PROPERTY( Children
)
516 wxPROPERTY( DefaultPath
, wxString
, SetDefaultPath
, GetDefaultPath
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
517 wxPROPERTY( Filter
, wxString
, SetFilter
, GetFilter
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
518 wxPROPERTY( DefaultFilter
, int , SetFilterIndex
, GetFilterIndex
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
519 wxPROPERTY_FLAGS( WindowStyle
, wxGenericDirCtrlStyle
, long, SetWindowStyleFlag
, GetWindowStyleFlag
, EMPTY_MACROVALUE
, 0, wxT("Helpstring"), wxT("group") )
520 wxEND_PROPERTIES_TABLE()
522 wxBEGIN_HANDLERS_TABLE(wxGenericDirCtrl
)
523 wxEND_HANDLERS_TABLE()
525 wxCONSTRUCTOR_8( wxGenericDirCtrl
, wxWindow
* , Parent
, wxWindowID
, Id
, wxString
, DefaultPath
,
526 wxPoint
, Position
, wxSize
, Size
, long , WindowStyle
, wxString
, Filter
, int , DefaultFilter
)
528 IMPLEMENT_DYNAMIC_CLASS(wxGenericDirCtrl
, wxControl
)
531 BEGIN_EVENT_TABLE(wxGenericDirCtrl
, wxControl
)
532 EVT_TREE_ITEM_EXPANDING (wxID_TREECTRL
, wxGenericDirCtrl::OnExpandItem
)
533 EVT_TREE_ITEM_COLLAPSED (wxID_TREECTRL
, wxGenericDirCtrl::OnCollapseItem
)
534 EVT_TREE_BEGIN_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnBeginEditItem
)
535 EVT_TREE_END_LABEL_EDIT (wxID_TREECTRL
, wxGenericDirCtrl::OnEndEditItem
)
536 EVT_SIZE (wxGenericDirCtrl::OnSize
)
539 wxGenericDirCtrl::wxGenericDirCtrl(void)
544 bool wxGenericDirCtrl::Create(wxWindow
*parent
,
550 const wxString
& filter
,
552 const wxString
& name
)
554 if (!wxControl::Create(parent
, id
, pos
, size
, style
, wxDefaultValidator
, name
))
557 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE
));
561 long treeStyle
= wxTR_HAS_BUTTONS
| wxTR_HIDE_ROOT
;
563 if (style
& wxDIRCTRL_EDIT_LABELS
)
564 treeStyle
|= wxTR_EDIT_LABELS
;
566 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
567 treeStyle
|= wxNO_BORDER
;
569 treeStyle
|= wxBORDER_SUNKEN
;
571 long filterStyle
= 0;
572 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
573 filterStyle
|= wxNO_BORDER
;
575 filterStyle
|= wxBORDER_SUNKEN
;
577 m_treeCtrl
= new wxTreeCtrl(this, wxID_TREECTRL
,
578 wxPoint(0,0), GetClientSize(), treeStyle
);
580 if (!filter
.IsEmpty() && (style
& wxDIRCTRL_SHOW_FILTERS
))
581 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
, wxDefaultPosition
, wxDefaultSize
, filterStyle
);
586 SetFilterIndex(defaultFilter
);
588 if (m_filterListCtrl
)
589 m_filterListCtrl
->FillFilterList(filter
, defaultFilter
);
591 m_treeCtrl
->SetImageList(wxTheFileIconsTable
->GetSmallImageList());
593 m_showHidden
= false;
594 wxDirItemData
* rootData
= new wxDirItemData(wxEmptyString
, wxEmptyString
, true);
598 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
599 rootName
= _("Computer");
601 rootName
= _("Sections");
604 m_rootId
= m_treeCtrl
->AddRoot( rootName
, 3, -1, rootData
);
605 m_treeCtrl
->SetItemHasChildren(m_rootId
);
606 ExpandDir(m_rootId
); // automatically expand first level
608 // Expand and select the default path
609 if (!m_defaultPath
.IsEmpty())
610 ExpandPath(m_defaultPath
);
618 wxGenericDirCtrl::~wxGenericDirCtrl()
622 void wxGenericDirCtrl::Init()
624 m_showHidden
= false;
626 m_currentFilterStr
= wxEmptyString
; // Default: any file
628 m_filterListCtrl
= NULL
;
631 void wxGenericDirCtrl::ShowHidden( bool show
)
635 wxString path
= GetPath();
641 wxGenericDirCtrl::AddSection(const wxString
& path
, const wxString
& name
, int imageId
)
643 wxDirItemData
*dir_item
= new wxDirItemData(path
,name
,true);
645 wxTreeItemId id
= AppendItem( m_rootId
, name
, imageId
, -1, dir_item
);
647 m_treeCtrl
->SetItemHasChildren(id
);
652 void wxGenericDirCtrl::SetupSections()
654 wxArrayString paths
, names
;
657 size_t n
, count
= wxGetAvailableDrives(paths
, names
, icons
);
659 for (n
= 0; n
< count
; n
++)
661 AddSection(paths
[n
], names
[n
], icons
[n
]);
665 void wxGenericDirCtrl::OnBeginEditItem(wxTreeEvent
&event
)
667 // don't rename the main entry "Sections"
668 if (event
.GetItem() == m_rootId
)
674 // don't rename the individual sections
675 if (m_treeCtrl
->GetItemParent( event
.GetItem() ) == m_rootId
)
682 void wxGenericDirCtrl::OnEndEditItem(wxTreeEvent
&event
)
684 if ((event
.GetLabel().IsEmpty()) ||
685 (event
.GetLabel() == _(".")) ||
686 (event
.GetLabel() == _("..")) ||
687 (event
.GetLabel().Find(wxT('/')) != wxNOT_FOUND
) ||
688 (event
.GetLabel().Find(wxT('\\')) != wxNOT_FOUND
) ||
689 (event
.GetLabel().Find(wxT('|')) != wxNOT_FOUND
))
691 wxMessageDialog
dialog(this, _("Illegal directory name."), _("Error"), wxOK
| wxICON_ERROR
);
697 wxTreeItemId id
= event
.GetItem();
698 wxDirItemData
*data
= (wxDirItemData
*)m_treeCtrl
->GetItemData( id
);
701 wxString
new_name( wxPathOnly( data
->m_path
) );
702 new_name
+= wxString(wxFILE_SEP_PATH
);
703 new_name
+= event
.GetLabel();
707 if (wxFileExists(new_name
))
709 wxMessageDialog
dialog(this, _("File name exists already."), _("Error"), wxOK
| wxICON_ERROR
);
714 if (wxRenameFile(data
->m_path
,new_name
))
716 data
->SetNewDirName( new_name
);
720 wxMessageDialog
dialog(this, _("Operation not permitted."), _("Error"), wxOK
| wxICON_ERROR
);
726 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent
&event
)
728 wxTreeItemId parentId
= event
.GetItem();
730 // VS: this is needed because the event handler is called from wxTreeCtrl
731 // ctor when wxTR_HIDE_ROOT was specified
733 if (!m_rootId
.IsOk())
735 m_rootId
= m_treeCtrl
->GetRootItem();
740 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent
&event
)
742 CollapseDir(event
.GetItem());
745 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId
)
749 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
750 if (!data
->m_isExpanded
)
753 data
->m_isExpanded
= false;
754 wxTreeItemIdValue cookie
;
755 /* Workaround because DeleteChildren has disapeared (why?) and
756 * CollapseAndReset doesn't work as advertised (deletes parent too) */
757 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
760 m_treeCtrl
->Delete(child
);
761 /* Not GetNextChild below, because the cookie mechanism can't
762 * handle disappearing children! */
763 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
767 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId
)
769 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
771 if (data
->m_isExpanded
)
774 data
->m_isExpanded
= true;
776 if (parentId
== m_treeCtrl
->GetRootItem())
784 wxString search
,path
,filename
;
786 wxString
dirName(data
->m_path
);
788 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
789 // Check if this is a root directory and if so,
790 // whether the drive is avaiable.
791 if (!wxIsDriveAvailable(dirName
))
793 data
->m_isExpanded
= false;
794 //wxMessageBox(wxT("Sorry, this drive is not available."));
799 // This may take a longish time. Go to busy cursor
802 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
803 if (dirName
.Last() == ':')
804 dirName
+= wxString(wxFILE_SEP_PATH
);
808 wxArrayString filenames
;
811 wxString eachFilename
;
818 int style
= wxDIR_DIRS
;
819 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
820 if (d
.GetFirst(& eachFilename
, wxEmptyString
, style
))
824 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
826 dirs
.Add(eachFilename
);
829 while (d
.GetNext(&eachFilename
));
832 dirs
.Sort(wxDirCtrlStringCompareFunction
);
834 // Now do the filenames -- but only if we're allowed to
835 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
843 int style
= wxDIR_FILES
;
844 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
845 // Process each filter (ex: "JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg")
846 wxStringTokenizer strTok
;
848 strTok
.SetString(m_currentFilterStr
,wxT(";"));
849 while(strTok
.HasMoreTokens())
851 curFilter
= strTok
.GetNextToken();
852 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, style
))
856 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
858 filenames
.Add(eachFilename
);
861 while (d
.GetNext(& eachFilename
));
865 filenames
.Sort(wxDirCtrlStringCompareFunction
);
868 // Add the sorted dirs
870 for (i
= 0; i
< dirs
.Count(); i
++)
872 wxString
eachFilename(dirs
[i
]);
874 if (!wxEndsWithPathSeparator(path
))
875 path
+= wxString(wxFILE_SEP_PATH
);
876 path
+= eachFilename
;
878 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,true);
879 wxTreeItemId id
= AppendItem( parentId
, eachFilename
,
880 wxFileIconsTable::folder
, -1, dir_item
);
881 m_treeCtrl
->SetItemImage( id
, wxFileIconsTable::folder_open
,
882 wxTreeItemIcon_Expanded
);
884 // Has this got any children? If so, make it expandable.
885 // (There are two situations when a dir has children: either it
886 // has subdirectories or it contains files that weren't filtered
887 // out. The latter only applies to dirctrl with files.)
888 if ( dir_item
->HasSubDirs() ||
889 (((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0) &&
890 dir_item
->HasFiles(m_currentFilterStr
)) )
892 m_treeCtrl
->SetItemHasChildren(id
);
896 // Add the sorted filenames
897 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
899 for (i
= 0; i
< filenames
.Count(); i
++)
901 wxString
eachFilename(filenames
[i
]);
903 if (!wxEndsWithPathSeparator(path
))
904 path
+= wxString(wxFILE_SEP_PATH
);
905 path
+= eachFilename
;
906 //path = dirName + wxString(wxT("/")) + eachFilename;
907 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,false);
908 int image_id
= wxFileIconsTable::file
;
909 if (eachFilename
.Find(wxT('.')) != wxNOT_FOUND
)
910 image_id
= wxTheFileIconsTable
->GetIconID(eachFilename
.AfterLast(wxT('.')));
911 (void) AppendItem( parentId
, eachFilename
, image_id
, -1, dir_item
);
916 void wxGenericDirCtrl::ReCreateTree()
918 CollapseDir(m_treeCtrl
->GetRootItem());
919 ExpandDir(m_treeCtrl
->GetRootItem());
922 // Find the child that matches the first part of 'path'.
923 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
924 // then the child for /usr is returned.
925 wxTreeItemId
wxGenericDirCtrl::FindChild(wxTreeItemId parentId
, const wxString
& path
, bool& done
)
927 wxString
path2(path
);
929 // Make sure all separators are as per the current platform
930 path2
.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH
));
931 path2
.Replace(wxT("/"), wxString(wxFILE_SEP_PATH
));
933 // Append a separator to foil bogus substring matching
934 path2
+= wxString(wxFILE_SEP_PATH
);
936 // In MSW or PM, case is not significant
937 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
941 wxTreeItemIdValue cookie
;
942 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
943 while (childId
.IsOk())
945 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
947 if (data
&& !data
->m_path
.IsEmpty())
949 wxString
childPath(data
->m_path
);
950 if (!wxEndsWithPathSeparator(childPath
))
951 childPath
+= wxString(wxFILE_SEP_PATH
);
953 // In MSW and PM, case is not significant
954 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
955 childPath
.MakeLower();
958 if (childPath
.Len() <= path2
.Len())
960 wxString path3
= path2
.Mid(0, childPath
.Len());
961 if (childPath
== path3
)
963 if (path3
.Len() == path2
.Len())
972 childId
= m_treeCtrl
->GetNextChild(parentId
, cookie
);
974 wxTreeItemId invalid
;
978 // Try to expand as much of the given path as possible,
979 // and select the given tree item.
980 bool wxGenericDirCtrl::ExpandPath(const wxString
& path
)
983 wxTreeItemId id
= FindChild(m_rootId
, path
, done
);
984 wxTreeItemId lastId
= id
; // The last non-zero id
985 while (id
.IsOk() && !done
)
989 id
= FindChild(id
, path
, done
);
995 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(lastId
);
998 m_treeCtrl
->Expand(lastId
);
1000 if ((GetWindowStyle() & wxDIRCTRL_SELECT_FIRST
) && data
->m_isDir
)
1002 // Find the first file in this directory
1003 wxTreeItemIdValue cookie
;
1004 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(lastId
, cookie
);
1005 bool selectedChild
= false;
1006 while (childId
.IsOk())
1008 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
1010 if (data
&& data
->m_path
!= wxEmptyString
&& !data
->m_isDir
)
1012 m_treeCtrl
->SelectItem(childId
);
1013 m_treeCtrl
->EnsureVisible(childId
);
1014 selectedChild
= true;
1017 childId
= m_treeCtrl
->GetNextChild(lastId
, cookie
);
1021 m_treeCtrl
->SelectItem(lastId
);
1022 m_treeCtrl
->EnsureVisible(lastId
);
1027 m_treeCtrl
->SelectItem(lastId
);
1028 m_treeCtrl
->EnsureVisible(lastId
);
1037 wxString
wxGenericDirCtrl::GetPath() const
1039 wxTreeItemId id
= m_treeCtrl
->GetSelection();
1042 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1043 return data
->m_path
;
1046 return wxEmptyString
;
1049 wxString
wxGenericDirCtrl::GetFilePath() const
1051 wxTreeItemId id
= m_treeCtrl
->GetSelection();
1054 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1056 return wxEmptyString
;
1058 return data
->m_path
;
1061 return wxEmptyString
;
1064 void wxGenericDirCtrl::SetPath(const wxString
& path
)
1066 m_defaultPath
= path
;
1073 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId id
, int dirFlags
, wxArrayString
& filenames
)
1075 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
1077 // This may take a longish time. Go to busy cursor
1082 wxString search
,path
,filename
;
1084 wxString
dirName(data
->m_path
);
1086 #if defined(__WXMSW__) || defined(__OS2__)
1087 if (dirName
.Last() == ':')
1088 dirName
+= wxString(wxFILE_SEP_PATH
);
1092 wxString eachFilename
;
1099 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, dirFlags
))
1103 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
1105 filenames
.Add(eachFilename
);
1108 while (d
.GetNext(& eachFilename
)) ;
1114 void wxGenericDirCtrl::SetFilterIndex(int n
)
1116 m_currentFilter
= n
;
1119 if (ExtractWildcard(m_filter
, n
, f
, d
))
1120 m_currentFilterStr
= f
;
1122 m_currentFilterStr
= wxT("*.*");
1125 void wxGenericDirCtrl::SetFilter(const wxString
& filter
)
1130 if (ExtractWildcard(m_filter
, m_currentFilter
, f
, d
))
1131 m_currentFilterStr
= f
;
1133 m_currentFilterStr
= wxT("*.*");
1136 // Extract description and actual filter from overall filter string
1137 bool wxGenericDirCtrl::ExtractWildcard(const wxString
& filterStr
, int n
, wxString
& filter
, wxString
& description
)
1139 wxArrayString filters
, descriptions
;
1140 int count
= wxParseCommonDialogsFilter(filterStr
, descriptions
, filters
);
1141 if (count
> 0 && n
< count
)
1143 filter
= filters
[n
];
1144 description
= descriptions
[n
];
1151 #if WXWIN_COMPATIBILITY_2_4
1152 // Parses the global filter, returning the number of filters.
1153 // Returns 0 if none or if there's a problem.
1154 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpg"
1155 int wxGenericDirCtrl::ParseFilter(const wxString
& filterStr
, wxArrayString
& filters
, wxArrayString
& descriptions
)
1157 return wxParseCommonDialogsFilter(filterStr
, descriptions
, filters
);
1159 #endif // WXWIN_COMPATIBILITY_2_4
1161 void wxGenericDirCtrl::DoResize()
1163 wxSize sz
= GetClientSize();
1164 int verticalSpacing
= 3;
1168 if (m_filterListCtrl
)
1171 // For some reason, this is required in order for the
1172 // correct control height to always be returned, rather
1173 // than the drop-down list height which is sometimes returned.
1174 wxSize oldSize
= m_filterListCtrl
->GetSize();
1175 m_filterListCtrl
->SetSize(wxDefaultPosition
.x
,
1176 wxDefaultPosition
.y
,
1179 wxSIZE_USE_EXISTING
);
1180 m_filterListCtrl
->SetSize(wxDefaultPosition
.x
,
1181 wxDefaultPosition
.y
,
1184 wxSIZE_USE_EXISTING
);
1186 filterSz
= m_filterListCtrl
->GetSize();
1187 sz
.y
-= (filterSz
.y
+ verticalSpacing
);
1189 m_treeCtrl
->SetSize(0, 0, sz
.x
, sz
.y
);
1190 if (m_filterListCtrl
)
1192 m_filterListCtrl
->SetSize(0, sz
.y
+ verticalSpacing
, sz
.x
, filterSz
.y
);
1193 // Don't know why, but this needs refreshing after a resize (wxMSW)
1194 m_filterListCtrl
->Refresh();
1200 void wxGenericDirCtrl::OnSize(wxSizeEvent
& WXUNUSED(event
))
1205 wxTreeItemId
wxGenericDirCtrl::AppendItem (const wxTreeItemId
& parent
,
1206 const wxString
& text
,
1207 int image
, int selectedImage
,
1208 wxTreeItemData
* data
)
1210 wxTreeCtrl
*treeCtrl
= GetTreeCtrl ();
1212 wxASSERT (treeCtrl
);
1216 return treeCtrl
->AppendItem (parent
, text
, image
, selectedImage
, data
);
1220 return wxTreeItemId();
1225 //-----------------------------------------------------------------------------
1226 // wxDirFilterListCtrl
1227 //-----------------------------------------------------------------------------
1229 IMPLEMENT_CLASS(wxDirFilterListCtrl
, wxChoice
)
1231 BEGIN_EVENT_TABLE(wxDirFilterListCtrl
, wxChoice
)
1232 EVT_CHOICE(wxID_ANY
, wxDirFilterListCtrl::OnSelFilter
)
1235 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl
* parent
, const wxWindowID id
,
1241 return wxChoice::Create(parent
, id
, pos
, size
, 0, NULL
, style
);
1244 void wxDirFilterListCtrl::Init()
1249 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent
& WXUNUSED(event
))
1251 int sel
= GetSelection();
1253 wxString currentPath
= m_dirCtrl
->GetPath();
1255 m_dirCtrl
->SetFilterIndex(sel
);
1257 // If the filter has changed, the view is out of date, so
1258 // collapse the tree.
1259 m_dirCtrl
->ReCreateTree();
1261 // Try to restore the selection, or at least the directory
1262 m_dirCtrl
->ExpandPath(currentPath
);
1265 void wxDirFilterListCtrl::FillFilterList(const wxString
& filter
, int defaultFilter
)
1268 wxArrayString descriptions
, filters
;
1269 size_t n
= (size_t) wxParseCommonDialogsFilter(filter
, filters
, descriptions
);
1271 if (n
> 0 && defaultFilter
< (int) n
)
1273 for (size_t i
= 0; i
< n
; i
++)
1274 Append(descriptions
[i
]);
1275 SetSelection(defaultFilter
);
1278 #endif // wxUSE_DIRDLG
1280 #if wxUSE_DIRDLG || wxUSE_FILEDLG
1282 // ----------------------------------------------------------------------------
1283 // wxFileIconsTable icons
1284 // ----------------------------------------------------------------------------
1287 static const char * file_icons_tbl_folder_open_xpm
[] = {
1288 /* width height ncolors chars_per_pixel */
1316 static const char * file_icons_tbl_computer_xpm
[] = {
1343 static const char * file_icons_tbl_drive_xpm
[] = {
1370 static const char *file_icons_tbl_cdrom_xpm
[] = {
1400 static const char * file_icons_tbl_floppy_xpm
[] = {
1427 static const char * file_icons_tbl_removeable_xpm
[] = {
1453 // ----------------------------------------------------------------------------
1454 // wxFileIconsTable & friends
1455 // ----------------------------------------------------------------------------
1457 // global instance of a wxFileIconsTable
1458 wxFileIconsTable
* wxTheFileIconsTable
= (wxFileIconsTable
*)NULL
;
1460 // A module to allow icons table cleanup
1462 class wxFileIconsTableModule
: public wxModule
1464 DECLARE_DYNAMIC_CLASS(wxFileIconsTableModule
)
1466 wxFileIconsTableModule() {}
1467 bool OnInit() { wxTheFileIconsTable
= new wxFileIconsTable
; return true; }
1470 if (wxTheFileIconsTable
)
1472 delete wxTheFileIconsTable
;
1473 wxTheFileIconsTable
= NULL
;
1478 IMPLEMENT_DYNAMIC_CLASS(wxFileIconsTableModule
, wxModule
)
1480 class wxFileIconEntry
: public wxObject
1483 wxFileIconEntry(int i
) { id
= i
; }
1488 wxFileIconsTable::wxFileIconsTable()
1491 m_smallImageList
= NULL
;
1494 wxFileIconsTable::~wxFileIconsTable()
1498 WX_CLEAR_HASH_TABLE(*m_HashTable
);
1501 if (m_smallImageList
) delete m_smallImageList
;
1504 // delayed initialization - wait until first use (wxArtProv not created yet)
1505 void wxFileIconsTable::Create()
1507 wxCHECK_RET(!m_smallImageList
&& !m_HashTable
, wxT("creating icons twice"));
1508 m_HashTable
= new wxHashTable(wxKEY_STRING
);
1509 m_smallImageList
= new wxImageList(16, 16);
1512 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER
, wxART_CMN_DIALOG
));
1514 m_smallImageList
->Add(wxIcon(file_icons_tbl_folder_open_xpm
));
1516 m_smallImageList
->Add(wxIcon(file_icons_tbl_computer_xpm
));
1518 m_smallImageList
->Add(wxIcon(file_icons_tbl_drive_xpm
));
1520 m_smallImageList
->Add(wxIcon(file_icons_tbl_cdrom_xpm
));
1522 m_smallImageList
->Add(wxIcon(file_icons_tbl_floppy_xpm
));
1524 m_smallImageList
->Add(wxIcon(file_icons_tbl_removeable_xpm
));
1526 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE
, wxART_CMN_DIALOG
));
1528 if (GetIconID(wxEmptyString
, _T("application/x-executable")) == file
)
1530 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE
, wxART_CMN_DIALOG
));
1531 delete m_HashTable
->Get(_T("exe"));
1532 m_HashTable
->Delete(_T("exe"));
1533 m_HashTable
->Put(_T("exe"), new wxFileIconEntry(executable
));
1535 /* else put into list by GetIconID
1536 (KDE defines application/x-executable for *.exe and has nice icon)
1540 wxImageList
*wxFileIconsTable::GetSmallImageList()
1542 if (!m_smallImageList
)
1545 return m_smallImageList
;
1548 #if wxUSE_MIMETYPE && wxUSE_IMAGE
1549 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
1550 // one icon and we won't resize it
1552 static wxBitmap
CreateAntialiasedBitmap(const wxImage
& img
)
1554 const unsigned int size
= 16;
1556 wxImage
smallimg (size
, size
);
1557 unsigned char *p1
, *p2
, *ps
;
1558 unsigned char mr
= img
.GetMaskRed(),
1559 mg
= img
.GetMaskGreen(),
1560 mb
= img
.GetMaskBlue();
1563 unsigned sr
, sg
, sb
, smask
;
1565 p1
= img
.GetData(), p2
= img
.GetData() + 3 * size
*2, ps
= smallimg
.GetData();
1566 smallimg
.SetMaskColour(mr
, mr
, mr
);
1568 for (y
= 0; y
< size
; y
++)
1570 for (x
= 0; x
< size
; x
++)
1572 sr
= sg
= sb
= smask
= 0;
1573 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1574 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1577 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1578 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1581 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1582 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1585 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1586 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1591 ps
[0] = ps
[1] = ps
[2] = mr
;
1593 ps
[0] = sr
>> 2, ps
[1] = sg
>> 2, ps
[2] = sb
>> 2;
1596 p1
+= size
*2 * 3, p2
+= size
*2 * 3;
1599 return wxBitmap(smallimg
);
1602 // This function is currently not unused anymore
1604 // finds empty borders and return non-empty area of image:
1605 static wxImage
CutEmptyBorders(const wxImage
& img
)
1607 unsigned char mr
= img
.GetMaskRed(),
1608 mg
= img
.GetMaskGreen(),
1609 mb
= img
.GetMaskBlue();
1610 unsigned char *dt
= img
.GetData(), *dttmp
;
1611 unsigned w
= img
.GetWidth(), h
= img
.GetHeight();
1613 unsigned top
, bottom
, left
, right
, i
;
1616 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
1617 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = false; break;}
1619 for (empt
= true, top
= 0; empt
&& top
< h
; top
++)
1622 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1625 for (empt
= true, bottom
= h
-1; empt
&& bottom
> top
; bottom
--)
1627 MK_DTTMP(0, bottom
);
1628 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1631 for (empt
= true, left
= 0; empt
&& left
< w
; left
++)
1634 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1637 for (empt
= true, right
= w
-1; empt
&& right
> left
; right
--)
1640 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1643 top
--, left
--, bottom
++, right
++;
1645 return img
.GetSubImage(wxRect(left
, top
, right
- left
+ 1, bottom
- top
+ 1));
1649 #endif // wxUSE_MIMETYPE
1651 int wxFileIconsTable::GetIconID(const wxString
& extension
, const wxString
& mime
)
1653 if (!m_smallImageList
)
1657 if (!extension
.IsEmpty())
1659 wxFileIconEntry
*entry
= (wxFileIconEntry
*) m_HashTable
->Get(extension
);
1660 if (entry
) return (entry
-> id
);
1663 wxFileType
*ft
= (mime
.IsEmpty()) ?
1664 wxTheMimeTypesManager
-> GetFileTypeFromExtension(extension
) :
1665 wxTheMimeTypesManager
-> GetFileTypeFromMimeType(mime
);
1667 wxIconLocation iconLoc
;
1672 if ( ft
&& ft
->GetIcon(&iconLoc
) )
1674 ic
= wxIcon( iconLoc
.GetFileName() );
1683 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1688 bmp
.CopyFromIcon(ic
);
1693 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1697 const unsigned int size
= 16;
1699 int id
= m_smallImageList
->GetImageCount();
1700 if ((bmp
.GetWidth() == (int) size
) && (bmp
.GetHeight() == (int) size
))
1702 m_smallImageList
->Add(bmp
);
1707 wxImage img
= bmp
.ConvertToImage();
1709 if ((img
.GetWidth() != size
*2) || (img
.GetHeight() != size
*2))
1710 // m_smallImageList->Add(CreateAntialiasedBitmap(CutEmptyBorders(img).Rescale(size*2, size*2)));
1711 m_smallImageList
->Add(CreateAntialiasedBitmap(img
.Rescale(size
*2, size
*2)));
1713 m_smallImageList
->Add(CreateAntialiasedBitmap(img
));
1715 #endif // wxUSE_IMAGE
1717 m_HashTable
->Put(extension
, new wxFileIconEntry(id
));
1720 #else // !wxUSE_MIMETYPE
1722 if (extension
== wxT("exe"))
1726 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
1729 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG