don't call stat() *and* lstat() (as if the file dialog wasn't already slow enough...
[wxWidgets.git] / src / generic / filedlgg.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: filedlgg.cpp
3 // Purpose: wxFileDialog
4 // Author: Robert Roebling
5 // Modified by:
6 // Created: 12/12/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Robert Roebling
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #ifdef __GNUG__
21 #pragma implementation "filedlgg.h"
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #ifdef __BORLANDC__
28 #pragma hdrstop
29 #endif
30
31 #if wxUSE_FILEDLG
32
33 #if !defined(__UNIX__) && !defined(__DOS__) && !defined(__WIN32__)
34 #error wxFileDialog currently only supports Unix, win32 and DOS
35 #endif
36
37 #include "wx/checkbox.h"
38 #include "wx/textctrl.h"
39 #include "wx/choice.h"
40 #include "wx/checkbox.h"
41 #include "wx/stattext.h"
42 #include "wx/filedlg.h"
43 #include "wx/debug.h"
44 #include "wx/log.h"
45 #include "wx/intl.h"
46 #include "wx/listctrl.h"
47 #include "wx/msgdlg.h"
48 #include "wx/sizer.h"
49 #include "wx/bmpbuttn.h"
50 #include "wx/tokenzr.h"
51 #include "wx/mimetype.h"
52 #include "wx/image.h"
53 #include "wx/module.h"
54 #include "wx/config.h"
55 #include "wx/imaglist.h"
56 #include "wx/dir.h"
57 #include "wx/artprov.h"
58
59 #if wxUSE_TOOLTIPS
60 #include "wx/tooltip.h"
61 #endif
62
63 #include <sys/types.h>
64 #include <sys/stat.h>
65
66 #ifdef __UNIX__
67 #include <dirent.h>
68 #include <pwd.h>
69 #ifndef __VMS
70 # include <grp.h>
71 #endif
72 #endif
73
74 #ifdef __WATCOMC__
75 #include <direct.h>
76 #endif
77
78 #include <time.h>
79 #if defined(__UNIX__) || defined(__DOS__)
80 #include <unistd.h>
81 #endif
82
83 // ----------------------------------------------------------------------------
84 // constants
85 // ----------------------------------------------------------------------------
86
87 // the list ctrl fields in report view
88 enum FileListField
89 {
90 FileList_Name,
91 FileList_Type,
92 FileList_Date,
93 FileList_Time,
94 #ifdef __UNIX__
95 FileList_Perm,
96 #endif // __UNIX__
97 FileList_Max
98 };
99
100 //-----------------------------------------------------------------------------
101 // wxFileData
102 //-----------------------------------------------------------------------------
103
104 class wxFileData
105 {
106 public:
107 wxFileData( const wxString &name, const wxString &fname );
108 wxString GetName() const;
109 wxString GetFullName() const;
110 wxString GetHint() const;
111 wxString GetEntry( FileListField num ) const;
112
113 bool IsDir() const { return m_isDir; }
114 bool IsLink() const { return m_isLink; }
115 bool IsExe() const { return m_isExe; }
116 long GetSize() const { return m_size; }
117
118 void MakeItem( wxListItem &item );
119 void SetNewName( const wxString &name, const wxString &fname );
120
121 private:
122 wxString m_name;
123 wxString m_fileName;
124 long m_size;
125 int m_hour;
126 int m_minute;
127 int m_year;
128 int m_month;
129 int m_day;
130 wxString m_permissions;
131 bool m_isDir;
132 bool m_isLink;
133 bool m_isExe;
134 };
135
136 //-----------------------------------------------------------------------------
137 // wxFileCtrl
138 //-----------------------------------------------------------------------------
139
140 class wxFileCtrl : public wxListCtrl
141 {
142 public:
143 wxFileCtrl();
144 wxFileCtrl( wxWindow *win,
145 wxStaticText *labelDir,
146 wxWindowID id,
147 const wxString &wild,
148 bool showHidden,
149 const wxPoint &pos = wxDefaultPosition,
150 const wxSize &size = wxDefaultSize,
151 long style = wxLC_LIST,
152 const wxValidator &validator = wxDefaultValidator,
153 const wxString &name = wxT("filelist") );
154 virtual ~wxFileCtrl();
155
156 void ChangeToListMode();
157 void ChangeToReportMode();
158 void ChangeToIconMode();
159 void ShowHidden( bool show = TRUE );
160 long Add( wxFileData *fd, wxListItem &item );
161 void UpdateFiles();
162 virtual void StatusbarText( wxChar *WXUNUSED(text) ) {};
163 void MakeDir();
164 void GoToParentDir();
165 void GoToHomeDir();
166 void GoToDir( const wxString &dir );
167 void SetWild( const wxString &wild );
168 void GetDir( wxString &dir );
169 void OnListDeleteItem( wxListEvent &event );
170 void OnListEndLabelEdit( wxListEvent &event );
171
172 // Associate commonly used UI controls with wxFileCtrl so that they can be
173 // disabled when they cannot be used (e.g. can't go to parent directory
174 // if wxFileCtrl already is in the root dir):
175 void SetGoToParentControl(wxWindow *ctrl) { m_goToParentControl = ctrl; }
176 void SetNewDirControl(wxWindow *ctrl) { m_newDirControl = ctrl; }
177
178 private:
179 void FreeItemData(const wxListItem& item);
180 void FreeAllItemsData();
181
182 wxString m_dirName;
183 bool m_showHidden;
184 wxString m_wild;
185
186 wxWindow *m_goToParentControl;
187 wxWindow *m_newDirControl;
188
189 // the label showing the current directory
190 wxStaticText *m_labelDir;
191
192 DECLARE_DYNAMIC_CLASS(wxFileCtrl);
193 DECLARE_EVENT_TABLE()
194 };
195
196 // ----------------------------------------------------------------------------
197 // private classes - icons list management
198 // ----------------------------------------------------------------------------
199
200 class wxFileIconEntry : public wxObject
201 {
202 public:
203 wxFileIconEntry(int i) { id = i; }
204
205 int id;
206 };
207
208
209 class wxFileIconsTable
210 {
211 public:
212 wxFileIconsTable();
213
214 int GetIconID(const wxString& extension, const wxString& mime = wxEmptyString);
215 wxImageList *GetImageList() { return &m_ImageList; }
216
217 protected:
218 wxImageList m_ImageList;
219 wxHashTable m_HashTable;
220 };
221
222 static wxFileIconsTable *g_IconsTable = NULL;
223
224 #define FI_FOLDER 0
225 #define FI_UNKNOWN 1
226 #define FI_EXECUTABLE 2
227
228 wxFileIconsTable::wxFileIconsTable() :
229 m_ImageList(16, 16),
230 m_HashTable(wxKEY_STRING)
231 {
232 m_HashTable.DeleteContents(TRUE);
233 // FI_FOLDER:
234 m_ImageList.Add(wxArtProvider::GetBitmap(wxART_FOLDER, wxART_CMN_DIALOG));
235 // FI_UNKNOWN:
236 m_ImageList.Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE, wxART_CMN_DIALOG));
237 // FI_EXECUTABLE:
238 if (GetIconID(wxEmptyString, _T("application/x-executable")) == FI_UNKNOWN)
239 {
240 m_ImageList.Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE, wxART_CMN_DIALOG));
241 m_HashTable.Delete(_T("exe"));
242 m_HashTable.Put(_T("exe"), new wxFileIconEntry(FI_EXECUTABLE));
243 }
244 /* else put into list by GetIconID
245 (KDE defines application/x-executable for *.exe and has nice icon)
246 */
247 }
248
249
250
251 #if wxUSE_MIMETYPE
252 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
253 // one icon and we won't resize it
254
255 static wxBitmap CreateAntialiasedBitmap(const wxImage& img)
256 {
257 wxImage smallimg (16, 16);
258 unsigned char *p1, *p2, *ps;
259 unsigned char mr = img.GetMaskRed(),
260 mg = img.GetMaskGreen(),
261 mb = img.GetMaskBlue();
262
263 unsigned x, y;
264 unsigned sr, sg, sb, smask;
265
266 p1 = img.GetData(), p2 = img.GetData() + 3 * 32, ps = smallimg.GetData();
267 smallimg.SetMaskColour(mr, mr, mr);
268
269 for (y = 0; y < 16; y++)
270 {
271 for (x = 0; x < 16; x++)
272 {
273 sr = sg = sb = smask = 0;
274 if (p1[0] != mr || p1[1] != mg || p1[2] != mb)
275 sr += p1[0], sg += p1[1], sb += p1[2];
276 else smask++;
277 p1 += 3;
278 if (p1[0] != mr || p1[1] != mg || p1[2] != mb)
279 sr += p1[0], sg += p1[1], sb += p1[2];
280 else smask++;
281 p1 += 3;
282 if (p2[0] != mr || p2[1] != mg || p2[2] != mb)
283 sr += p2[0], sg += p2[1], sb += p2[2];
284 else smask++;
285 p2 += 3;
286 if (p2[0] != mr || p2[1] != mg || p2[2] != mb)
287 sr += p2[0], sg += p2[1], sb += p2[2];
288 else smask++;
289 p2 += 3;
290
291 if (smask > 2)
292 ps[0] = ps[1] = ps[2] = mr;
293 else
294 ps[0] = sr >> 2, ps[1] = sg >> 2, ps[2] = sb >> 2;
295 ps += 3;
296 }
297 p1 += 32 * 3, p2 += 32 * 3;
298 }
299
300 return wxBitmap(smallimg);
301 }
302
303 // finds empty borders and return non-empty area of image:
304 static wxImage CutEmptyBorders(const wxImage& img)
305 {
306 unsigned char mr = img.GetMaskRed(),
307 mg = img.GetMaskGreen(),
308 mb = img.GetMaskBlue();
309 unsigned char *dt = img.GetData(), *dttmp;
310 unsigned w = img.GetWidth(), h = img.GetHeight();
311
312 unsigned top, bottom, left, right, i;
313 bool empt;
314
315 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
316 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = FALSE; break;}
317
318 for (empt = TRUE, top = 0; empt && top < h; top++)
319 {
320 MK_DTTMP(0, top);
321 for (i = 0; i < w; i++, dttmp+=3)
322 NOEMPTY_PIX(empt)
323 }
324 for (empt = TRUE, bottom = h-1; empt && bottom > top; bottom--)
325 {
326 MK_DTTMP(0, bottom);
327 for (i = 0; i < w; i++, dttmp+=3)
328 NOEMPTY_PIX(empt)
329 }
330 for (empt = TRUE, left = 0; empt && left < w; left++)
331 {
332 MK_DTTMP(left, 0);
333 for (i = 0; i < h; i++, dttmp+=3*w)
334 NOEMPTY_PIX(empt)
335 }
336 for (empt = TRUE, right = w-1; empt && right > left; right--)
337 {
338 MK_DTTMP(right, 0);
339 for (i = 0; i < h; i++, dttmp+=3*w)
340 NOEMPTY_PIX(empt)
341 }
342 top--, left--, bottom++, right++;
343
344 return img.GetSubImage(wxRect(left, top, right - left + 1, bottom - top + 1));
345 }
346 #endif // wxUSE_MIMETYPE
347
348
349
350 int wxFileIconsTable::GetIconID(const wxString& extension, const wxString& mime)
351 {
352 #if wxUSE_MIMETYPE
353 if (!extension.IsEmpty())
354 {
355 wxFileIconEntry *entry = (wxFileIconEntry*) m_HashTable.Get(extension);
356 if (entry) return (entry -> id);
357 }
358
359 wxFileType *ft = (mime.IsEmpty()) ?
360 wxTheMimeTypesManager -> GetFileTypeFromExtension(extension) :
361 wxTheMimeTypesManager -> GetFileTypeFromMimeType(mime);
362 wxIcon ic;
363 if (ft == NULL || (!ft -> GetIcon(&ic)) || (!ic.Ok()))
364 {
365 int newid = FI_UNKNOWN;
366 m_HashTable.Put(extension, new wxFileIconEntry(newid));
367 return newid;
368 }
369 #ifdef __WIN32__
370 wxBitmap myBitmap (ic.GetWidth(), ic.GetHeight() ) ;
371 wxMemoryDC memDC;
372 memDC.SelectObject( myBitmap );
373 memDC.DrawIcon(ic,0,0);
374 memDC.SelectObject( wxNullBitmap );
375 wxImage img = myBitmap.ConvertToImage();
376 #else
377 wxImage img = ic.ConvertToImage();
378 #endif
379 delete ft;
380
381 int id = m_ImageList.GetImageCount();
382 if (img.GetWidth() == 16 && img.GetHeight() == 16)
383 m_ImageList.Add(wxBitmap(img));
384 else
385 {
386 if (img.GetWidth() != 32 || img.GetHeight() != 32)
387 m_ImageList.Add(CreateAntialiasedBitmap(CutEmptyBorders(img).Rescale(32, 32)));
388 else
389 m_ImageList.Add(CreateAntialiasedBitmap(img));
390 }
391 m_HashTable.Put(extension, new wxFileIconEntry(id));
392 return id;
393
394 #else // !wxUSE_MIMETYPE
395
396 if (extension == wxT("exe"))
397 return FI_EXECUTABLE;
398 else
399 return FI_UNKNOWN;
400 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
401 }
402
403
404
405 // ----------------------------------------------------------------------------
406 // private functions
407 // ----------------------------------------------------------------------------
408
409 static
410 int ListCompare( long data1, long data2, long WXUNUSED(data))
411 {
412 wxFileData *fd1 = (wxFileData*)data1 ;
413 wxFileData *fd2 = (wxFileData*)data2 ;
414 if (fd1->GetName() == wxT("..")) return -1;
415 if (fd2->GetName() == wxT("..")) return 1;
416 if (fd1->IsDir() && !fd2->IsDir()) return -1;
417 if (fd2->IsDir() && !fd1->IsDir()) return 1;
418 return wxStrcmp( fd1->GetName(), fd2->GetName() );
419 }
420
421 #ifdef __UNIX__
422 #define IsTopMostDir(dir) (dir == wxT("/"))
423 #endif
424
425 #if defined(__DOS__) || defined(__WINDOWS__)
426 #define IsTopMostDir(dir) (dir.IsEmpty())
427 #endif
428
429 #if defined(__DOS__) || defined(__WINDOWS__)
430 extern bool wxIsDriveAvailable(const wxString& dirName);
431 #endif
432
433 //-----------------------------------------------------------------------------
434 // wxFileData
435 //-----------------------------------------------------------------------------
436
437 wxFileData::wxFileData( const wxString &name, const wxString &fname )
438 {
439 m_name = name;
440 m_fileName = fname;
441
442 #if defined(__DOS__) || defined(__WINDOWS__)
443 // VS: In case the file is root directory of a volume (e.g. "C:"),
444 // we don't want it stat()ed, since the drive may not be in:
445 if (name.length() == 2 && name[1u] == wxT(':'))
446 {
447 m_isDir = TRUE;
448 m_isExe =
449 m_isLink = FALSE;
450 m_size = 0;
451 return;
452 }
453 #endif // __DOS__ || __WINDOWS__
454
455 wxStructStat buff;
456
457 #if defined(__UNIX__) && (!defined( __EMX__ ) && !defined(__VMS))
458 lstat( m_fileName.fn_str(), &buff );
459 m_isLink = S_ISLNK( buff.st_mode );
460 #else // no lstat()
461 wxStat( m_fileName, &buff );
462 m_isLink = FALSE;
463 #endif
464
465 m_isDir = (buff.st_mode & S_IFDIR) != 0;
466 m_isExe = (buff.st_mode & wxS_IXUSR) != 0;
467
468 m_size = buff.st_size;
469
470 const struct tm * const t = localtime( &buff.st_mtime );
471 m_hour = t->tm_hour;
472 m_minute = t->tm_min;
473 m_month = t->tm_mon+1;
474 m_day = t->tm_mday;
475 m_year = t->tm_year;
476 m_year += 1900;
477
478 m_permissions.Printf(_T("%c%c%c"),
479 buff.st_mode & wxS_IRUSR ? _T('r') : _T('-'),
480 buff.st_mode & wxS_IWUSR ? _T('w') : _T('-'),
481 buff.st_mode & wxS_IXUSR ? _T('x') : _T('-'));
482 }
483
484 wxString wxFileData::GetName() const
485 {
486 return m_name;
487 }
488
489 wxString wxFileData::GetFullName() const
490 {
491 return m_fileName;
492 }
493
494 wxString wxFileData::GetHint() const
495 {
496 wxString s = m_fileName;
497 s += wxT(" ");
498 if (m_isDir) s += wxT("<DIR> ");
499 else if (m_isLink) s += wxT("<LINK> ");
500 else
501 {
502 s += LongToString( m_size );
503 s += wxT(" bytes ");
504 }
505 s += IntToString( m_day );
506 s += wxT(".");
507 s += IntToString( m_month );
508 s += wxT(".");
509 s += IntToString( m_year );
510 s += wxT(" ");
511 s += IntToString( m_hour );
512 s += wxT(":");
513 s += IntToString( m_minute );
514 s += wxT(" ");
515 s += m_permissions;
516 return s;
517 };
518
519 wxString wxFileData::GetEntry( FileListField num ) const
520 {
521 wxString s;
522 switch ( num )
523 {
524 case FileList_Name:
525 s = m_name;
526 break;
527
528 case FileList_Type:
529 if (m_isDir)
530 s = _("<DIR>");
531 else if (m_isLink)
532 s = _("<LINK>");
533 else
534 s.Printf(_T("%ld"), m_size);
535 break;
536
537 case FileList_Date:
538 s.Printf(_T("%02d.%02d.%d"), m_day, m_month, m_year);
539 break;
540
541 case FileList_Time:
542 s.Printf(_T("%02d:%02d"), m_hour, m_minute);
543 break;
544
545 #ifdef __UNIX__
546 case FileList_Perm:
547 s = m_permissions;
548 break;
549 #endif // __UNIX__
550
551 default:
552 wxFAIL_MSG( _T("unexpected field in wxFileData::GetEntry()") );
553 }
554
555 return s;
556 }
557
558 void wxFileData::SetNewName( const wxString &name, const wxString &fname )
559 {
560 m_name = name;
561 m_fileName = fname;
562 }
563
564 void wxFileData::MakeItem( wxListItem &item )
565 {
566 item.m_text = m_name;
567 item.ClearAttributes();
568 if (IsExe())
569 item.SetTextColour(*wxRED);
570 if (IsDir())
571 item.SetTextColour(*wxBLUE);
572
573 if (IsDir())
574 item.m_image = FI_FOLDER;
575 else if (IsExe())
576 item.m_image = FI_EXECUTABLE;
577 else if (m_name.Find(wxT('.')) != wxNOT_FOUND)
578 item.m_image = g_IconsTable->GetIconID(m_name.AfterLast(wxT('.')));
579 else
580 item.m_image = FI_UNKNOWN;
581
582 if (IsLink())
583 {
584 wxColour *dg = wxTheColourDatabase->FindColour( _T("MEDIUM GREY") );
585 item.SetTextColour(*dg);
586 }
587 item.m_data = (long)this;
588 }
589
590 //-----------------------------------------------------------------------------
591 // wxFileCtrl
592 //-----------------------------------------------------------------------------
593
594 IMPLEMENT_DYNAMIC_CLASS(wxFileCtrl,wxListCtrl)
595
596 BEGIN_EVENT_TABLE(wxFileCtrl,wxListCtrl)
597 EVT_LIST_DELETE_ITEM(-1, wxFileCtrl::OnListDeleteItem)
598 EVT_LIST_END_LABEL_EDIT(-1, wxFileCtrl::OnListEndLabelEdit)
599 END_EVENT_TABLE()
600
601
602 wxFileCtrl::wxFileCtrl()
603 {
604 m_showHidden = FALSE;
605 }
606
607 wxFileCtrl::wxFileCtrl(wxWindow *win,
608 wxStaticText *labelDir,
609 wxWindowID id,
610 const wxString& wild,
611 bool showHidden,
612 const wxPoint& pos,
613 const wxSize& size,
614 long style,
615 const wxValidator &validator,
616 const wxString &name)
617 : wxListCtrl(win, id, pos, size, style, validator, name),
618 m_wild(wild)
619 {
620 if (! g_IconsTable)
621 g_IconsTable = new wxFileIconsTable;
622 wxImageList *imageList = g_IconsTable->GetImageList();
623
624 SetImageList( imageList, wxIMAGE_LIST_SMALL );
625
626 m_goToParentControl =
627 m_newDirControl = NULL;
628
629 m_labelDir = labelDir;
630
631 m_showHidden = showHidden;
632 }
633
634 void wxFileCtrl::ChangeToListMode()
635 {
636 SetSingleStyle( wxLC_LIST );
637 UpdateFiles();
638 }
639
640 void wxFileCtrl::ChangeToReportMode()
641 {
642 SetSingleStyle( wxLC_REPORT );
643 UpdateFiles();
644 }
645
646 void wxFileCtrl::ChangeToIconMode()
647 {
648 SetSingleStyle( wxLC_ICON );
649 UpdateFiles();
650 }
651
652 void wxFileCtrl::ShowHidden( bool show )
653 {
654 m_showHidden = show;
655 UpdateFiles();
656 }
657
658 long wxFileCtrl::Add( wxFileData *fd, wxListItem &item )
659 {
660 long ret = -1;
661 item.m_mask = wxLIST_MASK_TEXT + wxLIST_MASK_DATA + wxLIST_MASK_IMAGE;
662 fd->MakeItem( item );
663 long my_style = GetWindowStyleFlag();
664 if (my_style & wxLC_REPORT)
665 {
666 ret = InsertItem( item );
667 for (int i = 1; i < FileList_Max; i++)
668 SetItem( item.m_itemId, i, fd->GetEntry((FileListField)i) );
669 }
670 else if (my_style & wxLC_LIST)
671 {
672 ret = InsertItem( item );
673 }
674 return ret;
675 }
676
677 void wxFileCtrl::UpdateFiles()
678 {
679 // don't do anything before ShowModal() call which sets m_dirName
680 if ( m_dirName.empty() )
681 return;
682
683 wxBusyCursor bcur; // this may take a while...
684
685 long my_style = GetWindowStyleFlag();
686 int name_col_width = 0;
687 if (my_style & wxLC_REPORT)
688 {
689 if (GetColumnCount() > 0)
690 name_col_width = GetColumnWidth( 0 );
691 }
692
693 FreeAllItemsData();
694 ClearAll();
695
696 if (my_style & wxLC_REPORT)
697 {
698 if (name_col_width < 140) name_col_width = 140;
699 InsertColumn( 0, _("Name"), wxLIST_FORMAT_LEFT, name_col_width );
700 InsertColumn( 1, _("Size"), wxLIST_FORMAT_LEFT, 60 );
701 InsertColumn( 2, _("Date"), wxLIST_FORMAT_LEFT, 65 );
702 InsertColumn( 3, _("Time"), wxLIST_FORMAT_LEFT, 50 );
703 #ifdef __UNIX__
704 InsertColumn( 4, _("Permissions"), wxLIST_FORMAT_LEFT, 120 );
705 #endif
706 }
707 wxFileData *fd = (wxFileData *) NULL;
708 wxListItem item;
709 item.m_itemId = 0;
710 item.m_col = 0;
711
712 #if defined(__DOS__) || defined(__WINDOWS__)
713 if ( IsTopMostDir(m_dirName) )
714 {
715 // Pseudo-directory with all available drives listed...
716 for (int drive = 1; drive <= 26; drive++)
717 {
718 wxString path;
719 path.Printf(wxT("%c:\\"), (char)(drive + 'A' - 1));
720 if ( wxIsDriveAvailable(path) )
721 {
722 path.RemoveLast();
723 fd = new wxFileData(path, path);
724 Add(fd, item);
725 item.m_itemId++;
726 }
727 }
728 }
729 else
730 #endif
731 {
732 // Real directory...
733 if ( !IsTopMostDir(m_dirName) )
734 {
735 wxString p(wxPathOnly(m_dirName));
736 #ifdef __UNIX__
737 if (p.IsEmpty()) p = wxT("/");
738 #endif
739 fd = new wxFileData( wxT(".."), p );
740 Add(fd, item);
741 item.m_itemId++;
742 }
743
744 wxString dirname(m_dirName);
745 #if defined(__DOS__) || defined(__WINDOWS__)
746 if (dirname.length() == 2 && dirname[1u] == wxT(':'))
747 dirname << wxT('\\');
748 #endif
749 wxDir dir(dirname);
750
751 if ( dir.IsOpened() )
752 {
753 wxString dirPrefix(dirname + wxFILE_SEP_PATH);
754 int hiddenFlag = m_showHidden ? wxDIR_HIDDEN : 0;
755
756 bool cont;
757 wxString f;
758
759 // Get the directories first (not matched against wildcards):
760 cont = dir.GetFirst(&f, wxEmptyString, wxDIR_DIRS | hiddenFlag);
761 while (cont)
762 {
763 fd = new wxFileData(f, dirPrefix + f);
764 Add(fd, item);
765 item.m_itemId++;
766 cont = dir.GetNext(&f);
767 }
768
769 // Tokenize the wildcard string, so we can handle more than 1
770 // search pattern in a wildcard.
771 wxStringTokenizer tokenWild(m_wild, wxT(";"));
772 while ( tokenWild.HasMoreTokens() )
773 {
774 cont = dir.GetFirst(&f, tokenWild.GetNextToken(),
775 wxDIR_FILES | hiddenFlag);
776 while (cont)
777 {
778 fd = new wxFileData(f, dirPrefix + f);
779 Add(fd, item);
780 item.m_itemId++;
781 cont = dir.GetNext(&f);
782 }
783 }
784 }
785 }
786
787 SortItems((wxListCtrlCompare)ListCompare, 0);
788
789 if ( my_style & wxLC_REPORT )
790 {
791 SetColumnWidth(1, wxLIST_AUTOSIZE);
792 SetColumnWidth(2, wxLIST_AUTOSIZE);
793 SetColumnWidth(3, wxLIST_AUTOSIZE);
794 }
795
796 // Finally, enable/disable context-dependent controls:
797 if ( m_goToParentControl )
798 m_goToParentControl->Enable(!IsTopMostDir(m_dirName));
799 #if defined(__DOS__) || defined(__WINDOWS__)
800 if ( m_newDirControl )
801 m_newDirControl->Enable(!IsTopMostDir(m_dirName));
802 #endif
803 }
804
805 void wxFileCtrl::SetWild( const wxString &wild )
806 {
807 m_wild = wild;
808 UpdateFiles();
809 }
810
811 void wxFileCtrl::MakeDir()
812 {
813 wxString new_name( _("NewName") );
814 wxString path( m_dirName );
815 path += wxFILE_SEP_PATH;
816 path += new_name;
817 if (wxFileExists(path))
818 {
819 // try NewName0, NewName1 etc.
820 int i = 0;
821 do {
822 new_name = _("NewName");
823 wxString num;
824 num.Printf( wxT("%d"), i );
825 new_name += num;
826
827 path = m_dirName;
828 path += wxFILE_SEP_PATH;
829 path += new_name;
830 i++;
831 } while (wxFileExists(path));
832 }
833
834 wxLogNull log;
835 if (!wxMkdir(path))
836 {
837 wxMessageDialog dialog(this, _("Operation not permitted."), _("Error"), wxOK | wxICON_ERROR );
838 dialog.ShowModal();
839 return;
840 }
841
842 wxFileData *fd = new wxFileData( new_name, path );
843 wxListItem item;
844 item.m_itemId = 0;
845 item.m_col = 0;
846 long id = Add( fd, item );
847
848 if (id != -1)
849 {
850 SortItems( (wxListCtrlCompare) ListCompare, 0 );
851 id = FindItem( 0, (long)fd );
852 EnsureVisible( id );
853 EditLabel( id );
854 }
855 }
856
857 void wxFileCtrl::GoToParentDir()
858 {
859 if (!IsTopMostDir(m_dirName))
860 {
861 size_t len = m_dirName.Len();
862 if (m_dirName[len-1] == wxFILE_SEP_PATH)
863 m_dirName.Remove( len-1, 1 );
864 wxString fname( wxFileNameFromPath(m_dirName) );
865 m_dirName = wxPathOnly( m_dirName );
866 #ifdef __UNIX__
867 if (m_dirName.IsEmpty())
868 m_dirName = wxT("/");
869 #endif
870 UpdateFiles();
871 long id = FindItem( 0, fname );
872 if (id != -1)
873 {
874 SetItemState( id, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
875 EnsureVisible( id );
876 }
877
878 m_labelDir->SetLabel(m_dirName);
879 }
880 }
881
882 void wxFileCtrl::GoToHomeDir()
883 {
884 wxString s = wxGetUserHome( wxString() );
885 GoToDir(s);
886 }
887
888 void wxFileCtrl::GoToDir( const wxString &dir )
889 {
890 m_dirName = dir;
891 UpdateFiles();
892 SetItemState( 0, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
893 EnsureVisible( 0 );
894
895 m_labelDir->SetLabel(dir);
896 }
897
898 void wxFileCtrl::GetDir( wxString &dir )
899 {
900 dir = m_dirName;
901 }
902
903 void wxFileCtrl::FreeItemData(const wxListItem& item)
904 {
905 wxFileData *fd = (wxFileData*)item.m_data;
906 delete fd;
907 }
908
909 void wxFileCtrl::OnListDeleteItem( wxListEvent &event )
910 {
911 FreeItemData(event.m_item);
912 }
913
914 void wxFileCtrl::FreeAllItemsData()
915 {
916 wxListItem item;
917 item.m_mask = wxLIST_MASK_DATA;
918
919 item.m_itemId = GetNextItem( -1, wxLIST_NEXT_ALL );
920 while ( item.m_itemId != -1 )
921 {
922 GetItem( item );
923 FreeItemData(item);
924 item.m_itemId = GetNextItem( item.m_itemId, wxLIST_NEXT_ALL );
925 }
926 }
927
928 void wxFileCtrl::OnListEndLabelEdit( wxListEvent &event )
929 {
930 wxFileData *fd = (wxFileData*)event.m_item.m_data;
931 wxASSERT( fd );
932
933 if ((event.GetLabel().IsEmpty()) ||
934 (event.GetLabel() == _(".")) ||
935 (event.GetLabel() == _("..")) ||
936 (event.GetLabel().First( wxFILE_SEP_PATH ) != wxNOT_FOUND))
937 {
938 wxMessageDialog dialog(this, _("Illegal directory name."), _("Error"), wxOK | wxICON_ERROR );
939 dialog.ShowModal();
940 event.Veto();
941 return;
942 }
943
944 wxString new_name( wxPathOnly( fd->GetFullName() ) );
945 new_name += wxFILE_SEP_PATH;
946 new_name += event.GetLabel();
947
948 wxLogNull log;
949
950 if (wxFileExists(new_name))
951 {
952 wxMessageDialog dialog(this, _("File name exists already."), _("Error"), wxOK | wxICON_ERROR );
953 dialog.ShowModal();
954 event.Veto();
955 }
956
957 if (wxRenameFile(fd->GetFullName(),new_name))
958 {
959 fd->SetNewName( new_name, event.GetLabel() );
960 SetItemState( event.GetItem(), wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
961 EnsureVisible( event.GetItem() );
962 }
963 else
964 {
965 wxMessageDialog dialog(this, _("Operation not permitted."), _("Error"), wxOK | wxICON_ERROR );
966 dialog.ShowModal();
967 event.Veto();
968 }
969 }
970
971 wxFileCtrl::~wxFileCtrl()
972 {
973 FreeAllItemsData();
974 }
975
976 //-----------------------------------------------------------------------------
977 // wxFileDialog
978 //-----------------------------------------------------------------------------
979
980 #define ID_LIST_MODE (wxID_FILEDLGG )
981 #define ID_REPORT_MODE (wxID_FILEDLGG + 1)
982 #define ID_UP_DIR (wxID_FILEDLGG + 5)
983 #define ID_PARENT_DIR (wxID_FILEDLGG + 6)
984 #define ID_NEW_DIR (wxID_FILEDLGG + 7)
985 #define ID_CHOICE (wxID_FILEDLGG + 8)
986 #define ID_TEXT (wxID_FILEDLGG + 9)
987 #define ID_LIST_CTRL (wxID_FILEDLGG + 10)
988 #define ID_ACTIVATED (wxID_FILEDLGG + 11)
989 #define ID_CHECK (wxID_FILEDLGG + 12)
990
991 IMPLEMENT_DYNAMIC_CLASS(wxFileDialog,wxDialog)
992
993 BEGIN_EVENT_TABLE(wxFileDialog,wxDialog)
994 EVT_BUTTON(ID_LIST_MODE, wxFileDialog::OnList)
995 EVT_BUTTON(ID_REPORT_MODE, wxFileDialog::OnReport)
996 EVT_BUTTON(ID_UP_DIR, wxFileDialog::OnUp)
997 EVT_BUTTON(ID_PARENT_DIR, wxFileDialog::OnHome)
998 EVT_BUTTON(ID_NEW_DIR, wxFileDialog::OnNew)
999 EVT_BUTTON(wxID_OK, wxFileDialog::OnListOk)
1000 EVT_LIST_ITEM_SELECTED(ID_LIST_CTRL, wxFileDialog::OnSelected)
1001 EVT_LIST_ITEM_ACTIVATED(ID_LIST_CTRL, wxFileDialog::OnActivated)
1002 EVT_CHOICE(ID_CHOICE,wxFileDialog::OnChoiceFilter)
1003 EVT_TEXT_ENTER(ID_TEXT,wxFileDialog::OnTextEnter)
1004 EVT_TEXT(ID_TEXT,wxFileDialog::OnTextChange)
1005 EVT_CHECKBOX(ID_CHECK,wxFileDialog::OnCheck)
1006 END_EVENT_TABLE()
1007
1008 long wxFileDialog::ms_lastViewStyle = wxLC_LIST;
1009 bool wxFileDialog::ms_lastShowHidden = FALSE;
1010
1011 wxFileDialog::wxFileDialog(wxWindow *parent,
1012 const wxString& message,
1013 const wxString& defaultDir,
1014 const wxString& defaultFile,
1015 const wxString& wildCard,
1016 long style,
1017 const wxPoint& pos )
1018 : wxDialog( parent, -1, message, pos, wxDefaultSize,
1019 wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER )
1020 {
1021 if (wxConfig::Get(FALSE))
1022 {
1023 wxConfig::Get()->Read(wxT("/wxWindows/wxFileDialog/ViewStyle"),
1024 &ms_lastViewStyle);
1025 wxConfig::Get()->Read(wxT("/wxWindows/wxFileDialog/ShowHidden"),
1026 &ms_lastShowHidden);
1027 }
1028
1029 m_message = message;
1030 m_dialogStyle = style;
1031
1032 if (m_dialogStyle == 0)
1033 m_dialogStyle = wxOPEN;
1034 if ((m_dialogStyle & wxMULTIPLE ) && !(m_dialogStyle & wxOPEN))
1035 m_dialogStyle |= wxOPEN;
1036
1037 m_dir = defaultDir;
1038 if ((m_dir.empty()) || (m_dir == wxT(".")))
1039 {
1040 m_dir = wxGetCwd();
1041 }
1042
1043 size_t len = m_dir.Len();
1044 if ((len > 1) && (m_dir[len-1] == wxFILE_SEP_PATH))
1045 m_dir.Remove( len-1, 1 );
1046
1047 m_path = m_dir;
1048 m_path += wxFILE_SEP_PATH;
1049 m_path += defaultFile;
1050 m_fileName = defaultFile;
1051 m_wildCard = wildCard;
1052 m_filterIndex = 0;
1053 m_filterExtension = wxEmptyString;
1054
1055 // interpret wildcards
1056
1057 if (m_wildCard.IsEmpty())
1058 m_wildCard = _("All files (*)|*");
1059
1060 wxStringTokenizer tokens( m_wildCard, wxT("|") );
1061 wxString firstWild;
1062 wxString firstWildText;
1063 if (tokens.CountTokens() == 1)
1064 {
1065 firstWildText = tokens.GetNextToken();
1066 firstWild = firstWildText;
1067 }
1068 else
1069 {
1070 wxASSERT_MSG( tokens.CountTokens() % 2 == 0, wxT("Wrong file type descripition") );
1071 firstWildText = tokens.GetNextToken();
1072 firstWild = tokens.GetNextToken();
1073 }
1074 if ( firstWild.Left( 2 ) == wxT("*.") )
1075 m_filterExtension = firstWild.Mid( 1 );
1076 if ( m_filterExtension == wxT(".*") )
1077 m_filterExtension = wxEmptyString;
1078
1079 // layout
1080
1081 bool is_pda = (wxSystemSettings::GetScreenType() <= wxSYS_SCREEN_PDA);
1082
1083 wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL );
1084
1085 wxBoxSizer *buttonsizer = new wxBoxSizer( wxHORIZONTAL );
1086
1087 wxBitmapButton *but;
1088
1089 but = new wxBitmapButton(this, ID_LIST_MODE,
1090 wxArtProvider::GetBitmap(wxART_LIST_VIEW, wxART_CMN_DIALOG));
1091 #if wxUSE_TOOLTIPS
1092 but->SetToolTip( _("View files as a list view") );
1093 #endif
1094 buttonsizer->Add( but, 0, wxALL, 5 );
1095
1096 but = new wxBitmapButton(this, ID_REPORT_MODE,
1097 wxArtProvider::GetBitmap(wxART_REPORT_VIEW, wxART_CMN_DIALOG));
1098 #if wxUSE_TOOLTIPS
1099 but->SetToolTip( _("View files as a detailed view") );
1100 #endif
1101 buttonsizer->Add( but, 0, wxALL, 5 );
1102
1103 buttonsizer->Add( 30, 5, 1 );
1104
1105 wxWindow *butDirUp =
1106 new wxBitmapButton(this, ID_UP_DIR,
1107 wxArtProvider::GetBitmap(wxART_GO_DIR_UP, wxART_CMN_DIALOG));
1108 #if wxUSE_TOOLTIPS
1109 butDirUp->SetToolTip( _("Go to parent directory") );
1110 #endif
1111 buttonsizer->Add( butDirUp, 0, wxALL, 5 );
1112
1113 #ifndef __DOS__ // VS: Home directory is meaningless in MS-DOS...
1114 but = new wxBitmapButton(this, ID_PARENT_DIR,
1115 wxArtProvider::GetBitmap(wxART_GO_HOME, wxART_CMN_DIALOG));
1116 #if wxUSE_TOOLTIPS
1117 but->SetToolTip( _("Go to home directory") );
1118 #endif
1119 buttonsizer->Add( but, 0, wxALL, 5);
1120
1121 buttonsizer->Add( 20, 20 );
1122 #endif //!__DOS__
1123
1124 wxWindow *butNewDir =
1125 new wxBitmapButton(this, ID_NEW_DIR,
1126 wxArtProvider::GetBitmap(wxART_NEW_DIR, wxART_CMN_DIALOG));
1127 #if wxUSE_TOOLTIPS
1128 butNewDir->SetToolTip( _("Create new directory") );
1129 #endif
1130 buttonsizer->Add( butNewDir, 0, wxALL, 5 );
1131
1132 if (is_pda)
1133 mainsizer->Add( buttonsizer, 0, wxALL | wxEXPAND, 0 );
1134 else
1135 mainsizer->Add( buttonsizer, 0, wxALL | wxEXPAND, 5 );
1136
1137 wxBoxSizer *staticsizer = new wxBoxSizer( wxHORIZONTAL );
1138 if (is_pda)
1139 staticsizer->Add( new wxStaticText( this, -1, _("Current directory:") ), 0, wxRIGHT, 10 );
1140 m_static = new wxStaticText( this, -1, m_dir );
1141 staticsizer->Add( m_static, 1 );
1142 mainsizer->Add( staticsizer, 0, wxEXPAND | wxLEFT|wxRIGHT|wxBOTTOM, 10 );
1143
1144 long style2 = ms_lastViewStyle | wxSUNKEN_BORDER;
1145 if ( !(m_dialogStyle & wxMULTIPLE) )
1146 style2 |= wxLC_SINGLE_SEL;
1147
1148 m_list = new wxFileCtrl( this, m_static, ID_LIST_CTRL,
1149 firstWild, ms_lastShowHidden,
1150 wxDefaultPosition, wxSize(540,200),
1151 style2);
1152
1153 m_list->SetNewDirControl(butNewDir);
1154 m_list->SetGoToParentControl(butDirUp);
1155
1156 if (is_pda)
1157 {
1158 // PDAs have a different screen layout
1159 mainsizer->Add( m_list, 1, wxEXPAND | wxLEFT|wxRIGHT, 5 );
1160
1161 wxBoxSizer *choicesizer = new wxBoxSizer( wxHORIZONTAL );
1162 m_choice = new wxChoice( this, ID_CHOICE );
1163 choicesizer->Add( m_choice, 1, wxCENTER|wxALL, 5 );
1164 mainsizer->Add( choicesizer, 0, wxEXPAND );
1165
1166 wxBoxSizer *textsizer = new wxBoxSizer( wxHORIZONTAL );
1167 m_text = new wxTextCtrl( this, ID_TEXT, m_fileName, wxDefaultPosition, wxDefaultSize, wxPROCESS_ENTER );
1168 textsizer->Add( m_text, 1, wxCENTER | wxALL, 5 );
1169 mainsizer->Add( textsizer, 0, wxEXPAND );
1170
1171 m_check = new wxCheckBox( this, ID_CHECK, _("Show hidden files") );
1172 m_check->SetValue( ms_lastShowHidden );
1173 textsizer->Add( m_check, 0, wxCENTER|wxALL, 5 );
1174
1175 buttonsizer = new wxBoxSizer( wxHORIZONTAL );
1176 buttonsizer->Add( new wxButton( this, wxID_OK, _("OK") ), 0, wxCENTER | wxALL, 5 );
1177 buttonsizer->Add( new wxButton( this, wxID_CANCEL, _("Cancel") ), 0, wxCENTER | wxALL, 5 );
1178 mainsizer->Add( buttonsizer, 0, wxALIGN_RIGHT );
1179 }
1180 else
1181 {
1182 mainsizer->Add( m_list, 1, wxEXPAND | wxLEFT|wxRIGHT, 10 );
1183
1184 wxBoxSizer *textsizer = new wxBoxSizer( wxHORIZONTAL );
1185 m_text = new wxTextCtrl( this, ID_TEXT, m_fileName, wxDefaultPosition, wxDefaultSize, wxPROCESS_ENTER );
1186 textsizer->Add( m_text, 1, wxCENTER | wxLEFT|wxRIGHT|wxTOP, 10 );
1187 textsizer->Add( new wxButton( this, wxID_OK, _("OK") ), 0, wxCENTER | wxLEFT|wxRIGHT|wxTOP, 10 );
1188 mainsizer->Add( textsizer, 0, wxEXPAND );
1189
1190 wxBoxSizer *choicesizer = new wxBoxSizer( wxHORIZONTAL );
1191 m_choice = new wxChoice( this, ID_CHOICE );
1192 choicesizer->Add( m_choice, 1, wxCENTER|wxALL, 10 );
1193 m_check = new wxCheckBox( this, ID_CHECK, _("Show hidden files") );
1194 m_check->SetValue( ms_lastShowHidden );
1195 choicesizer->Add( m_check, 0, wxCENTER|wxALL, 10 );
1196 choicesizer->Add( new wxButton( this, wxID_CANCEL, _("Cancel") ), 0, wxCENTER | wxALL, 10 );
1197 mainsizer->Add( choicesizer, 0, wxEXPAND );
1198 }
1199
1200 m_choice->Append( firstWildText, (void*) new wxString( firstWild ) );
1201 while (tokens.HasMoreTokens())
1202 {
1203 firstWildText = tokens.GetNextToken();
1204 firstWild = tokens.GetNextToken();
1205 m_choice->Append( firstWildText, (void*) new wxString( firstWild ) );
1206 }
1207 m_choice->SetSelection( 0 );
1208
1209 SetAutoLayout( TRUE );
1210 SetSizer( mainsizer );
1211
1212 mainsizer->Fit( this );
1213 mainsizer->SetSizeHints( this );
1214
1215 Centre( wxBOTH );
1216
1217 m_text->SetFocus();
1218 }
1219
1220 wxFileDialog::~wxFileDialog()
1221 {
1222 if (wxConfig::Get(FALSE))
1223 {
1224 wxConfig::Get()->Write(wxT("/wxWindows/wxFileDialog/ViewStyle"),
1225 ms_lastViewStyle);
1226 wxConfig::Get()->Write(wxT("/wxWindows/wxFileDialog/ShowHidden"),
1227 ms_lastShowHidden);
1228 }
1229 }
1230
1231 int wxFileDialog::ShowModal()
1232 {
1233 m_list->GoToDir(m_dir);
1234 m_text->SetValue(m_fileName);
1235
1236 return wxDialog::ShowModal();
1237 }
1238
1239 void wxFileDialog::DoSetFilterIndex(int filterindex)
1240 {
1241 wxString *str = (wxString*) m_choice->GetClientData( filterindex );
1242 m_list->SetWild( *str );
1243 m_filterIndex = filterindex;
1244 if ( str->Left(2) == wxT("*.") )
1245 {
1246 m_filterExtension = str->Mid(2);
1247 if (m_filterExtension == _T("*"))
1248 m_filterExtension.clear();
1249 }
1250 else
1251 {
1252 m_filterExtension.clear();
1253 }
1254 }
1255
1256 void wxFileDialog::SetFilterIndex( int filterindex )
1257 {
1258 m_choice->SetSelection( filterindex );
1259
1260 DoSetFilterIndex(filterindex);
1261 }
1262
1263 void wxFileDialog::OnChoiceFilter( wxCommandEvent &event )
1264 {
1265 DoSetFilterIndex((int)event.GetInt());
1266 }
1267
1268 void wxFileDialog::OnCheck( wxCommandEvent &event )
1269 {
1270 m_list->ShowHidden( (ms_lastShowHidden = event.GetInt() != 0) );
1271 }
1272
1273 void wxFileDialog::OnActivated( wxListEvent &event )
1274 {
1275 HandleAction( event.m_item.m_text );
1276 }
1277
1278 void wxFileDialog::OnTextEnter( wxCommandEvent &WXUNUSED(event) )
1279 {
1280 wxCommandEvent cevent(wxEVT_COMMAND_BUTTON_CLICKED, wxID_OK);
1281 cevent.SetEventObject( this );
1282 GetEventHandler()->ProcessEvent( cevent );
1283 }
1284
1285 static bool ignoreChanges = FALSE;
1286
1287 void wxFileDialog::OnTextChange( wxCommandEvent &WXUNUSED(event) )
1288 {
1289 if (!ignoreChanges)
1290 {
1291 // Clear selections. Otherwise when the user types in a value they may
1292 // not get the file whose name they typed.
1293 if (m_list->GetSelectedItemCount() > 0)
1294 {
1295 long item = m_list->GetNextItem(-1, wxLIST_NEXT_ALL,
1296 wxLIST_STATE_SELECTED);
1297 while ( item != -1 )
1298 {
1299 m_list->SetItemState(item,0, wxLIST_STATE_SELECTED);
1300 item = m_list->GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
1301 }
1302 }
1303 }
1304 }
1305
1306 void wxFileDialog::OnSelected( wxListEvent &event )
1307 {
1308 wxString filename( event.m_item.m_text );
1309 if (filename == wxT("..")) return;
1310
1311 wxString dir;
1312 m_list->GetDir( dir );
1313 if (!IsTopMostDir(dir))
1314 dir += wxFILE_SEP_PATH;
1315 dir += filename;
1316 if (wxDirExists(dir)) return;
1317
1318 ignoreChanges = TRUE;
1319 m_text->SetValue( filename );
1320 ignoreChanges = FALSE;
1321 }
1322
1323 void wxFileDialog::HandleAction( const wxString &fn )
1324 {
1325 wxString filename( fn );
1326 wxString dir;
1327 m_list->GetDir( dir );
1328 if (filename.IsEmpty()) return;
1329 if (filename == wxT(".")) return;
1330
1331 if (filename == wxT(".."))
1332 {
1333 m_list->GoToParentDir();
1334 m_list->SetFocus();
1335 return;
1336 }
1337
1338 #ifdef __UNIX__
1339 if (filename == wxT("~"))
1340 {
1341 m_list->GoToHomeDir();
1342 m_list->SetFocus();
1343 return;
1344 }
1345
1346 if (filename[0u] == wxT('~'))
1347 {
1348 filename.Remove( 0, 1 );
1349 wxString tmp( wxGetUserHome() );
1350 tmp += wxT('/');
1351 tmp += filename;
1352 filename = tmp;
1353 }
1354 #endif // __UNIX__
1355
1356 if ((filename.Find(wxT('*')) != wxNOT_FOUND) ||
1357 (filename.Find(wxT('?')) != wxNOT_FOUND))
1358 {
1359 if (filename.Find(wxFILE_SEP_PATH) != wxNOT_FOUND)
1360 {
1361 wxMessageBox(_("Illegal file specification."), _("Error"), wxOK | wxICON_ERROR );
1362 return;
1363 }
1364 m_list->SetWild( filename );
1365 return;
1366 }
1367
1368 if (!IsTopMostDir(dir))
1369 dir += wxFILE_SEP_PATH;
1370 if (!wxIsAbsolutePath(filename))
1371 {
1372 dir += filename;
1373 filename = dir;
1374 }
1375
1376 if (wxDirExists(filename))
1377 {
1378 m_list->GoToDir( filename );
1379 return;
1380 }
1381
1382 // append the default extension to the filename if it doesn't have any
1383 //
1384 // VZ: the logic of testing for !wxFileExists() only for the open file
1385 // dialog is not entirely clear to me, why don't we allow saving to a
1386 // file without extension as well?
1387 if ( !(m_dialogStyle & wxOPEN) || !wxFileExists(filename) )
1388 {
1389 wxString ext;
1390 wxSplitPath(filename, NULL, NULL, &ext);
1391 if ( ext.empty() )
1392 {
1393 // append the first extension of the filter string
1394 filename += m_filterExtension.BeforeFirst(_T(';'));
1395 }
1396 }
1397
1398 // check that the file [doesn't] exist if necessary
1399 if ( (m_dialogStyle & wxSAVE) &&
1400 (m_dialogStyle & wxOVERWRITE_PROMPT) &&
1401 wxFileExists( filename ) )
1402 {
1403 wxString msg;
1404 msg.Printf( _("File '%s' already exists, do you really want to "
1405 "overwrite it?"), filename.c_str() );
1406
1407 if (wxMessageBox(msg, _("Confirm"), wxYES_NO) != wxYES)
1408 return;
1409 }
1410 else if ( (m_dialogStyle & wxOPEN) &&
1411 (m_dialogStyle & wxFILE_MUST_EXIST) &&
1412 !wxFileExists(filename) )
1413 {
1414 wxMessageBox(_("Please choose an existing file."), _("Error"),
1415 wxOK | wxICON_ERROR );
1416 }
1417
1418 SetPath( filename );
1419
1420 // change to the directory where the user went if asked
1421 if ( m_dialogStyle & wxCHANGE_DIR )
1422 {
1423 wxString cwd;
1424 wxSplitPath(filename, &cwd, NULL, NULL);
1425
1426 if ( cwd != wxGetWorkingDirectory() )
1427 {
1428 wxSetWorkingDirectory(cwd);
1429 }
1430 }
1431
1432 wxCommandEvent event;
1433 wxDialog::OnOK(event);
1434 }
1435
1436 void wxFileDialog::OnListOk( wxCommandEvent &WXUNUSED(event) )
1437 {
1438 HandleAction( m_text->GetValue() );
1439 }
1440
1441 void wxFileDialog::OnList( wxCommandEvent &WXUNUSED(event) )
1442 {
1443 m_list->ChangeToListMode();
1444 ms_lastViewStyle = wxLC_LIST;
1445 m_list->SetFocus();
1446 }
1447
1448 void wxFileDialog::OnReport( wxCommandEvent &WXUNUSED(event) )
1449 {
1450 m_list->ChangeToReportMode();
1451 ms_lastViewStyle = wxLC_REPORT;
1452 m_list->SetFocus();
1453 }
1454
1455 void wxFileDialog::OnUp( wxCommandEvent &WXUNUSED(event) )
1456 {
1457 m_list->GoToParentDir();
1458 m_list->SetFocus();
1459 }
1460
1461 void wxFileDialog::OnHome( wxCommandEvent &WXUNUSED(event) )
1462 {
1463 m_list->GoToHomeDir();
1464 m_list->SetFocus();
1465 }
1466
1467 void wxFileDialog::OnNew( wxCommandEvent &WXUNUSED(event) )
1468 {
1469 m_list->MakeDir();
1470 }
1471
1472 void wxFileDialog::SetPath( const wxString& path )
1473 {
1474 // not only set the full path but also update filename and dir
1475 m_path = path;
1476 if ( !path.empty() )
1477 {
1478 wxString ext;
1479 wxSplitPath(path, &m_dir, &m_fileName, &ext);
1480 if (!ext.empty())
1481 {
1482 m_fileName += wxT(".");
1483 m_fileName += ext;
1484 }
1485 }
1486 }
1487
1488 void wxFileDialog::GetPaths( wxArrayString& paths ) const
1489 {
1490 paths.Empty();
1491 if (m_list->GetSelectedItemCount() == 0)
1492 {
1493 paths.Add( GetPath() );
1494 return;
1495 }
1496
1497 paths.Alloc( m_list->GetSelectedItemCount() );
1498
1499 wxString dir;
1500 m_list->GetDir( dir );
1501 #ifdef __UNIX__
1502 if (dir != wxT("/"))
1503 #endif
1504 dir += wxFILE_SEP_PATH;
1505
1506 wxListItem item;
1507 item.m_mask = wxLIST_MASK_TEXT;
1508
1509 item.m_itemId = m_list->GetNextItem( -1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );
1510 while ( item.m_itemId != -1 )
1511 {
1512 m_list->GetItem( item );
1513 paths.Add( dir + item.m_text );
1514 item.m_itemId = m_list->GetNextItem( item.m_itemId,
1515 wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );
1516 }
1517 }
1518
1519 void wxFileDialog::GetFilenames(wxArrayString& files) const
1520 {
1521 files.Empty();
1522 if (m_list->GetSelectedItemCount() == 0)
1523 {
1524 files.Add( GetFilename() );
1525 return;
1526 }
1527 files.Alloc( m_list->GetSelectedItemCount() );
1528
1529 wxListItem item;
1530 item.m_mask = wxLIST_MASK_TEXT;
1531
1532 item.m_itemId = m_list->GetNextItem( -1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );
1533 while ( item.m_itemId != -1 )
1534 {
1535 m_list->GetItem( item );
1536 files.Add( item.m_text );
1537 item.m_itemId = m_list->GetNextItem( item.m_itemId,
1538 wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );
1539 }
1540 }
1541
1542
1543
1544 // ----------------------------------------------------------------------------
1545 // global functions
1546 // ----------------------------------------------------------------------------
1547
1548 wxString
1549 wxFileSelectorEx(const wxChar *message,
1550 const wxChar *default_path,
1551 const wxChar *default_filename,
1552 int *WXUNUSED(indexDefaultExtension),
1553 const wxChar *wildcard,
1554 int flags,
1555 wxWindow *parent,
1556 int x, int y)
1557 {
1558 // TODO: implement this somehow
1559 return wxFileSelector(message, default_path, default_filename, wxT(""),
1560 wildcard, flags, parent, x, y);
1561 }
1562
1563 wxString wxFileSelector( const wxChar *title,
1564 const wxChar *defaultDir, const wxChar *defaultFileName,
1565 const wxChar *defaultExtension, const wxChar *filter, int flags,
1566 wxWindow *parent, int x, int y )
1567 {
1568 wxString filter2;
1569 if ( defaultExtension && !filter )
1570 filter2 = wxString(wxT("*.")) + wxString(defaultExtension) ;
1571 else if ( filter )
1572 filter2 = filter;
1573
1574 wxString defaultDirString;
1575 if (defaultDir)
1576 defaultDirString = defaultDir;
1577
1578 wxString defaultFilenameString;
1579 if (defaultFileName)
1580 defaultFilenameString = defaultFileName;
1581
1582 wxFileDialog fileDialog( parent, title, defaultDirString, defaultFilenameString, filter2, flags, wxPoint(x, y) );
1583
1584 if ( fileDialog.ShowModal() == wxID_OK )
1585 {
1586 return fileDialog.GetPath();
1587 }
1588 else
1589 {
1590 return wxEmptyString;
1591 }
1592 }
1593
1594 static wxString GetWildcardString(const wxChar *ext)
1595 {
1596 wxString wild;
1597 if ( ext )
1598 {
1599 if ( *ext == wxT('.') )
1600 ext++;
1601
1602 wild << _T("*.") << ext;
1603 }
1604 else // no extension specified
1605 {
1606 wild = wxFileSelectorDefaultWildcardStr;
1607 }
1608
1609 return wild;
1610 }
1611
1612 wxString wxLoadFileSelector(const wxChar *what,
1613 const wxChar *ext,
1614 const wxChar *nameDef,
1615 wxWindow *parent)
1616 {
1617 wxString prompt;
1618 if ( what && *what )
1619 prompt = wxString::Format(_("Load %s file"), what);
1620 else
1621 prompt = _("Load file");
1622
1623 return wxFileSelector(prompt, NULL, nameDef, ext,
1624 GetWildcardString(ext), 0, parent);
1625 }
1626
1627 wxString wxSaveFileSelector(const wxChar *what,
1628 const wxChar *ext,
1629 const wxChar *nameDef,
1630 wxWindow *parent)
1631 {
1632 wxString prompt;
1633 if ( what && *what )
1634 prompt = wxString::Format(_("Save %s file"), what);
1635 else
1636 prompt = _("Save file");
1637
1638 return wxFileSelector(prompt, NULL, nameDef, ext,
1639 GetWildcardString(ext), 0, parent);
1640 }
1641
1642 // A module to allow icons table cleanup
1643
1644 class wxFileDialogGenericModule: public wxModule
1645 {
1646 DECLARE_DYNAMIC_CLASS(wxFileDialogGenericModule)
1647 public:
1648 wxFileDialogGenericModule() {}
1649 bool OnInit() { return TRUE; }
1650 void OnExit() { if (g_IconsTable) {delete g_IconsTable; g_IconsTable = NULL;} }
1651 };
1652
1653 IMPLEMENT_DYNAMIC_CLASS(wxFileDialogGenericModule, wxModule)
1654
1655 #endif // wxUSE_FILEDLG
1656