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 /////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "dirctrlg.h"
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
25 #include "wx/generic/dirctrlg.h"
27 #include "wx/module.h"
29 #include "wx/button.h"
30 #include "wx/layout.h"
31 #include "wx/msgdlg.h"
32 #include "wx/textctrl.h"
33 #include "wx/textdlg.h"
34 #include "wx/filefn.h"
35 #include "wx/cmndata.h"
36 #include "wx/gdicmn.h"
38 #include "wx/imaglist.h"
42 #include "wx/tokenzr.h"
44 #include "wx/settings.h"
45 #include "wx/artprov.h"
47 #include "wx/mimetype.h"
49 #include "wx/choice.h"
52 #include "wx/statline.h"
55 #if defined(__WXMAC__)
56 #include "wx/mac/private.h" // includes mac headers
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)
82 extern bool wxIsDriveAvailable(const wxString
& dirName
);
85 #if defined(__WXMAC__)
87 # include "MoreFilesX.h"
89 # include "MoreFilesExtras.h"
97 // If compiled under Windows, this macro can cause problems
102 // ----------------------------------------------------------------------------
103 // wxGetAvailableDrives, for WINDOWS, DOS, WXPM, MAC, UNIX (returns "/")
104 // ----------------------------------------------------------------------------
106 size_t wxGetAvailableDrives(wxArrayString
&paths
, wxArrayString
&names
, wxArrayInt
&icon_ids
)
108 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
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
]);
120 int imageId
= wxFileIconsTable::drive
;
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'))
153 /* If we can switch to the drive, it exists. */
154 for( drive
= 1; drive
<= 26; drive
++ )
157 path
.Printf(wxT("%c:\\"), (char) (drive
+ 'a' - 1));
158 name
.Printf(wxT("%c:"), (char) (drive
+ 'A' - 1));
160 if (wxIsDriveAvailable(path
))
164 icon_ids
.Add((drive
<= 2) ? wxFileIconsTable::floppy
: wxFileIconsTable::drive
);
167 #endif // __WIN32__/!__WIN32__
169 #elif defined(__WXMAC__)
172 ItemCount theVolCount
;
173 char thePath
[FILENAME_MAX
];
175 if (FSGetMountedVolumes(&theVolRefs
, &theVolCount
) == noErr
) {
177 ::HLock( (Handle
)theVolRefs
) ;
178 for (index
= 0; index
< theVolCount
; ++index
) {
179 // get the POSIX path associated with the FSRef
180 if ( FSRefMakePath(&((*theVolRefs
)[index
]),
181 (UInt8
*)thePath
, sizeof(thePath
)) != noErr
) {
184 // add path separator at end if necessary
185 wxString
path( thePath
) ;
186 if (path
.Last() != wxFILE_SEP_PATH
) {
187 path
+= wxFILE_SEP_PATH
;
189 // get Mac volume name for display
190 FSVolumeRefNum vRefNum
;
191 HFSUniStr255 volumeName
;
193 if ( FSGetVRefNum(&((*theVolRefs
)[index
]), &vRefNum
) != noErr
) {
196 if ( FSGetVInfo(vRefNum
, &volumeName
, NULL
, NULL
) != noErr
) {
199 // get C string from Unicode HFS name
200 // see: http://developer.apple.com/carbon/tipsandtricks.html
201 CFStringRef cfstr
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
204 // Do something with str
205 char *cstr
= NewPtr(CFStringGetLength(cfstr
) + 1);
206 if (( cstr
== NULL
) ||
207 !CFStringGetCString(cfstr
, cstr
, CFStringGetLength(cfstr
) + 1,
208 kCFStringEncodingMacRoman
))
213 wxString
name( cstr
);
217 GetVolParmsInfoBuffer volParmsInfo
;
219 if ( FSGetVolParms(vRefNum
, sizeof(volParmsInfo
), &volParmsInfo
, &actualSize
) != noErr
) {
226 if ( VolIsEjectable(&volParmsInfo
) )
227 icon_ids
.Add(wxFileIconsTable::cdrom
);
229 icon_ids
.Add(wxFileIconsTable::drive
);
231 ::HUnlock( (Handle
)theVolRefs
);
232 ::DisposeHandle( (Handle
)theVolRefs
);
239 short actualCount
= 0 ;
240 if (OnLine(&volume
, 1, &actualCount
, &index
) != noErr
|| actualCount
==0)
245 wxString name
= wxMacFSSpec2MacFilename( &volume
);
246 paths
.Add(name
+ wxFILE_SEP_PATH
);
248 icon_ids
.Add(wxFileIconsTable::drive
);
252 #elif defined(__UNIX__)
255 icon_ids
.Add(wxFileIconsTable::computer
);
257 #error "Unsupported platform in wxGenericDirCtrl!"
259 return paths
.GetCount();
262 // ----------------------------------------------------------------------------
263 // wxIsDriveAvailable
264 // ----------------------------------------------------------------------------
268 bool wxIsDriveAvailable(const wxString
& dirName
)
270 // FIXME_MGL - this method leads to hang up under Watcom for some reason
272 if ( dirName
.Len() == 3 && dirName
[1u] == wxT(':') )
274 wxString
dirNameLower(dirName
.Lower());
275 // VS: always return TRUE for removable media, since Win95 doesn't
276 // like it when MS-DOS app accesses empty floppy drive
277 return (dirNameLower
[0u] == wxT('a') ||
278 dirNameLower
[0u] == wxT('b') ||
279 wxPathExists(dirNameLower
));
286 #elif defined(__WINDOWS__) || defined(__WXPM__)
288 int setdrive(int drive
)
290 #if defined(__GNUWIN32__) && \
291 (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
292 return _chdrive(drive
);
296 if (drive
< 1 || drive
> 31)
298 newdrive
[0] = (wxChar
)(wxT('A') + drive
- 1);
299 newdrive
[1] = wxT(':');
300 newdrive
[2] = wxT('\0');
301 #if defined(__WXMSW__)
303 if (wxSetWorkingDirectory(newdrive
))
305 if (::SetCurrentDirectory(newdrive
))
308 // VA doesn't know what LPSTR is and has its own set
309 if (DosSetCurrentDir((PSZ
)newdrive
))
317 bool wxIsDriveAvailable(const wxString
& dirName
)
320 UINT errorMode
= SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOOPENFILEERRORBOX
);
324 // Check if this is a root directory and if so,
325 // whether the drive is available.
326 if (dirName
.Len() == 3 && dirName
[(size_t)1] == wxT(':'))
328 wxString
dirNameLower(dirName
.Lower());
329 #if defined(__GNUWIN32__) && !(defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
330 success
= wxPathExists(dirNameLower
);
332 int currentDrive
= _getdrive();
333 int thisDrive
= (int) (dirNameLower
[(size_t)0] - 'a' + 1) ;
334 int err
= setdrive( thisDrive
) ;
335 setdrive( currentDrive
);
344 (void) SetErrorMode(errorMode
);
349 #endif // __WINDOWS__ || __WXPM__
351 // Function which is called by quick sort. We want to override the default wxArrayString behaviour,
352 // and sort regardless of case.
353 static int LINKAGEMODE
wxDirCtrlStringCompareFunction(const void *first
, const void *second
)
355 wxString
*strFirst
= (wxString
*)first
;
356 wxString
*strSecond
= (wxString
*)second
;
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 wxDirItemData::~wxDirItemData()
383 void wxDirItemData::SetNewDirName(const wxString
& path
)
386 m_name
= wxFileNameFromPath(path
);
389 bool wxDirItemData::HasSubDirs() const
391 if (m_path
.IsEmpty())
397 if ( !dir
.Open(m_path
) )
401 return dir
.HasSubDirs();
404 bool wxDirItemData::HasFiles(const wxString
& WXUNUSED(spec
)) const
406 if (m_path
.IsEmpty())
412 if ( !dir
.Open(m_path
) )
416 return dir
.HasFiles();
419 //-----------------------------------------------------------------------------
421 //-----------------------------------------------------------------------------
423 IMPLEMENT_DYNAMIC_CLASS(wxGenericDirCtrl
, wxControl
)
425 BEGIN_EVENT_TABLE(wxGenericDirCtrl
, wxControl
)
426 EVT_TREE_ITEM_EXPANDING (-1, wxGenericDirCtrl::OnExpandItem
)
427 EVT_TREE_ITEM_COLLAPSED (-1, wxGenericDirCtrl::OnCollapseItem
)
428 EVT_TREE_BEGIN_LABEL_EDIT (-1, wxGenericDirCtrl::OnBeginEditItem
)
429 EVT_TREE_END_LABEL_EDIT (-1, wxGenericDirCtrl::OnEndEditItem
)
430 EVT_SIZE (wxGenericDirCtrl::OnSize
)
433 wxGenericDirCtrl::wxGenericDirCtrl(void)
438 bool wxGenericDirCtrl::Create(wxWindow
*parent
,
444 const wxString
& filter
,
446 const wxString
& name
)
448 if (!wxControl::Create(parent
, id
, pos
, size
, style
, wxDefaultValidator
, name
))
451 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE
));
455 long treeStyle
= wxTR_HAS_BUTTONS
| wxTR_HIDE_ROOT
;
457 if (style
& wxDIRCTRL_EDIT_LABELS
)
458 treeStyle
|= wxTR_EDIT_LABELS
;
460 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
461 treeStyle
|= wxNO_BORDER
;
463 treeStyle
|= wxBORDER_SUNKEN
;
465 long filterStyle
= 0;
466 if ((style
& wxDIRCTRL_3D_INTERNAL
) == 0)
467 filterStyle
|= wxNO_BORDER
;
469 filterStyle
|= wxBORDER_SUNKEN
;
471 m_treeCtrl
= new wxTreeCtrl(this, wxID_TREECTRL
, pos
, size
, treeStyle
);
473 if (!filter
.IsEmpty() && (style
& wxDIRCTRL_SHOW_FILTERS
))
474 m_filterListCtrl
= new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL
, wxDefaultPosition
, wxDefaultSize
, filterStyle
);
479 SetFilterIndex(defaultFilter
);
481 if (m_filterListCtrl
)
482 m_filterListCtrl
->FillFilterList(filter
, defaultFilter
);
484 m_treeCtrl
->SetImageList(wxTheFileIconsTable
->GetSmallImageList());
486 m_showHidden
= FALSE
;
487 wxDirItemData
* rootData
= new wxDirItemData(wxT(""), wxT(""), TRUE
);
491 #if defined(__WINDOWS__) || defined(__WXPM__) || defined(__DOS__)
492 rootName
= _("Computer");
494 rootName
= _("Sections");
497 m_rootId
= m_treeCtrl
->AddRoot( rootName
, 3, -1, rootData
);
498 m_treeCtrl
->SetItemHasChildren(m_rootId
);
499 ExpandDir(m_rootId
); // automatically expand first level
501 // Expand and select the default path
502 if (!m_defaultPath
.IsEmpty())
503 ExpandPath(m_defaultPath
);
510 wxGenericDirCtrl::~wxGenericDirCtrl()
514 void wxGenericDirCtrl::Init()
516 m_showHidden
= FALSE
;
518 m_currentFilterStr
= wxEmptyString
; // Default: any file
520 m_filterListCtrl
= NULL
;
523 void wxGenericDirCtrl::ShowHidden( bool show
)
527 wxString path
= GetPath();
532 void wxGenericDirCtrl::AddSection(const wxString
& path
, const wxString
& name
, int imageId
)
534 wxDirItemData
*dir_item
= new wxDirItemData(path
,name
,TRUE
);
536 wxTreeItemId id
= m_treeCtrl
->AppendItem( m_rootId
, name
, imageId
, -1, dir_item
);
538 m_treeCtrl
->SetItemHasChildren(id
);
541 void wxGenericDirCtrl::SetupSections()
543 wxArrayString paths
, names
;
546 size_t n
, count
= wxGetAvailableDrives(paths
, names
, icons
);
548 for (n
= 0; n
< count
; n
++)
550 AddSection(paths
[n
], names
[n
], icons
[n
]);
554 void wxGenericDirCtrl::OnBeginEditItem(wxTreeEvent
&event
)
556 // don't rename the main entry "Sections"
557 if (event
.GetItem() == m_rootId
)
563 // don't rename the individual sections
564 if (m_treeCtrl
->GetItemParent( event
.GetItem() ) == m_rootId
)
571 void wxGenericDirCtrl::OnEndEditItem(wxTreeEvent
&event
)
573 if ((event
.GetLabel().IsEmpty()) ||
574 (event
.GetLabel() == _(".")) ||
575 (event
.GetLabel() == _("..")) ||
576 (event
.GetLabel().Find(wxT('/')) != wxNOT_FOUND
) ||
577 (event
.GetLabel().Find(wxT('\\')) != wxNOT_FOUND
) ||
578 (event
.GetLabel().Find(wxT('|')) != wxNOT_FOUND
))
580 wxMessageDialog
dialog(this, _("Illegal directory name."), _("Error"), wxOK
| wxICON_ERROR
);
586 wxTreeItemId id
= event
.GetItem();
587 wxDirItemData
*data
= (wxDirItemData
*)m_treeCtrl
->GetItemData( id
);
590 wxString
new_name( wxPathOnly( data
->m_path
) );
591 new_name
+= wxString(wxFILE_SEP_PATH
);
592 new_name
+= event
.GetLabel();
596 if (wxFileExists(new_name
))
598 wxMessageDialog
dialog(this, _("File name exists already."), _("Error"), wxOK
| wxICON_ERROR
);
603 if (wxRenameFile(data
->m_path
,new_name
))
605 data
->SetNewDirName( new_name
);
609 wxMessageDialog
dialog(this, _("Operation not permitted."), _("Error"), wxOK
| wxICON_ERROR
);
615 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent
&event
)
617 wxTreeItemId parentId
= event
.GetItem();
619 // VS: this is needed because the event handler is called from wxTreeCtrl
620 // ctor when wxTR_HIDE_ROOT was specified
622 if (!m_rootId
.IsOk())
624 m_rootId
= m_treeCtrl
->GetRootItem();
629 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent
&event
)
631 CollapseDir(event
.GetItem());
634 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId
)
638 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
639 if (!data
->m_isExpanded
)
642 data
->m_isExpanded
= FALSE
;
644 /* Workaround because DeleteChildren has disapeared (why?) and
645 * CollapseAndReset doesn't work as advertised (deletes parent too) */
646 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
649 m_treeCtrl
->Delete(child
);
650 /* Not GetNextChild below, because the cookie mechanism can't
651 * handle disappearing children! */
652 child
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
656 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId
)
658 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(parentId
);
660 if (data
->m_isExpanded
)
663 data
->m_isExpanded
= TRUE
;
665 if (parentId
== m_treeCtrl
->GetRootItem())
673 wxString search
,path
,filename
;
675 wxString
dirName(data
->m_path
);
677 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
678 // Check if this is a root directory and if so,
679 // whether the drive is avaiable.
680 if (!wxIsDriveAvailable(dirName
))
682 data
->m_isExpanded
= FALSE
;
683 //wxMessageBox(wxT("Sorry, this drive is not available."));
688 // This may take a longish time. Go to busy cursor
691 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
692 if (dirName
.Last() == ':')
693 dirName
+= wxString(wxFILE_SEP_PATH
);
697 wxArrayString filenames
;
700 wxString eachFilename
;
707 int style
= wxDIR_DIRS
;
708 if (m_showHidden
) style
|= wxDIR_HIDDEN
;
709 if (d
.GetFirst(& eachFilename
, wxEmptyString
, style
))
713 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
715 dirs
.Add(eachFilename
);
718 while (d
.GetNext(& eachFilename
));
721 dirs
.Sort((wxArrayString::CompareFunction
) wxDirCtrlStringCompareFunction
);
723 // Now do the filenames -- but only if we're allowed to
724 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
732 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, wxDIR_FILES
))
736 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
738 filenames
.Add(eachFilename
);
741 while (d
.GetNext(& eachFilename
));
744 filenames
.Sort((wxArrayString::CompareFunction
) wxDirCtrlStringCompareFunction
);
747 // Add the sorted dirs
749 for (i
= 0; i
< dirs
.Count(); i
++)
751 wxString
eachFilename(dirs
[i
]);
753 if (!wxEndsWithPathSeparator(path
))
754 path
+= wxString(wxFILE_SEP_PATH
);
755 path
+= eachFilename
;
757 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,TRUE
);
758 wxTreeItemId id
= m_treeCtrl
->AppendItem( parentId
, eachFilename
,
759 wxFileIconsTable::folder
, -1, dir_item
);
760 m_treeCtrl
->SetItemImage( id
, wxFileIconsTable::folder_open
,
761 wxTreeItemIcon_Expanded
);
763 // Has this got any children? If so, make it expandable.
764 // (There are two situations when a dir has children: either it
765 // has subdirectories or it contains files that weren't filtered
766 // out. The latter only applies to dirctrl with files.)
767 if ( dir_item
->HasSubDirs() ||
768 (((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0) &&
769 dir_item
->HasFiles(m_currentFilterStr
)) )
771 m_treeCtrl
->SetItemHasChildren(id
);
775 // Add the sorted filenames
776 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY
) == 0)
778 for (i
= 0; i
< filenames
.Count(); i
++)
780 wxString
eachFilename(filenames
[i
]);
782 if (!wxEndsWithPathSeparator(path
))
783 path
+= wxString(wxFILE_SEP_PATH
);
784 path
+= eachFilename
;
785 //path = dirName + wxString(wxT("/")) + eachFilename;
786 wxDirItemData
*dir_item
= new wxDirItemData(path
,eachFilename
,FALSE
);
787 int image_id
= wxFileIconsTable::file
;
788 if (eachFilename
.Find(wxT('.')) != wxNOT_FOUND
)
789 image_id
= wxTheFileIconsTable
->GetIconID(eachFilename
.AfterLast(wxT('.')));
790 (void)m_treeCtrl
->AppendItem( parentId
, eachFilename
, image_id
, -1, dir_item
);
795 void wxGenericDirCtrl::ReCreateTree()
797 CollapseDir(m_treeCtrl
->GetRootItem());
798 ExpandDir(m_treeCtrl
->GetRootItem());
801 // Find the child that matches the first part of 'path'.
802 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
803 // then the child for /usr is returned.
804 wxTreeItemId
wxGenericDirCtrl::FindChild(wxTreeItemId parentId
, const wxString
& path
, bool& done
)
806 wxString
path2(path
);
808 // Make sure all separators are as per the current platform
809 path2
.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH
));
810 path2
.Replace(wxT("/"), wxString(wxFILE_SEP_PATH
));
812 // Append a separator to foil bogus substring matching
813 path2
+= wxString(wxFILE_SEP_PATH
);
815 // In MSW or PM, case is not significant
816 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
821 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(parentId
, cookie
);
822 while (childId
.IsOk())
824 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
826 if (data
&& !data
->m_path
.IsEmpty())
828 wxString
childPath(data
->m_path
);
829 if (!wxEndsWithPathSeparator(childPath
))
830 childPath
+= wxString(wxFILE_SEP_PATH
);
832 // In MSW and PM, case is not significant
833 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
834 childPath
.MakeLower();
837 if (childPath
.Len() <= path2
.Len())
839 wxString path3
= path2
.Mid(0, childPath
.Len());
840 if (childPath
== path3
)
842 if (path3
.Len() == path2
.Len())
851 childId
= m_treeCtrl
->GetNextChild(parentId
, cookie
);
853 wxTreeItemId invalid
;
857 // Try to expand as much of the given path as possible,
858 // and select the given tree item.
859 bool wxGenericDirCtrl::ExpandPath(const wxString
& path
)
862 wxTreeItemId id
= FindChild(m_rootId
, path
, done
);
863 wxTreeItemId lastId
= id
; // The last non-zero id
864 while (id
.IsOk() && !done
)
868 id
= FindChild(id
, path
, done
);
874 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(lastId
);
877 m_treeCtrl
->Expand(lastId
);
879 if ((GetWindowStyle() & wxDIRCTRL_SELECT_FIRST
) && data
->m_isDir
)
881 // Find the first file in this directory
883 wxTreeItemId childId
= m_treeCtrl
->GetFirstChild(lastId
, cookie
);
884 bool selectedChild
= FALSE
;
885 while (childId
.IsOk())
887 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(childId
);
889 if (data
&& data
->m_path
!= wxT("") && !data
->m_isDir
)
891 m_treeCtrl
->SelectItem(childId
);
892 m_treeCtrl
->EnsureVisible(childId
);
893 selectedChild
= TRUE
;
896 childId
= m_treeCtrl
->GetNextChild(lastId
, cookie
);
900 m_treeCtrl
->SelectItem(lastId
);
901 m_treeCtrl
->EnsureVisible(lastId
);
906 m_treeCtrl
->SelectItem(lastId
);
907 m_treeCtrl
->EnsureVisible(lastId
);
916 wxString
wxGenericDirCtrl::GetPath() const
918 wxTreeItemId id
= m_treeCtrl
->GetSelection();
921 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
925 return wxEmptyString
;
928 wxString
wxGenericDirCtrl::GetFilePath() const
930 wxTreeItemId id
= m_treeCtrl
->GetSelection();
933 wxDirItemData
* data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
935 return wxEmptyString
;
940 return wxEmptyString
;
943 void wxGenericDirCtrl::SetPath(const wxString
& path
)
945 m_defaultPath
= path
;
952 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId id
, int dirFlags
, wxArrayString
& filenames
)
954 wxDirItemData
*data
= (wxDirItemData
*) m_treeCtrl
->GetItemData(id
);
956 // This may take a longish time. Go to busy cursor
961 wxString search
,path
,filename
;
963 wxString
dirName(data
->m_path
);
965 #if defined(__WXMSW__) || defined(__WXPM__)
966 if (dirName
.Last() == ':')
967 dirName
+= wxString(wxFILE_SEP_PATH
);
971 wxString eachFilename
;
978 if (d
.GetFirst(& eachFilename
, m_currentFilterStr
, dirFlags
))
982 if ((eachFilename
!= wxT(".")) && (eachFilename
!= wxT("..")))
984 filenames
.Add(eachFilename
);
987 while (d
.GetNext(& eachFilename
)) ;
993 void wxGenericDirCtrl::SetFilterIndex(int n
)
998 if (ExtractWildcard(m_filter
, n
, f
, d
))
999 m_currentFilterStr
= f
;
1001 m_currentFilterStr
= wxT("*.*");
1004 void wxGenericDirCtrl::SetFilter(const wxString
& filter
)
1009 if (ExtractWildcard(m_filter
, m_currentFilter
, f
, d
))
1010 m_currentFilterStr
= f
;
1012 m_currentFilterStr
= wxT("*.*");
1015 // Extract description and actual filter from overall filter string
1016 bool wxGenericDirCtrl::ExtractWildcard(const wxString
& filterStr
, int n
, wxString
& filter
, wxString
& description
)
1018 wxArrayString filters
, descriptions
;
1019 int count
= ParseFilter(filterStr
, filters
, descriptions
);
1020 if (count
> 0 && n
< count
)
1022 filter
= filters
[n
];
1023 description
= descriptions
[n
];
1030 // Parses the global filter, returning the number of filters.
1031 // Returns 0 if none or if there's a problem.
1032 // filterStr is in the form:
1034 // "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpg"
1036 int wxGenericDirCtrl::ParseFilter(const wxString
& filterStr
, wxArrayString
& filters
, wxArrayString
& descriptions
)
1038 wxString
str(filterStr
);
1040 wxString description
, filter
;
1042 bool finished
= FALSE
;
1045 pos
= str
.Find(wxT('|'));
1047 return 0; // Problem
1048 description
= str
.Left(pos
);
1049 str
= str
.Mid(pos
+1);
1050 pos
= str
.Find(wxT('|'));
1058 filter
= str
.Left(pos
);
1059 str
= str
.Mid(pos
+1);
1061 descriptions
.Add(description
);
1062 filters
.Add(filter
);
1066 return filters
.Count();
1069 void wxGenericDirCtrl::DoResize()
1071 wxSize sz
= GetClientSize();
1072 int verticalSpacing
= 3;
1076 if (m_filterListCtrl
)
1079 // For some reason, this is required in order for the
1080 // correct control height to always be returned, rather
1081 // than the drop-down list height which is sometimes returned.
1082 wxSize oldSize
= m_filterListCtrl
->GetSize();
1083 m_filterListCtrl
->SetSize(-1, -1, oldSize
.x
+10, -1, wxSIZE_USE_EXISTING
);
1084 m_filterListCtrl
->SetSize(-1, -1, oldSize
.x
, -1, wxSIZE_USE_EXISTING
);
1086 filterSz
= m_filterListCtrl
->GetSize();
1087 sz
.y
-= (filterSz
.y
+ verticalSpacing
);
1089 m_treeCtrl
->SetSize(0, 0, sz
.x
, sz
.y
);
1090 if (m_filterListCtrl
)
1092 m_filterListCtrl
->SetSize(0, sz
.y
+ verticalSpacing
, sz
.x
, filterSz
.y
);
1093 // Don't know why, but this needs refreshing after a resize (wxMSW)
1094 m_filterListCtrl
->Refresh();
1100 void wxGenericDirCtrl::OnSize(wxSizeEvent
& WXUNUSED(event
))
1105 //-----------------------------------------------------------------------------
1106 // wxDirFilterListCtrl
1107 //-----------------------------------------------------------------------------
1109 IMPLEMENT_CLASS(wxDirFilterListCtrl
, wxChoice
)
1111 BEGIN_EVENT_TABLE(wxDirFilterListCtrl
, wxChoice
)
1112 EVT_CHOICE(-1, wxDirFilterListCtrl::OnSelFilter
)
1115 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl
* parent
, const wxWindowID id
,
1121 return wxChoice::Create(parent
, id
, pos
, size
, 0, NULL
, style
);
1124 void wxDirFilterListCtrl::Init()
1129 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent
& WXUNUSED(event
))
1131 int sel
= GetSelection();
1133 wxString currentPath
= m_dirCtrl
->GetPath();
1135 m_dirCtrl
->SetFilterIndex(sel
);
1137 // If the filter has changed, the view is out of date, so
1138 // collapse the tree.
1139 m_dirCtrl
->ReCreateTree();
1141 // Try to restore the selection, or at least the directory
1142 m_dirCtrl
->ExpandPath(currentPath
);
1145 void wxDirFilterListCtrl::FillFilterList(const wxString
& filter
, int defaultFilter
)
1148 wxArrayString descriptions
, filters
;
1149 size_t n
= (size_t) m_dirCtrl
->ParseFilter(filter
, filters
, descriptions
);
1151 if (n
> 0 && defaultFilter
< (int) n
)
1154 for (i
= 0; i
< n
; i
++)
1155 Append(descriptions
[i
]);
1156 SetSelection(defaultFilter
);
1160 // ----------------------------------------------------------------------------
1161 // wxFileIconsTable icons
1162 // ----------------------------------------------------------------------------
1165 static const char * file_icons_tbl_folder_open_xpm
[] = {
1166 /* width height ncolors chars_per_pixel */
1194 static const char * file_icons_tbl_computer_xpm
[] = {
1221 static const char * file_icons_tbl_drive_xpm
[] = {
1248 static const char *file_icons_tbl_cdrom_xpm
[] = {
1278 static const char * file_icons_tbl_floppy_xpm
[] = {
1305 static const char * file_icons_tbl_removeable_xpm
[] = {
1331 // ----------------------------------------------------------------------------
1332 // wxFileIconsTable & friends
1333 // ----------------------------------------------------------------------------
1335 // global instance of a wxFileIconsTable
1336 wxFileIconsTable
* wxTheFileIconsTable
= (wxFileIconsTable
*)NULL
;
1338 // A module to allow icons table cleanup
1340 class wxFileIconsTableModule
: public wxModule
1342 DECLARE_DYNAMIC_CLASS(wxFileIconsTableModule
)
1344 wxFileIconsTableModule() {}
1345 bool OnInit() { wxTheFileIconsTable
= new wxFileIconsTable
; return TRUE
; }
1348 if (wxTheFileIconsTable
)
1350 delete wxTheFileIconsTable
;
1351 wxTheFileIconsTable
= NULL
;
1356 IMPLEMENT_DYNAMIC_CLASS(wxFileIconsTableModule
, wxModule
)
1358 class wxFileIconEntry
: public wxObject
1361 wxFileIconEntry(int i
) { id
= i
; }
1366 wxFileIconsTable::wxFileIconsTable()
1369 m_smallImageList
= NULL
;
1372 wxFileIconsTable::~wxFileIconsTable()
1374 if (m_HashTable
) delete m_HashTable
;
1375 if (m_smallImageList
) delete m_smallImageList
;
1378 // delayed initialization - wait until first use (wxArtProv not created yet)
1379 void wxFileIconsTable::Create()
1381 wxCHECK_RET(!m_smallImageList
&& !m_HashTable
, wxT("creating icons twice"));
1382 printf("creating \n"); fflush(stdout
);
1383 m_HashTable
= new wxHashTable(wxKEY_STRING
);
1384 m_smallImageList
= new wxImageList(16, 16);
1386 m_HashTable
->DeleteContents(TRUE
);
1388 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_FOLDER
, wxART_CMN_DIALOG
));
1390 m_smallImageList
->Add(wxIcon(file_icons_tbl_folder_open_xpm
));
1392 m_smallImageList
->Add(wxIcon(file_icons_tbl_computer_xpm
));
1394 m_smallImageList
->Add(wxIcon(file_icons_tbl_drive_xpm
));
1396 m_smallImageList
->Add(wxIcon(file_icons_tbl_cdrom_xpm
));
1398 m_smallImageList
->Add(wxIcon(file_icons_tbl_floppy_xpm
));
1400 m_smallImageList
->Add(wxIcon(file_icons_tbl_removeable_xpm
));
1402 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE
, wxART_CMN_DIALOG
));
1404 if (GetIconID(wxEmptyString
, _T("application/x-executable")) == file
)
1406 m_smallImageList
->Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE
, wxART_CMN_DIALOG
));
1407 m_HashTable
->Delete(_T("exe"));
1408 m_HashTable
->Put(_T("exe"), new wxFileIconEntry(executable
));
1410 /* else put into list by GetIconID
1411 (KDE defines application/x-executable for *.exe and has nice icon)
1415 wxImageList
*wxFileIconsTable::GetSmallImageList()
1417 if (!m_smallImageList
)
1420 return m_smallImageList
;
1424 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
1425 // one icon and we won't resize it
1427 static wxBitmap
CreateAntialiasedBitmap(const wxImage
& img
)
1429 wxImage
smallimg (16, 16);
1430 unsigned char *p1
, *p2
, *ps
;
1431 unsigned char mr
= img
.GetMaskRed(),
1432 mg
= img
.GetMaskGreen(),
1433 mb
= img
.GetMaskBlue();
1436 unsigned sr
, sg
, sb
, smask
;
1438 p1
= img
.GetData(), p2
= img
.GetData() + 3 * 32, ps
= smallimg
.GetData();
1439 smallimg
.SetMaskColour(mr
, mr
, mr
);
1441 for (y
= 0; y
< 16; y
++)
1443 for (x
= 0; x
< 16; x
++)
1445 sr
= sg
= sb
= smask
= 0;
1446 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1447 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1450 if (p1
[0] != mr
|| p1
[1] != mg
|| p1
[2] != mb
)
1451 sr
+= p1
[0], sg
+= p1
[1], sb
+= p1
[2];
1454 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1455 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1458 if (p2
[0] != mr
|| p2
[1] != mg
|| p2
[2] != mb
)
1459 sr
+= p2
[0], sg
+= p2
[1], sb
+= p2
[2];
1464 ps
[0] = ps
[1] = ps
[2] = mr
;
1466 ps
[0] = sr
>> 2, ps
[1] = sg
>> 2, ps
[2] = sb
>> 2;
1469 p1
+= 32 * 3, p2
+= 32 * 3;
1472 return wxBitmap(smallimg
);
1475 // finds empty borders and return non-empty area of image:
1476 static wxImage
CutEmptyBorders(const wxImage
& img
)
1478 unsigned char mr
= img
.GetMaskRed(),
1479 mg
= img
.GetMaskGreen(),
1480 mb
= img
.GetMaskBlue();
1481 unsigned char *dt
= img
.GetData(), *dttmp
;
1482 unsigned w
= img
.GetWidth(), h
= img
.GetHeight();
1484 unsigned top
, bottom
, left
, right
, i
;
1487 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
1488 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = FALSE; break;}
1490 for (empt
= TRUE
, top
= 0; empt
&& top
< h
; top
++)
1493 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1496 for (empt
= TRUE
, bottom
= h
-1; empt
&& bottom
> top
; bottom
--)
1498 MK_DTTMP(0, bottom
);
1499 for (i
= 0; i
< w
; i
++, dttmp
+=3)
1502 for (empt
= TRUE
, left
= 0; empt
&& left
< w
; left
++)
1505 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1508 for (empt
= TRUE
, right
= w
-1; empt
&& right
> left
; right
--)
1511 for (i
= 0; i
< h
; i
++, dttmp
+=3*w
)
1514 top
--, left
--, bottom
++, right
++;
1516 return img
.GetSubImage(wxRect(left
, top
, right
- left
+ 1, bottom
- top
+ 1));
1518 #endif // wxUSE_MIMETYPE
1520 int wxFileIconsTable::GetIconID(const wxString
& extension
, const wxString
& mime
)
1522 if (!m_smallImageList
)
1526 if (!extension
.IsEmpty())
1528 wxFileIconEntry
*entry
= (wxFileIconEntry
*) m_HashTable
->Get(extension
);
1529 if (entry
) return (entry
-> id
);
1532 wxFileType
*ft
= (mime
.IsEmpty()) ?
1533 wxTheMimeTypesManager
-> GetFileTypeFromExtension(extension
) :
1534 wxTheMimeTypesManager
-> GetFileTypeFromMimeType(mime
);
1536 if (ft
== NULL
|| (!ft
->GetIcon(&ic
)) || (!ic
.Ok()))
1539 m_HashTable
->Put(extension
, new wxFileIconEntry(newid
));
1544 tmpBmp
.CopyFromIcon(ic
);
1545 wxImage img
= tmpBmp
.ConvertToImage();
1549 int id
= m_smallImageList
->GetImageCount();
1550 if (img
.GetWidth() == 16 && img
.GetHeight() == 16)
1551 m_smallImageList
->Add(wxBitmap(img
));
1554 if (img
.GetWidth() != 32 || img
.GetHeight() != 32)
1555 m_smallImageList
->Add(CreateAntialiasedBitmap(CutEmptyBorders(img
).Rescale(32, 32)));
1557 m_smallImageList
->Add(CreateAntialiasedBitmap(img
));
1559 m_HashTable
->Put(extension
, new wxFileIconEntry(id
));
1562 #else // !wxUSE_MIMETYPE
1564 if (extension
== wxT("exe"))
1568 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
1571 #endif // wxUSE_DIRDLG