1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/generic/filectrlg.cpp
3 // Purpose: wxGenericFileCtrl Implementation
4 // Author: Diaa M. Sami
7 // Copyright: (c) Diaa M. Sami
8 // Licence: wxWindows licence
9 ///////////////////////////////////////////////////////////////////////////////
11 #include "wx/wxprec.h"
19 #include "wx/generic/filectrlg.h"
22 #include "wx/settings.h"
24 #include "wx/stattext.h"
25 #include "wx/checkbox.h"
26 #include "wx/msgdlg.h"
28 #include "wx/filedlg.h"
31 #include "wx/clntdata.h"
32 #include "wx/file.h" // for wxS_IXXX constants only
33 #include "wx/generic/dirctrlg.h" // for wxFileIconsTable
35 #include "wx/tokenzr.h"
38 #include "wx/msw/wrapwin.h"
41 #if defined(__WXWINCE__)
42 #define IsTopMostDir(dir) (dir == wxT("\\") || dir == wxT("/"))
43 #elif (defined(__DOS__) || defined(__WINDOWS__) || defined (__OS2__))
44 #define IsTopMostDir(dir) (dir.empty())
46 #define IsTopMostDir(dir) (dir == wxT("/"))
50 // ----------------------------------------------------------------------------
52 // ----------------------------------------------------------------------------
55 int wxCALLBACK wxFileDataNameCompare( long data1, long data2, long sortOrder)
57 wxFileData *fd1 = (wxFileData *)wxUIntToPtr(data1);
58 wxFileData *fd2 = (wxFileData *)wxUIntToPtr(data2);
60 if (fd1->GetFileName() == wxT(".."))
62 if (fd2->GetFileName() == wxT(".."))
64 if (fd1->IsDir() && !fd2->IsDir())
66 if (fd2->IsDir() && !fd1->IsDir())
69 return sortOrder*wxStrcmp( fd1->GetFileName(), fd2->GetFileName() );
73 int wxCALLBACK wxFileDataSizeCompare(long data1, long data2, long sortOrder)
75 wxFileData *fd1 = (wxFileData *)wxUIntToPtr(data1);
76 wxFileData *fd2 = (wxFileData *)wxUIntToPtr(data2);
78 if (fd1->GetFileName() == wxT(".."))
80 if (fd2->GetFileName() == wxT(".."))
82 if (fd1->IsDir() && !fd2->IsDir())
84 if (fd2->IsDir() && !fd1->IsDir())
86 if (fd1->IsLink() && !fd2->IsLink())
88 if (fd2->IsLink() && !fd1->IsLink())
91 return fd1->GetSize() > fd2->GetSize() ? sortOrder : -sortOrder;
95 int wxCALLBACK wxFileDataTypeCompare(long data1, long data2, long sortOrder)
97 wxFileData *fd1 = (wxFileData *)wxUIntToPtr(data1);
98 wxFileData *fd2 = (wxFileData *)wxUIntToPtr(data2);
100 if (fd1->GetFileName() == wxT(".."))
102 if (fd2->GetFileName() == wxT(".."))
104 if (fd1->IsDir() && !fd2->IsDir())
106 if (fd2->IsDir() && !fd1->IsDir())
108 if (fd1->IsLink() && !fd2->IsLink())
110 if (fd2->IsLink() && !fd1->IsLink())
113 return sortOrder*wxStrcmp( fd1->GetFileType(), fd2->GetFileType() );
117 int wxCALLBACK wxFileDataTimeCompare(long data1, long data2, long sortOrder)
119 wxFileData *fd1 = (wxFileData *)wxUIntToPtr(data1);
120 wxFileData *fd2 = (wxFileData *)wxUIntToPtr(data2);
122 if (fd1->GetFileName() == wxT(".."))
124 if (fd2->GetFileName() == wxT(".."))
126 if (fd1->IsDir() && !fd2->IsDir())
128 if (fd2->IsDir() && !fd1->IsDir())
131 return fd1->GetDateTime().IsLaterThan(fd2->GetDateTime()) ? sortOrder : -sortOrder;
134 // defined in src/generic/dirctrlg.cpp
135 extern size_t wxGetAvailableDrives(wxArrayString &paths, wxArrayString &names, wxArrayInt &icon_ids);
137 //-----------------------------------------------------------------------------
139 //-----------------------------------------------------------------------------
141 wxFileData::wxFileData( const wxString &filePath, const wxString &fileName, fileType type, int image_id )
144 m_fileName = fileName;
145 m_filePath = filePath;
152 void wxFileData::Init()
155 m_type = wxFileData::is_file;
156 m_image = wxFileIconsTable::file;
159 void wxFileData::Copy( const wxFileData& fileData )
161 m_fileName = fileData.GetFileName();
162 m_filePath = fileData.GetFilePath();
163 m_size = fileData.GetSize();
164 m_dateTime = fileData.GetDateTime();
165 m_permissions = fileData.GetPermissions();
166 m_type = fileData.GetType();
167 m_image = fileData.GetImageId();
170 void wxFileData::ReadData()
178 #if defined(__DOS__) || (defined(__WINDOWS__) && !defined(__WXWINCE__)) || defined(__OS2__)
179 // c:\.. is a drive don't stat it
180 if ((m_fileName == wxT("..")) && (m_filePath.length() <= 5))
186 #endif // __DOS__ || __WINDOWS__
192 DWORD fileAttribs = GetFileAttributes(m_filePath.fn_str());
193 m_type |= (fileAttribs & FILE_ATTRIBUTE_DIRECTORY) != 0 ? is_dir : 0;
196 wxSplitPath(m_filePath, & p, & f, & ext);
197 if (wxStricmp(ext, wxT("exe")) == 0)
202 HANDLE fileHandle = CreateFile(m_filePath.fn_str(),
207 FILE_ATTRIBUTE_NORMAL,
210 if (fileHandle != INVALID_HANDLE_VALUE)
212 m_size = GetFileSize(fileHandle, 0);
213 CloseHandle(fileHandle);
216 m_dateTime = wxFileModificationTime(m_filePath);
224 #if defined(__UNIX__) && (!defined( __OS2__ ) && !defined(__VMS))
225 lstat( m_filePath.fn_str(), &buff );
226 m_type |= S_ISLNK(buff.st_mode) ? is_link : 0;
228 // only translate to file charset if we don't go by our
229 // wxStat implementation
230 #ifndef wxNEED_WX_UNISTD_H
231 wxStat( m_filePath.fn_str() , &buff );
233 wxStat( m_filePath, &buff );
237 m_type |= (buff.st_mode & S_IFDIR) != 0 ? is_dir : 0;
238 m_type |= (buff.st_mode & wxS_IXUSR) != 0 ? is_exe : 0;
240 m_size = buff.st_size;
242 m_dateTime = buff.st_mtime;
246 #if defined(__UNIX__)
247 m_permissions.Printf(_T("%c%c%c%c%c%c%c%c%c"),
248 buff.st_mode & wxS_IRUSR ? _T('r') : _T('-'),
249 buff.st_mode & wxS_IWUSR ? _T('w') : _T('-'),
250 buff.st_mode & wxS_IXUSR ? _T('x') : _T('-'),
251 buff.st_mode & wxS_IRGRP ? _T('r') : _T('-'),
252 buff.st_mode & wxS_IWGRP ? _T('w') : _T('-'),
253 buff.st_mode & wxS_IXGRP ? _T('x') : _T('-'),
254 buff.st_mode & wxS_IROTH ? _T('r') : _T('-'),
255 buff.st_mode & wxS_IWOTH ? _T('w') : _T('-'),
256 buff.st_mode & wxS_IXOTH ? _T('x') : _T('-'));
257 #elif defined(__WIN32__)
258 DWORD attribs = ::GetFileAttributes(m_filePath.c_str());
259 if (attribs != (DWORD)-1)
261 m_permissions.Printf(_T("%c%c%c%c"),
262 attribs & FILE_ATTRIBUTE_ARCHIVE ? _T('A') : _T(' '),
263 attribs & FILE_ATTRIBUTE_READONLY ? _T('R') : _T(' '),
264 attribs & FILE_ATTRIBUTE_HIDDEN ? _T('H') : _T(' '),
265 attribs & FILE_ATTRIBUTE_SYSTEM ? _T('S') : _T(' '));
269 // try to get a better icon
270 if (m_image == wxFileIconsTable::file)
272 if (m_fileName.Find(wxT('.'), true) != wxNOT_FOUND)
274 m_image = wxTheFileIconsTable->GetIconID( m_fileName.AfterLast(wxT('.')));
277 m_image = wxFileIconsTable::executable;
282 wxString wxFileData::GetFileType() const
290 else if (m_fileName.Find(wxT('.'), true) != wxNOT_FOUND)
291 return m_fileName.AfterLast(wxT('.'));
293 return wxEmptyString;
296 wxString wxFileData::GetModificationTime() const
298 // want time as 01:02 so they line up nicely, no %r in WIN32
299 return m_dateTime.FormatDate() + wxT(" ") + m_dateTime.Format(wxT("%I:%M:%S %p"));
302 wxString wxFileData::GetHint() const
304 wxString s = m_filePath;
314 s += wxString::Format(wxPLURAL("%ld byte", "%ld bytes", m_size),
315 wxLongLong(m_size).ToString().c_str());
321 s << GetModificationTime()
329 wxString wxFileData::GetEntry( fileListFieldType num ) const
339 if (!IsDir() && !IsLink() && !IsDrive())
340 s = wxLongLong(m_size).ToString();
349 s = GetModificationTime();
352 #if defined(__UNIX__) || defined(__WIN32__)
356 #endif // defined(__UNIX__) || defined(__WIN32__)
359 wxFAIL_MSG( _T("unexpected field in wxFileData::GetEntry()") );
365 void wxFileData::SetNewName( const wxString &filePath, const wxString &fileName )
367 m_fileName = fileName;
368 m_filePath = filePath;
371 void wxFileData::MakeItem( wxListItem &item )
373 item.m_text = m_fileName;
374 item.ClearAttributes();
376 item.SetTextColour(*wxRED);
378 item.SetTextColour(*wxBLUE);
380 item.m_image = m_image;
384 wxColour dg = wxTheColourDatabase->Find( _T("MEDIUM GREY") );
386 item.SetTextColour(dg);
388 item.m_data = wxPtrToUInt(this);
391 //-----------------------------------------------------------------------------
393 //-----------------------------------------------------------------------------
395 IMPLEMENT_DYNAMIC_CLASS(wxFileListCtrl,wxListCtrl)
397 BEGIN_EVENT_TABLE(wxFileListCtrl,wxListCtrl)
398 EVT_LIST_DELETE_ITEM(wxID_ANY, wxFileListCtrl::OnListDeleteItem)
399 EVT_LIST_DELETE_ALL_ITEMS(wxID_ANY, wxFileListCtrl::OnListDeleteAllItems)
400 EVT_LIST_END_LABEL_EDIT(wxID_ANY, wxFileListCtrl::OnListEndLabelEdit)
401 EVT_LIST_COL_CLICK(wxID_ANY, wxFileListCtrl::OnListColClick)
405 wxFileListCtrl::wxFileListCtrl()
407 m_showHidden = false;
408 m_sort_forward = true;
409 m_sort_field = wxFileData::FileList_Name;
412 wxFileListCtrl::wxFileListCtrl(wxWindow *win,
414 const wxString& wild,
419 const wxValidator &validator,
420 const wxString &name)
421 : wxListCtrl(win, id, pos, size, style, validator, name),
424 wxImageList *imageList = wxTheFileIconsTable->GetSmallImageList();
426 SetImageList( imageList, wxIMAGE_LIST_SMALL );
428 m_showHidden = showHidden;
430 m_sort_forward = true;
431 m_sort_field = wxFileData::FileList_Name;
433 m_dirName = wxT("*");
435 if (style & wxLC_REPORT)
436 ChangeToReportMode();
439 void wxFileListCtrl::ChangeToListMode()
442 SetSingleStyle( wxLC_LIST );
446 void wxFileListCtrl::ChangeToReportMode()
449 SetSingleStyle( wxLC_REPORT );
451 // do this since WIN32 does mm/dd/yy UNIX does mm/dd/yyyy
452 // don't hardcode since mm/dd is dd/mm elsewhere
454 wxDateTime dt(22, wxDateTime::Dec, 2002, 22, 22, 22);
455 wxString txt = dt.FormatDate() + wxT("22") + dt.Format(wxT("%I:%M:%S %p"));
456 GetTextExtent(txt, &w, &h);
458 InsertColumn( 0, _("Name"), wxLIST_FORMAT_LEFT, w );
459 InsertColumn( 1, _("Size"), wxLIST_FORMAT_LEFT, w/2 );
460 InsertColumn( 2, _("Type"), wxLIST_FORMAT_LEFT, w/2 );
461 InsertColumn( 3, _("Modified"), wxLIST_FORMAT_LEFT, w );
462 #if defined(__UNIX__)
463 GetTextExtent(wxT("Permissions 2"), &w, &h);
464 InsertColumn( 4, _("Permissions"), wxLIST_FORMAT_LEFT, w );
465 #elif defined(__WIN32__)
466 GetTextExtent(wxT("Attributes 2"), &w, &h);
467 InsertColumn( 4, _("Attributes"), wxLIST_FORMAT_LEFT, w );
473 void wxFileListCtrl::ChangeToSmallIconMode()
476 SetSingleStyle( wxLC_SMALL_ICON );
480 void wxFileListCtrl::ShowHidden( bool show )
486 long wxFileListCtrl::Add( wxFileData *fd, wxListItem &item )
489 item.m_mask = wxLIST_MASK_TEXT + wxLIST_MASK_DATA + wxLIST_MASK_IMAGE;
490 fd->MakeItem( item );
491 long my_style = GetWindowStyleFlag();
492 if (my_style & wxLC_REPORT)
494 ret = InsertItem( item );
495 for (int i = 1; i < wxFileData::FileList_Max; i++)
496 SetItem( item.m_itemId, i, fd->GetEntry((wxFileData::fileListFieldType)i) );
498 else if ((my_style & wxLC_LIST) || (my_style & wxLC_SMALL_ICON))
500 ret = InsertItem( item );
505 void wxFileListCtrl::UpdateItem(const wxListItem &item)
507 wxFileData *fd = (wxFileData*)GetItemData(item);
508 wxCHECK_RET(fd, wxT("invalid filedata"));
512 SetItemText(item, fd->GetFileName());
513 SetItemImage(item, fd->GetImageId());
515 if (GetWindowStyleFlag() & wxLC_REPORT)
517 for (int i = 1; i < wxFileData::FileList_Max; i++)
518 SetItem( item.m_itemId, i, fd->GetEntry((wxFileData::fileListFieldType)i) );
522 void wxFileListCtrl::UpdateFiles()
524 // don't do anything before ShowModal() call which sets m_dirName
525 if ( m_dirName == wxT("*") )
528 wxBusyCursor bcur; // this may take a while...
536 #if (defined(__WINDOWS__) || defined(__DOS__) || defined(__WXMAC__) || defined(__OS2__)) && !defined(__WXWINCE__)
537 if ( IsTopMostDir(m_dirName) )
539 wxArrayString names, paths;
541 const size_t count = wxGetAvailableDrives(paths, names, icons);
543 for ( size_t n = 0; n < count; n++ )
545 // use paths[n] as the drive name too as our HandleAction() can't
546 // deal with the drive names (of the form "System (C:)") currently
547 // as it mistakenly treats them as file names
549 // it would be preferable to show names, and not paths, in the
550 // dialog just as the native dialog does but for this we must:
551 // a) store the item type as item data and modify HandleAction()
552 // to use it instead of wxDirExists() to check whether the item
554 // b) store the drives by their drive letters and not their
555 // descriptions as otherwise it's pretty confusing to the user
556 wxFileData *fd = new wxFileData(paths[n], paths[n],
557 wxFileData::is_drive, icons[n]);
558 if (Add(fd, item) != -1)
565 #endif // defined(__DOS__) || defined(__WINDOWS__)
568 if ( !IsTopMostDir(m_dirName) && !m_dirName.empty() )
570 wxString p(wxPathOnly(m_dirName));
571 #if (defined(__UNIX__) || defined(__WXWINCE__)) && !defined(__OS2__)
572 if (p.empty()) p = wxT("/");
574 wxFileData *fd = new wxFileData(p, wxT(".."), wxFileData::is_dir, wxFileIconsTable::folder);
575 if (Add(fd, item) != -1)
581 wxString dirname(m_dirName);
582 #if defined(__DOS__) || defined(__WINDOWS__) || defined(__OS2__)
583 if (dirname.length() == 2 && dirname[1u] == wxT(':'))
584 dirname << wxT('\\');
585 #endif // defined(__DOS__) || defined(__WINDOWS__) || defined(__OS2__)
588 dirname = wxFILE_SEP_PATH;
593 if ( dir.IsOpened() )
595 wxString dirPrefix(dirname);
596 if (dirPrefix.Last() != wxFILE_SEP_PATH)
597 dirPrefix += wxFILE_SEP_PATH;
599 int hiddenFlag = m_showHidden ? wxDIR_HIDDEN : 0;
604 // Get the directories first (not matched against wildcards):
605 cont = dir.GetFirst(&f, wxEmptyString, wxDIR_DIRS | hiddenFlag);
608 wxFileData *fd = new wxFileData(dirPrefix + f, f, wxFileData::is_dir, wxFileIconsTable::folder);
609 if (Add(fd, item) != -1)
614 cont = dir.GetNext(&f);
617 // Tokenize the wildcard string, so we can handle more than 1
618 // search pattern in a wildcard.
619 wxStringTokenizer tokenWild(m_wild, wxT(";"));
620 while ( tokenWild.HasMoreTokens() )
622 cont = dir.GetFirst(&f, tokenWild.GetNextToken(),
623 wxDIR_FILES | hiddenFlag);
626 wxFileData *fd = new wxFileData(dirPrefix + f, f, wxFileData::is_file, wxFileIconsTable::file);
627 if (Add(fd, item) != -1)
632 cont = dir.GetNext(&f);
638 SortItems(m_sort_field, m_sort_forward);
641 void wxFileListCtrl::SetWild( const wxString &wild )
643 if (wild.Find(wxT('|')) != wxNOT_FOUND)
650 void wxFileListCtrl::MakeDir()
652 wxString new_name( _("NewName") );
653 wxString path( m_dirName );
654 path += wxFILE_SEP_PATH;
656 if (wxFileExists(path))
658 // try NewName0, NewName1 etc.
661 new_name = _("NewName");
663 num.Printf( wxT("%d"), i );
667 path += wxFILE_SEP_PATH;
670 } while (wxFileExists(path));
676 wxMessageDialog dialog(this, _("Operation not permitted."), _("Error"), wxOK | wxICON_ERROR );
681 wxFileData *fd = new wxFileData( path, new_name, wxFileData::is_dir, wxFileIconsTable::folder );
685 long id = Add( fd, item );
689 SortItems(m_sort_field, m_sort_forward);
690 id = FindItem( 0, wxPtrToUInt(fd) );
698 void wxFileListCtrl::GoToParentDir()
700 if (!IsTopMostDir(m_dirName))
702 size_t len = m_dirName.length();
703 if (wxEndsWithPathSeparator(m_dirName))
704 m_dirName.Remove( len-1, 1 );
705 wxString fname( wxFileNameFromPath(m_dirName) );
706 m_dirName = wxPathOnly( m_dirName );
707 #if defined(__DOS__) || defined(__WINDOWS__) || defined(__OS2__)
708 if (!m_dirName.empty())
710 if (m_dirName.Last() == wxT('.'))
711 m_dirName = wxEmptyString;
713 #elif defined(__UNIX__)
714 if (m_dirName.empty())
715 m_dirName = wxT("/");
718 long id = FindItem( 0, fname );
719 if (id != wxNOT_FOUND)
721 SetItemState( id, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
727 void wxFileListCtrl::GoToHomeDir()
729 wxString s = wxGetUserHome( wxString() );
733 void wxFileListCtrl::GoToDir( const wxString &dir )
735 if (!wxDirExists(dir)) return;
740 SetItemState( 0, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
745 void wxFileListCtrl::FreeItemData(wxListItem& item)
749 wxFileData *fd = (wxFileData*)item.m_data;
756 void wxFileListCtrl::OnListDeleteItem( wxListEvent &event )
758 FreeItemData(event.m_item);
761 void wxFileListCtrl::OnListDeleteAllItems( wxListEvent & WXUNUSED(event) )
766 void wxFileListCtrl::FreeAllItemsData()
769 item.m_mask = wxLIST_MASK_DATA;
771 item.m_itemId = GetNextItem( -1, wxLIST_NEXT_ALL );
772 while ( item.m_itemId != -1 )
776 item.m_itemId = GetNextItem( item.m_itemId, wxLIST_NEXT_ALL );
780 void wxFileListCtrl::OnListEndLabelEdit( wxListEvent &event )
782 wxFileData *fd = (wxFileData*)event.m_item.m_data;
785 if ((event.GetLabel().empty()) ||
786 (event.GetLabel() == wxT(".")) ||
787 (event.GetLabel() == wxT("..")) ||
788 (event.GetLabel().First( wxFILE_SEP_PATH ) != wxNOT_FOUND))
790 wxMessageDialog dialog(this, _("Illegal directory name."), _("Error"), wxOK | wxICON_ERROR );
796 wxString new_name( wxPathOnly( fd->GetFilePath() ) );
797 new_name += wxFILE_SEP_PATH;
798 new_name += event.GetLabel();
802 if (wxFileExists(new_name))
804 wxMessageDialog dialog(this, _("File name exists already."), _("Error"), wxOK | wxICON_ERROR );
809 if (wxRenameFile(fd->GetFilePath(),new_name))
811 fd->SetNewName( new_name, event.GetLabel() );
813 SetItemState( event.GetItem(), wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
815 UpdateItem( event.GetItem() );
816 EnsureVisible( event.GetItem() );
820 wxMessageDialog dialog(this, _("Operation not permitted."), _("Error"), wxOK | wxICON_ERROR );
826 void wxFileListCtrl::OnListColClick( wxListEvent &event )
828 int col = event.GetColumn();
832 case wxFileData::FileList_Name :
833 case wxFileData::FileList_Size :
834 case wxFileData::FileList_Type :
835 case wxFileData::FileList_Time : break;
839 if ((wxFileData::fileListFieldType)col == m_sort_field)
840 m_sort_forward = !m_sort_forward;
842 m_sort_field = (wxFileData::fileListFieldType)col;
844 SortItems(m_sort_field, m_sort_forward);
847 void wxFileListCtrl::SortItems(wxFileData::fileListFieldType field, bool forward)
849 m_sort_field = field;
850 m_sort_forward = forward;
851 const long sort_dir = forward ? 1 : -1;
853 switch (m_sort_field)
855 case wxFileData::FileList_Size :
856 wxListCtrl::SortItems(wxFileDataSizeCompare, sort_dir);
859 case wxFileData::FileList_Type :
860 wxListCtrl::SortItems(wxFileDataTypeCompare, sort_dir);
863 case wxFileData::FileList_Time :
864 wxListCtrl::SortItems(wxFileDataTimeCompare, sort_dir);
867 case wxFileData::FileList_Name :
869 wxListCtrl::SortItems(wxFileDataNameCompare, sort_dir);
874 wxFileListCtrl::~wxFileListCtrl()
876 // Normally the data are freed via an EVT_LIST_DELETE_ALL_ITEMS event and
877 // wxFileListCtrl::OnListDeleteAllItems. But if the event is generated after
878 // the destruction of the wxFileListCtrl we need to free any data here:
882 #define ID_CHOICE (wxID_FILECTRL + 1)
883 #define ID_TEXT (wxID_FILECTRL + 2)
884 #define ID_FILELIST_CTRL (wxID_FILECTRL + 3)
885 #define ID_CHECK (wxID_FILECTRL + 4)
887 ///////////////////////////////////////////////////////////////////////////////
888 // wxGenericFileCtrl implementation
889 ///////////////////////////////////////////////////////////////////////////////
891 IMPLEMENT_DYNAMIC_CLASS( wxGenericFileCtrl, wxPanel )
893 BEGIN_EVENT_TABLE( wxGenericFileCtrl, wxPanel )
894 EVT_LIST_ITEM_SELECTED( ID_FILELIST_CTRL, wxGenericFileCtrl::OnSelected )
895 EVT_LIST_ITEM_ACTIVATED( ID_FILELIST_CTRL, wxGenericFileCtrl::OnActivated )
896 EVT_CHOICE( ID_CHOICE, wxGenericFileCtrl::OnChoiceFilter )
897 EVT_TEXT_ENTER( ID_TEXT, wxGenericFileCtrl::OnTextEnter )
898 EVT_TEXT( ID_TEXT, wxGenericFileCtrl::OnTextChange )
899 EVT_CHECKBOX( ID_CHECK, wxGenericFileCtrl::OnCheck )
902 bool wxGenericFileCtrl::Create( wxWindow *parent,
904 const wxString& defaultDirectory,
905 const wxString& defaultFileName,
906 const wxString& wildCard,
910 const wxString& name )
912 this->m_style = style;
913 m_inSelected = false;
914 m_noSelChgEvent = false;
916 // check that the styles are not contradictory
917 wxASSERT_MSG( !( ( m_style & wxFC_SAVE ) && ( m_style & wxFC_OPEN ) ),
918 wxT( "can't specify both wxFC_SAVE and wxFC_OPEN at once" ) );
920 wxASSERT_MSG( !( ( m_style & wxFC_SAVE ) && ( m_style & wxFC_MULTIPLE ) ),
921 wxT( "wxFC_MULTIPLE can't be used with wxFC_SAVE" ) );
923 wxPanel::Create( parent, id, pos, size, wxTAB_TRAVERSAL, name );
925 m_dir = defaultDirectory;
927 m_ignoreChanges = true;
929 if ( ( m_dir.empty() ) || ( m_dir == wxT( "." ) ) )
933 m_dir = wxFILE_SEP_PATH;
936 const size_t len = m_dir.length();
937 if ( ( len > 1 ) && ( wxEndsWithPathSeparator( m_dir ) ) )
938 m_dir.Remove( len - 1, 1 );
940 m_filterExtension = wxEmptyString;
944 const bool is_pda = ( wxSystemSettings::GetScreenType() <= wxSYS_SCREEN_PDA );
946 wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL );
948 wxBoxSizer *staticsizer = new wxBoxSizer( wxHORIZONTAL );
950 staticsizer->Add( new wxStaticText( this, wxID_ANY, _( "Current directory:" ) ), 0, wxRIGHT, 10 );
951 m_static = new wxStaticText( this, wxID_ANY, m_dir );
952 staticsizer->Add( m_static, 1 );
953 mainsizer->Add( staticsizer, 0, wxEXPAND | wxLEFT | wxRIGHT | wxBOTTOM, 10 );
955 long style2 = wxLC_LIST;
956 if ( !( m_style & wxFC_MULTIPLE ) )
957 style2 |= wxLC_SINGLE_SEL;
960 style2 |= wxSIMPLE_BORDER;
962 style2 |= wxSUNKEN_BORDER;
965 m_list = new wxFileListCtrl( this, ID_FILELIST_CTRL,
966 wxEmptyString, false,
967 wxDefaultPosition, wxSize( 400, 140 ),
970 m_text = new wxTextCtrl( this, ID_TEXT, wxEmptyString,
971 wxDefaultPosition, wxDefaultSize,
972 wxTE_PROCESS_ENTER );
973 m_choice = new wxChoice( this, ID_CHOICE );
977 // PDAs have a different screen layout
978 mainsizer->Add( m_list, wxSizerFlags( 1 ).Expand().HorzBorder() );
980 wxBoxSizer *textsizer = new wxBoxSizer( wxHORIZONTAL );
981 textsizer->Add( m_text, wxSizerFlags( 1 ).Centre().Border() );
982 mainsizer->Add( textsizer, wxSizerFlags().Expand() );
985 textsizer->Add( m_choice, wxSizerFlags( 1 ).Centre().Border() );
989 mainsizer->Add( m_list, wxSizerFlags( 1 ).Expand().DoubleHorzBorder() );
991 wxBoxSizer *textsizer = new wxBoxSizer( wxHORIZONTAL );
992 textsizer->Add( m_text, wxSizerFlags( 1 ).Centre().
993 DoubleBorder( wxLEFT | wxRIGHT | wxTOP ) );
994 mainsizer->Add( textsizer, wxSizerFlags().Expand() );
996 wxSizerFlags flagsCentre;
997 flagsCentre.Centre().DoubleBorder();
999 wxBoxSizer *choicesizer = new wxBoxSizer( wxHORIZONTAL );
1000 choicesizer->Add( m_choice, wxSizerFlags( flagsCentre ).Proportion( 1 ) );
1002 if ( !( m_style & wxFC_NOSHOWHIDDEN ) )
1004 m_check = new wxCheckBox( this, ID_CHECK, _( "Show &hidden files" ) );
1005 choicesizer->Add( m_check, flagsCentre );
1008 mainsizer->Add( choicesizer, wxSizerFlags().Expand() );
1011 SetWildcard( wildCard );
1013 SetAutoLayout( true );
1014 SetSizer( mainsizer );
1018 mainsizer->Fit( this );
1021 m_list->GoToDir( m_dir );
1023 m_text->SetValue( m_fileName );
1025 m_ignoreChanges = false;
1027 // must be after m_ignoreChanges = false
1028 SetFilename( defaultFileName );
1033 // NB: there is an unfortunate mismatch between wxFileName and wxFileDialog
1034 // method names but our GetDirectory() does correspond to wxFileName::
1035 // GetPath() while our GetPath() is wxFileName::GetFullPath()
1036 wxString wxGenericFileCtrl::GetPath() const
1038 wxASSERT_MSG ( !(m_style & wxFC_MULTIPLE), "use GetPaths() instead" );
1040 return DoGetFileName().GetFullPath();
1043 wxString wxGenericFileCtrl::GetFilename() const
1045 wxASSERT_MSG ( !(m_style & wxFC_MULTIPLE), "use GetFilenames() instead" );
1047 return DoGetFileName().GetFullName();
1050 wxString wxGenericFileCtrl::GetDirectory() const
1052 // don't check for wxFC_MULTIPLE here, this one is probably safe to call in
1053 // any case as it can be always taken to mean "current directory"
1054 return DoGetFileName().GetPath();
1057 wxFileName wxGenericFileCtrl::DoGetFileName() const
1061 wxString value = m_text->GetValue();
1062 if ( value.empty() )
1064 // nothing in the text control, get the selected file from the list
1066 item.m_itemId = m_list->GetNextItem(-1, wxLIST_NEXT_ALL,
1067 wxLIST_STATE_SELECTED);
1068 m_list->GetItem(item);
1070 fn.Assign(m_list->GetDir(), item.m_text);
1072 else // user entered the value
1074 // the path can be either absolute or relative
1076 if ( fn.IsRelative() )
1077 fn.MakeAbsolute(m_list->GetDir());
1083 // helper used in DoGetFilenames() and needed because Borland can't compile
1084 // operator?: inline
1085 static inline wxString GetFileNameOrPath(const wxFileName& fn, bool fullPath)
1087 return fullPath ? fn.GetFullPath() : fn.GetFullName();
1091 wxGenericFileCtrl::DoGetFilenames(wxArrayString& filenames, bool fullPath) const
1095 const wxString dir = m_list->GetDir();
1097 const wxString value = m_text->GetValue();
1098 if ( !value.empty() )
1100 wxFileName fn(value);
1101 if ( fn.IsRelative() )
1102 fn.MakeAbsolute(dir);
1104 filenames.push_back(GetFileNameOrPath(fn, fullPath));
1108 const int numSel = m_list->GetSelectedItemCount();
1112 filenames.reserve(numSel);
1115 item.m_mask = wxLIST_MASK_TEXT;
1119 item.m_itemId = m_list->GetNextItem(item.m_itemId, wxLIST_NEXT_ALL,
1120 wxLIST_STATE_SELECTED);
1122 if ( item.m_itemId == -1 )
1125 m_list->GetItem(item);
1127 const wxFileName fn(dir, item.m_text);
1128 filenames.push_back(GetFileNameOrPath(fn, fullPath));
1132 bool wxGenericFileCtrl::SetDirectory( const wxString& dir )
1134 m_ignoreChanges = true;
1135 m_list->GoToDir( dir );
1137 m_ignoreChanges = false;
1139 return wxFileName( dir ).SameAs( m_list->GetDir() );
1142 bool wxGenericFileCtrl::SetFilename( const wxString& name )
1144 const long item = m_list->FindItem( -1, name );
1146 if ( item == -1 ) // file not found either because it doesn't exist or the
1147 // current filter doesn't show it.
1150 m_noSelChgEvent = true;
1152 // Deselect selected items
1154 const int numSelectedItems = m_list->GetSelectedItemCount();
1156 if ( numSelectedItems > 0 )
1158 long itemIndex = -1;
1162 itemIndex = m_list->GetNextItem( itemIndex, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );
1163 if ( itemIndex == -1 )
1166 m_list->SetItemState( itemIndex, 0, wxLIST_STATE_SELECTED );
1171 m_list->SetItemState( item, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
1172 m_list->EnsureVisible( item );
1174 m_noSelChgEvent = false;
1179 void wxGenericFileCtrl::DoSetFilterIndex( int filterindex )
1181 const wxString& str = (wx_static_cast(wxStringClientData *,
1182 m_choice->GetClientObject( filterindex )))
1184 m_list->SetWild( str );
1185 m_filterIndex = filterindex;
1186 if ( str.Left( 2 ) == wxT( "*." ) )
1188 m_filterExtension = str.Mid( 1 );
1189 if ( m_filterExtension == _T( ".*" ) )
1190 m_filterExtension.clear();
1194 m_filterExtension.clear();
1198 void wxGenericFileCtrl::SetWildcard( const wxString& wildCard )
1200 if ( wildCard.empty() || wildCard == wxFileSelectorDefaultWildcardStr )
1202 m_wildCard = wxString::Format( _( "All files (%s)|%s" ),
1203 wxFileSelectorDefaultWildcardStr,
1204 wxFileSelectorDefaultWildcardStr );
1207 m_wildCard = wildCard;
1209 wxArrayString wildDescriptions, wildFilters;
1210 const size_t count = wxParseCommonDialogsFilter( m_wildCard,
1213 wxCHECK_RET( count, wxT( "wxFileDialog: bad wildcard string" ) );
1217 for ( size_t n = 0; n < count; n++ )
1219 m_choice->Append(wildDescriptions[n], new wxStringClientData(wildFilters[n]));
1222 SetFilterIndex( 0 );
1225 void wxGenericFileCtrl::SetFilterIndex( int filterindex )
1227 m_choice->SetSelection( filterindex );
1229 DoSetFilterIndex( filterindex );
1232 void wxGenericFileCtrl::OnChoiceFilter( wxCommandEvent &event )
1234 DoSetFilterIndex( ( int )event.GetInt() );
1237 void wxGenericFileCtrl::OnCheck( wxCommandEvent &event )
1239 m_list->ShowHidden( event.GetInt() != 0 );
1242 void wxGenericFileCtrl::OnActivated( wxListEvent &event )
1244 HandleAction( event.m_item.m_text );
1247 void wxGenericFileCtrl::OnTextEnter( wxCommandEvent &WXUNUSED( event ) )
1249 HandleAction( m_text->GetValue() );
1252 void wxGenericFileCtrl::OnTextChange( wxCommandEvent &WXUNUSED( event ) )
1254 if ( !m_ignoreChanges )
1256 // Clear selections. Otherwise when the user types in a value they may
1257 // not get the file whose name they typed.
1258 if ( m_list->GetSelectedItemCount() > 0 )
1260 long item = m_list->GetNextItem( -1, wxLIST_NEXT_ALL,
1261 wxLIST_STATE_SELECTED );
1262 while ( item != -1 )
1264 m_list->SetItemState( item, 0, wxLIST_STATE_SELECTED );
1265 item = m_list->GetNextItem( item, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );
1271 void wxGenericFileCtrl::OnSelected( wxListEvent &event )
1273 if ( m_ignoreChanges )
1279 m_inSelected = true;
1280 const wxString filename( event.m_item.m_text );
1283 // No double-click on most WinCE devices, so do action immediately.
1284 HandleAction( filename );
1286 if ( filename == wxT( ".." ) )
1288 m_inSelected = false;
1292 wxString dir = m_list->GetDir();
1293 if ( !IsTopMostDir( dir ) )
1294 dir += wxFILE_SEP_PATH;
1296 if ( wxDirExists( dir ) )
1298 m_inSelected = false;
1304 m_ignoreChanges = true;
1305 m_text->SetValue( filename );
1307 if ( m_list->GetSelectedItemCount() > 1 )
1312 if ( !m_noSelChgEvent )
1313 GenerateSelectionChangedEvent( this, this );
1315 m_ignoreChanges = false;
1317 m_inSelected = false;
1320 void wxGenericFileCtrl::HandleAction( const wxString &fn )
1322 if ( m_ignoreChanges )
1325 wxString filename( fn );
1326 if ( filename.empty() )
1330 if ( filename == wxT( "." ) ) return;
1332 wxString dir = m_list->GetDir();
1334 // "some/place/" means they want to chdir not try to load "place"
1335 const bool want_dir = filename.Last() == wxFILE_SEP_PATH;
1337 filename = filename.RemoveLast();
1339 if ( filename == wxT( ".." ) )
1341 m_ignoreChanges = true;
1342 m_list->GoToParentDir();
1344 GenerateFolderChangedEvent( this, this );
1347 m_ignoreChanges = false;
1352 if ( filename == wxT( "~" ) )
1354 m_ignoreChanges = true;
1355 m_list->GoToHomeDir();
1357 GenerateFolderChangedEvent( this, this );
1360 m_ignoreChanges = false;
1364 if ( filename.BeforeFirst( wxT( '/' ) ) == wxT( "~" ) )
1366 filename = wxString( wxGetUserHome() ) + filename.Remove( 0, 1 );
1370 if ( !( m_style & wxFC_SAVE ) )
1372 if ( ( filename.Find( wxT( '*' ) ) != wxNOT_FOUND ) ||
1373 ( filename.Find( wxT( '?' ) ) != wxNOT_FOUND ) )
1375 if ( filename.Find( wxFILE_SEP_PATH ) != wxNOT_FOUND )
1377 wxMessageBox( _( "Illegal file specification." ),
1378 _( "Error" ), wxOK | wxICON_ERROR, this );
1381 m_list->SetWild( filename );
1386 if ( !IsTopMostDir( dir ) )
1387 dir += wxFILE_SEP_PATH;
1388 if ( !wxIsAbsolutePath( filename ) )
1394 if ( wxDirExists( filename ) )
1396 m_ignoreChanges = true;
1397 m_list->GoToDir( filename );
1400 GenerateFolderChangedEvent( this, this );
1402 m_ignoreChanges = false;
1406 // they really wanted a dir, but it doesn't exist
1409 wxMessageBox( _( "Directory doesn't exist." ), _( "Error" ),
1410 wxOK | wxICON_ERROR, this );
1414 // append the default extension to the filename if it doesn't have any
1416 // VZ: the logic of testing for !wxFileExists() only for the open file
1417 // dialog is not entirely clear to me, why don't we allow saving to a
1418 // file without extension as well?
1419 if ( !( m_style & wxFC_OPEN ) || !wxFileExists( filename ) )
1421 filename = wxFileDialogBase::AppendExtension( filename, m_filterExtension );
1422 GenerateFileActivatedEvent( this, this, wxFileName( filename ).GetFullName() );
1426 GenerateFileActivatedEvent( this, this );
1429 bool wxGenericFileCtrl::SetPath( const wxString& path )
1431 if ( !wxFileName::FileExists( ( path ) ) )
1435 wxSplitPath( path, &m_dir, &m_fileName, &ext );
1438 m_fileName += wxT( "." );
1442 SetDirectory( m_dir );
1443 SetFilename( m_fileName );
1448 void wxGenericFileCtrl::GetPaths( wxArrayString& paths ) const
1450 DoGetFilenames( paths, true );
1453 void wxGenericFileCtrl::GetFilenames( wxArrayString& files ) const
1455 DoGetFilenames( files, false );
1458 void wxGenericFileCtrl::UpdateControls()
1460 const wxString dir = m_list->GetDir();
1461 m_static->SetLabel( dir );
1464 void wxGenericFileCtrl::GoToParentDir()
1466 m_list->GoToParentDir();
1470 void wxGenericFileCtrl::GoToHomeDir()
1472 m_list->GoToHomeDir();
1476 #endif // wxUSE_FILECTRL