implemented wxFileSelectorEx() (this fixes docview behaviour when multiple selections...
[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
370 wxBitmap tmpBmp;
371 tmpBmp.CopyFromIcon(ic);
372 wxImage img = tmpBmp.ConvertToImage();
373
374 delete ft;
375
376 int id = m_ImageList.GetImageCount();
377 if (img.GetWidth() == 16 && img.GetHeight() == 16)
378 m_ImageList.Add(wxBitmap(img));
379 else
380 {
381 if (img.GetWidth() != 32 || img.GetHeight() != 32)
382 m_ImageList.Add(CreateAntialiasedBitmap(CutEmptyBorders(img).Rescale(32, 32)));
383 else
384 m_ImageList.Add(CreateAntialiasedBitmap(img));
385 }
386 m_HashTable.Put(extension, new wxFileIconEntry(id));
387 return id;
388
389 #else // !wxUSE_MIMETYPE
390
391 if (extension == wxT("exe"))
392 return FI_EXECUTABLE;
393 else
394 return FI_UNKNOWN;
395 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
396 }
397
398
399
400 // ----------------------------------------------------------------------------
401 // private functions
402 // ----------------------------------------------------------------------------
403
404 static
405 int ListCompare( long data1, long data2, long WXUNUSED(data))
406 {
407 wxFileData *fd1 = (wxFileData*)data1 ;
408 wxFileData *fd2 = (wxFileData*)data2 ;
409 if (fd1->GetName() == wxT("..")) return -1;
410 if (fd2->GetName() == wxT("..")) return 1;
411 if (fd1->IsDir() && !fd2->IsDir()) return -1;
412 if (fd2->IsDir() && !fd1->IsDir()) return 1;
413 return wxStrcmp( fd1->GetName(), fd2->GetName() );
414 }
415
416 #ifdef __UNIX__
417 #define IsTopMostDir(dir) (dir == wxT("/"))
418 #endif
419
420 #if defined(__DOS__) || defined(__WINDOWS__)
421 #define IsTopMostDir(dir) (dir.IsEmpty())
422 #endif
423
424 #if defined(__DOS__) || defined(__WINDOWS__)
425 extern bool wxIsDriveAvailable(const wxString& dirName);
426 #endif
427
428 //-----------------------------------------------------------------------------
429 // wxFileData
430 //-----------------------------------------------------------------------------
431
432 wxFileData::wxFileData( const wxString &name, const wxString &fname )
433 {
434 m_name = name;
435 m_fileName = fname;
436
437 #if defined(__DOS__) || defined(__WINDOWS__)
438 // VS: In case the file is root directory of a volume (e.g. "C:"),
439 // we don't want it stat()ed, since the drive may not be in:
440 if (name.length() == 2 && name[1u] == wxT(':'))
441 {
442 m_isDir = TRUE;
443 m_isExe =
444 m_isLink = FALSE;
445 m_size = 0;
446 return;
447 }
448 #endif // __DOS__ || __WINDOWS__
449
450 wxStructStat buff;
451
452 #if defined(__UNIX__) && (!defined( __EMX__ ) && !defined(__VMS))
453 lstat( m_fileName.fn_str(), &buff );
454 m_isLink = S_ISLNK( buff.st_mode );
455 #else // no lstat()
456 wxStat( m_fileName, &buff );
457 m_isLink = FALSE;
458 #endif
459
460 m_isDir = (buff.st_mode & S_IFDIR) != 0;
461 m_isExe = (buff.st_mode & wxS_IXUSR) != 0;
462
463 m_size = buff.st_size;
464
465 const struct tm * const t = localtime( &buff.st_mtime );
466 m_hour = t->tm_hour;
467 m_minute = t->tm_min;
468 m_month = t->tm_mon+1;
469 m_day = t->tm_mday;
470 m_year = t->tm_year;
471 m_year += 1900;
472
473 m_permissions.Printf(_T("%c%c%c"),
474 buff.st_mode & wxS_IRUSR ? _T('r') : _T('-'),
475 buff.st_mode & wxS_IWUSR ? _T('w') : _T('-'),
476 buff.st_mode & wxS_IXUSR ? _T('x') : _T('-'));
477 }
478
479 wxString wxFileData::GetName() const
480 {
481 return m_name;
482 }
483
484 wxString wxFileData::GetFullName() const
485 {
486 return m_fileName;
487 }
488
489 wxString wxFileData::GetHint() const
490 {
491 wxString s = m_fileName;
492 s += wxT(" ");
493 if (m_isDir) s += wxT("<DIR> ");
494 else if (m_isLink) s += wxT("<LINK> ");
495 else
496 {
497 s += LongToString( m_size );
498 s += wxT(" bytes ");
499 }
500 s += IntToString( m_day );
501 s += wxT(".");
502 s += IntToString( m_month );
503 s += wxT(".");
504 s += IntToString( m_year );
505 s += wxT(" ");
506 s += IntToString( m_hour );
507 s += wxT(":");
508 s += IntToString( m_minute );
509 s += wxT(" ");
510 s += m_permissions;
511 return s;
512 };
513
514 wxString wxFileData::GetEntry( FileListField num ) const
515 {
516 wxString s;
517 switch ( num )
518 {
519 case FileList_Name:
520 s = m_name;
521 break;
522
523 case FileList_Type:
524 if (m_isDir)
525 s = _("<DIR>");
526 else if (m_isLink)
527 s = _("<LINK>");
528 else
529 s.Printf(_T("%ld"), m_size);
530 break;
531
532 case FileList_Date:
533 s.Printf(_T("%02d.%02d.%d"), m_day, m_month, m_year);
534 break;
535
536 case FileList_Time:
537 s.Printf(_T("%02d:%02d"), m_hour, m_minute);
538 break;
539
540 #ifdef __UNIX__
541 case FileList_Perm:
542 s = m_permissions;
543 break;
544 #endif // __UNIX__
545
546 default:
547 wxFAIL_MSG( _T("unexpected field in wxFileData::GetEntry()") );
548 }
549
550 return s;
551 }
552
553 void wxFileData::SetNewName( const wxString &name, const wxString &fname )
554 {
555 m_name = name;
556 m_fileName = fname;
557 }
558
559 void wxFileData::MakeItem( wxListItem &item )
560 {
561 item.m_text = m_name;
562 item.ClearAttributes();
563 if (IsExe())
564 item.SetTextColour(*wxRED);
565 if (IsDir())
566 item.SetTextColour(*wxBLUE);
567
568 if (IsDir())
569 item.m_image = FI_FOLDER;
570 else if (IsExe())
571 item.m_image = FI_EXECUTABLE;
572 else if (m_name.Find(wxT('.')) != wxNOT_FOUND)
573 item.m_image = g_IconsTable->GetIconID(m_name.AfterLast(wxT('.')));
574 else
575 item.m_image = FI_UNKNOWN;
576
577 if (IsLink())
578 {
579 wxColour *dg = wxTheColourDatabase->FindColour( _T("MEDIUM GREY") );
580 item.SetTextColour(*dg);
581 }
582 item.m_data = (long)this;
583 }
584
585 //-----------------------------------------------------------------------------
586 // wxFileCtrl
587 //-----------------------------------------------------------------------------
588
589 IMPLEMENT_DYNAMIC_CLASS(wxFileCtrl,wxListCtrl)
590
591 BEGIN_EVENT_TABLE(wxFileCtrl,wxListCtrl)
592 EVT_LIST_DELETE_ITEM(-1, wxFileCtrl::OnListDeleteItem)
593 EVT_LIST_END_LABEL_EDIT(-1, wxFileCtrl::OnListEndLabelEdit)
594 END_EVENT_TABLE()
595
596
597 wxFileCtrl::wxFileCtrl()
598 {
599 m_showHidden = FALSE;
600 }
601
602 wxFileCtrl::wxFileCtrl(wxWindow *win,
603 wxStaticText *labelDir,
604 wxWindowID id,
605 const wxString& wild,
606 bool showHidden,
607 const wxPoint& pos,
608 const wxSize& size,
609 long style,
610 const wxValidator &validator,
611 const wxString &name)
612 : wxListCtrl(win, id, pos, size, style, validator, name),
613 m_wild(wild)
614 {
615 if (! g_IconsTable)
616 g_IconsTable = new wxFileIconsTable;
617 wxImageList *imageList = g_IconsTable->GetImageList();
618
619 SetImageList( imageList, wxIMAGE_LIST_SMALL );
620
621 m_goToParentControl =
622 m_newDirControl = NULL;
623
624 m_labelDir = labelDir;
625
626 m_showHidden = showHidden;
627 }
628
629 void wxFileCtrl::ChangeToListMode()
630 {
631 SetSingleStyle( wxLC_LIST );
632 UpdateFiles();
633 }
634
635 void wxFileCtrl::ChangeToReportMode()
636 {
637 SetSingleStyle( wxLC_REPORT );
638 UpdateFiles();
639 }
640
641 void wxFileCtrl::ChangeToIconMode()
642 {
643 SetSingleStyle( wxLC_ICON );
644 UpdateFiles();
645 }
646
647 void wxFileCtrl::ShowHidden( bool show )
648 {
649 m_showHidden = show;
650 UpdateFiles();
651 }
652
653 long wxFileCtrl::Add( wxFileData *fd, wxListItem &item )
654 {
655 long ret = -1;
656 item.m_mask = wxLIST_MASK_TEXT + wxLIST_MASK_DATA + wxLIST_MASK_IMAGE;
657 fd->MakeItem( item );
658 long my_style = GetWindowStyleFlag();
659 if (my_style & wxLC_REPORT)
660 {
661 ret = InsertItem( item );
662 for (int i = 1; i < FileList_Max; i++)
663 SetItem( item.m_itemId, i, fd->GetEntry((FileListField)i) );
664 }
665 else if (my_style & wxLC_LIST)
666 {
667 ret = InsertItem( item );
668 }
669 return ret;
670 }
671
672 void wxFileCtrl::UpdateFiles()
673 {
674 // don't do anything before ShowModal() call which sets m_dirName
675 if ( m_dirName.empty() )
676 return;
677
678 wxBusyCursor bcur; // this may take a while...
679
680 long my_style = GetWindowStyleFlag();
681 int name_col_width = 0;
682 if (my_style & wxLC_REPORT)
683 {
684 if (GetColumnCount() > 0)
685 name_col_width = GetColumnWidth( 0 );
686 }
687
688 FreeAllItemsData();
689 ClearAll();
690
691 if (my_style & wxLC_REPORT)
692 {
693 if (name_col_width < 140) name_col_width = 140;
694 InsertColumn( 0, _("Name"), wxLIST_FORMAT_LEFT, name_col_width );
695 InsertColumn( 1, _("Size"), wxLIST_FORMAT_LEFT, 60 );
696 InsertColumn( 2, _("Date"), wxLIST_FORMAT_LEFT, 65 );
697 InsertColumn( 3, _("Time"), wxLIST_FORMAT_LEFT, 50 );
698 #ifdef __UNIX__
699 InsertColumn( 4, _("Permissions"), wxLIST_FORMAT_LEFT, 120 );
700 #endif
701 }
702 wxFileData *fd = (wxFileData *) NULL;
703 wxListItem item;
704 item.m_itemId = 0;
705 item.m_col = 0;
706
707 #if defined(__DOS__) || defined(__WINDOWS__)
708 if ( IsTopMostDir(m_dirName) )
709 {
710 // Pseudo-directory with all available drives listed...
711 for (int drive = 1; drive <= 26; drive++)
712 {
713 wxString path;
714 path.Printf(wxT("%c:\\"), (char)(drive + 'A' - 1));
715 if ( wxIsDriveAvailable(path) )
716 {
717 path.RemoveLast();
718 fd = new wxFileData(path, path);
719 Add(fd, item);
720 item.m_itemId++;
721 }
722 }
723 }
724 else
725 #endif
726 {
727 // Real directory...
728 if ( !IsTopMostDir(m_dirName) )
729 {
730 wxString p(wxPathOnly(m_dirName));
731 #ifdef __UNIX__
732 if (p.IsEmpty()) p = wxT("/");
733 #endif
734 fd = new wxFileData( wxT(".."), p );
735 Add(fd, item);
736 item.m_itemId++;
737 }
738
739 wxString dirname(m_dirName);
740 #if defined(__DOS__) || defined(__WINDOWS__)
741 if (dirname.length() == 2 && dirname[1u] == wxT(':'))
742 dirname << wxT('\\');
743 #endif
744 wxDir dir(dirname);
745
746 if ( dir.IsOpened() )
747 {
748 wxString dirPrefix(dirname + wxFILE_SEP_PATH);
749 int hiddenFlag = m_showHidden ? wxDIR_HIDDEN : 0;
750
751 bool cont;
752 wxString f;
753
754 // Get the directories first (not matched against wildcards):
755 cont = dir.GetFirst(&f, wxEmptyString, wxDIR_DIRS | hiddenFlag);
756 while (cont)
757 {
758 fd = new wxFileData(f, dirPrefix + f);
759 Add(fd, item);
760 item.m_itemId++;
761 cont = dir.GetNext(&f);
762 }
763
764 // Tokenize the wildcard string, so we can handle more than 1
765 // search pattern in a wildcard.
766 wxStringTokenizer tokenWild(m_wild, wxT(";"));
767 while ( tokenWild.HasMoreTokens() )
768 {
769 cont = dir.GetFirst(&f, tokenWild.GetNextToken(),
770 wxDIR_FILES | hiddenFlag);
771 while (cont)
772 {
773 fd = new wxFileData(f, dirPrefix + f);
774 Add(fd, item);
775 item.m_itemId++;
776 cont = dir.GetNext(&f);
777 }
778 }
779 }
780 }
781
782 SortItems((wxListCtrlCompare)ListCompare, 0);
783
784 if ( my_style & wxLC_REPORT )
785 {
786 SetColumnWidth(1, wxLIST_AUTOSIZE);
787 SetColumnWidth(2, wxLIST_AUTOSIZE);
788 SetColumnWidth(3, wxLIST_AUTOSIZE);
789 }
790
791 // Finally, enable/disable context-dependent controls:
792 if ( m_goToParentControl )
793 m_goToParentControl->Enable(!IsTopMostDir(m_dirName));
794 #if defined(__DOS__) || defined(__WINDOWS__)
795 if ( m_newDirControl )
796 m_newDirControl->Enable(!IsTopMostDir(m_dirName));
797 #endif
798 }
799
800 void wxFileCtrl::SetWild( const wxString &wild )
801 {
802 m_wild = wild;
803 UpdateFiles();
804 }
805
806 void wxFileCtrl::MakeDir()
807 {
808 wxString new_name( _("NewName") );
809 wxString path( m_dirName );
810 path += wxFILE_SEP_PATH;
811 path += new_name;
812 if (wxFileExists(path))
813 {
814 // try NewName0, NewName1 etc.
815 int i = 0;
816 do {
817 new_name = _("NewName");
818 wxString num;
819 num.Printf( wxT("%d"), i );
820 new_name += num;
821
822 path = m_dirName;
823 path += wxFILE_SEP_PATH;
824 path += new_name;
825 i++;
826 } while (wxFileExists(path));
827 }
828
829 wxLogNull log;
830 if (!wxMkdir(path))
831 {
832 wxMessageDialog dialog(this, _("Operation not permitted."), _("Error"), wxOK | wxICON_ERROR );
833 dialog.ShowModal();
834 return;
835 }
836
837 wxFileData *fd = new wxFileData( new_name, path );
838 wxListItem item;
839 item.m_itemId = 0;
840 item.m_col = 0;
841 long id = Add( fd, item );
842
843 if (id != -1)
844 {
845 SortItems( (wxListCtrlCompare) ListCompare, 0 );
846 id = FindItem( 0, (long)fd );
847 EnsureVisible( id );
848 EditLabel( id );
849 }
850 }
851
852 void wxFileCtrl::GoToParentDir()
853 {
854 if (!IsTopMostDir(m_dirName))
855 {
856 size_t len = m_dirName.Len();
857 if (m_dirName[len-1] == wxFILE_SEP_PATH)
858 m_dirName.Remove( len-1, 1 );
859 wxString fname( wxFileNameFromPath(m_dirName) );
860 m_dirName = wxPathOnly( m_dirName );
861 #ifdef __UNIX__
862 if (m_dirName.IsEmpty())
863 m_dirName = wxT("/");
864 #endif
865 UpdateFiles();
866 long id = FindItem( 0, fname );
867 if (id != -1)
868 {
869 SetItemState( id, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
870 EnsureVisible( id );
871 }
872
873 m_labelDir->SetLabel(m_dirName);
874 }
875 }
876
877 void wxFileCtrl::GoToHomeDir()
878 {
879 wxString s = wxGetUserHome( wxString() );
880 GoToDir(s);
881 }
882
883 void wxFileCtrl::GoToDir( const wxString &dir )
884 {
885 m_dirName = dir;
886 UpdateFiles();
887 SetItemState( 0, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
888 EnsureVisible( 0 );
889
890 m_labelDir->SetLabel(dir);
891 }
892
893 void wxFileCtrl::GetDir( wxString &dir )
894 {
895 dir = m_dirName;
896 }
897
898 void wxFileCtrl::FreeItemData(const wxListItem& item)
899 {
900 wxFileData *fd = (wxFileData*)item.m_data;
901 delete fd;
902 }
903
904 void wxFileCtrl::OnListDeleteItem( wxListEvent &event )
905 {
906 FreeItemData(event.m_item);
907 }
908
909 void wxFileCtrl::FreeAllItemsData()
910 {
911 wxListItem item;
912 item.m_mask = wxLIST_MASK_DATA;
913
914 item.m_itemId = GetNextItem( -1, wxLIST_NEXT_ALL );
915 while ( item.m_itemId != -1 )
916 {
917 GetItem( item );
918 FreeItemData(item);
919 item.m_itemId = GetNextItem( item.m_itemId, wxLIST_NEXT_ALL );
920 }
921 }
922
923 void wxFileCtrl::OnListEndLabelEdit( wxListEvent &event )
924 {
925 wxFileData *fd = (wxFileData*)event.m_item.m_data;
926 wxASSERT( fd );
927
928 if ((event.GetLabel().IsEmpty()) ||
929 (event.GetLabel() == _(".")) ||
930 (event.GetLabel() == _("..")) ||
931 (event.GetLabel().First( wxFILE_SEP_PATH ) != wxNOT_FOUND))
932 {
933 wxMessageDialog dialog(this, _("Illegal directory name."), _("Error"), wxOK | wxICON_ERROR );
934 dialog.ShowModal();
935 event.Veto();
936 return;
937 }
938
939 wxString new_name( wxPathOnly( fd->GetFullName() ) );
940 new_name += wxFILE_SEP_PATH;
941 new_name += event.GetLabel();
942
943 wxLogNull log;
944
945 if (wxFileExists(new_name))
946 {
947 wxMessageDialog dialog(this, _("File name exists already."), _("Error"), wxOK | wxICON_ERROR );
948 dialog.ShowModal();
949 event.Veto();
950 }
951
952 if (wxRenameFile(fd->GetFullName(),new_name))
953 {
954 fd->SetNewName( new_name, event.GetLabel() );
955 SetItemState( event.GetItem(), wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
956 EnsureVisible( event.GetItem() );
957 }
958 else
959 {
960 wxMessageDialog dialog(this, _("Operation not permitted."), _("Error"), wxOK | wxICON_ERROR );
961 dialog.ShowModal();
962 event.Veto();
963 }
964 }
965
966 wxFileCtrl::~wxFileCtrl()
967 {
968 FreeAllItemsData();
969 }
970
971 //-----------------------------------------------------------------------------
972 // wxFileDialog
973 //-----------------------------------------------------------------------------
974
975 #define ID_LIST_MODE (wxID_FILEDLGG )
976 #define ID_REPORT_MODE (wxID_FILEDLGG + 1)
977 #define ID_UP_DIR (wxID_FILEDLGG + 5)
978 #define ID_PARENT_DIR (wxID_FILEDLGG + 6)
979 #define ID_NEW_DIR (wxID_FILEDLGG + 7)
980 #define ID_CHOICE (wxID_FILEDLGG + 8)
981 #define ID_TEXT (wxID_FILEDLGG + 9)
982 #define ID_LIST_CTRL (wxID_FILEDLGG + 10)
983 #define ID_ACTIVATED (wxID_FILEDLGG + 11)
984 #define ID_CHECK (wxID_FILEDLGG + 12)
985
986 IMPLEMENT_DYNAMIC_CLASS(wxFileDialog,wxDialog)
987
988 BEGIN_EVENT_TABLE(wxFileDialog,wxDialog)
989 EVT_BUTTON(ID_LIST_MODE, wxFileDialog::OnList)
990 EVT_BUTTON(ID_REPORT_MODE, wxFileDialog::OnReport)
991 EVT_BUTTON(ID_UP_DIR, wxFileDialog::OnUp)
992 EVT_BUTTON(ID_PARENT_DIR, wxFileDialog::OnHome)
993 EVT_BUTTON(ID_NEW_DIR, wxFileDialog::OnNew)
994 EVT_BUTTON(wxID_OK, wxFileDialog::OnListOk)
995 EVT_LIST_ITEM_SELECTED(ID_LIST_CTRL, wxFileDialog::OnSelected)
996 EVT_LIST_ITEM_ACTIVATED(ID_LIST_CTRL, wxFileDialog::OnActivated)
997 EVT_CHOICE(ID_CHOICE,wxFileDialog::OnChoiceFilter)
998 EVT_TEXT_ENTER(ID_TEXT,wxFileDialog::OnTextEnter)
999 EVT_TEXT(ID_TEXT,wxFileDialog::OnTextChange)
1000 EVT_CHECKBOX(ID_CHECK,wxFileDialog::OnCheck)
1001 END_EVENT_TABLE()
1002
1003 long wxFileDialog::ms_lastViewStyle = wxLC_LIST;
1004 bool wxFileDialog::ms_lastShowHidden = FALSE;
1005
1006 wxFileDialog::wxFileDialog(wxWindow *parent,
1007 const wxString& message,
1008 const wxString& defaultDir,
1009 const wxString& defaultFile,
1010 const wxString& wildCard,
1011 long style,
1012 const wxPoint& pos )
1013 : wxDialog( parent, -1, message, pos, wxDefaultSize,
1014 wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER )
1015 {
1016 if (wxConfig::Get(FALSE))
1017 {
1018 wxConfig::Get()->Read(wxT("/wxWindows/wxFileDialog/ViewStyle"),
1019 &ms_lastViewStyle);
1020 wxConfig::Get()->Read(wxT("/wxWindows/wxFileDialog/ShowHidden"),
1021 &ms_lastShowHidden);
1022 }
1023
1024 m_message = message;
1025 m_dialogStyle = style;
1026
1027 if (m_dialogStyle == 0)
1028 m_dialogStyle = wxOPEN;
1029 if ((m_dialogStyle & wxMULTIPLE ) && !(m_dialogStyle & wxOPEN))
1030 m_dialogStyle |= wxOPEN;
1031
1032 m_dir = defaultDir;
1033 if ((m_dir.empty()) || (m_dir == wxT(".")))
1034 {
1035 m_dir = wxGetCwd();
1036 }
1037
1038 size_t len = m_dir.Len();
1039 if ((len > 1) && (m_dir[len-1] == wxFILE_SEP_PATH))
1040 m_dir.Remove( len-1, 1 );
1041
1042 m_path = m_dir;
1043 m_path += wxFILE_SEP_PATH;
1044 m_path += defaultFile;
1045 m_fileName = defaultFile;
1046 m_wildCard = wildCard;
1047 m_filterIndex = 0;
1048 m_filterExtension = wxEmptyString;
1049
1050 // interpret wildcards
1051
1052 if (m_wildCard.IsEmpty())
1053 m_wildCard = _("All files (*)|*");
1054
1055 wxStringTokenizer tokens( m_wildCard, wxT("|") );
1056 wxString firstWild;
1057 wxString firstWildText;
1058 if (tokens.CountTokens() == 1)
1059 {
1060 firstWildText = tokens.GetNextToken();
1061 firstWild = firstWildText;
1062 }
1063 else
1064 {
1065 wxASSERT_MSG( tokens.CountTokens() % 2 == 0, wxT("Wrong file type descripition") );
1066 firstWildText = tokens.GetNextToken();
1067 firstWild = tokens.GetNextToken();
1068 }
1069 if ( firstWild.Left( 2 ) == wxT("*.") )
1070 m_filterExtension = firstWild.Mid( 1 );
1071 if ( m_filterExtension == wxT(".*") )
1072 m_filterExtension = wxEmptyString;
1073
1074 // layout
1075
1076 bool is_pda = (wxSystemSettings::GetScreenType() <= wxSYS_SCREEN_PDA);
1077
1078 wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL );
1079
1080 wxBoxSizer *buttonsizer = new wxBoxSizer( wxHORIZONTAL );
1081
1082 wxBitmapButton *but;
1083
1084 but = new wxBitmapButton(this, ID_LIST_MODE,
1085 wxArtProvider::GetBitmap(wxART_LIST_VIEW, wxART_CMN_DIALOG));
1086 #if wxUSE_TOOLTIPS
1087 but->SetToolTip( _("View files as a list view") );
1088 #endif
1089 buttonsizer->Add( but, 0, wxALL, 5 );
1090
1091 but = new wxBitmapButton(this, ID_REPORT_MODE,
1092 wxArtProvider::GetBitmap(wxART_REPORT_VIEW, wxART_CMN_DIALOG));
1093 #if wxUSE_TOOLTIPS
1094 but->SetToolTip( _("View files as a detailed view") );
1095 #endif
1096 buttonsizer->Add( but, 0, wxALL, 5 );
1097
1098 buttonsizer->Add( 30, 5, 1 );
1099
1100 wxWindow *butDirUp =
1101 new wxBitmapButton(this, ID_UP_DIR,
1102 wxArtProvider::GetBitmap(wxART_GO_DIR_UP, wxART_CMN_DIALOG));
1103 #if wxUSE_TOOLTIPS
1104 butDirUp->SetToolTip( _("Go to parent directory") );
1105 #endif
1106 buttonsizer->Add( butDirUp, 0, wxALL, 5 );
1107
1108 #ifndef __DOS__ // VS: Home directory is meaningless in MS-DOS...
1109 but = new wxBitmapButton(this, ID_PARENT_DIR,
1110 wxArtProvider::GetBitmap(wxART_GO_HOME, wxART_CMN_DIALOG));
1111 #if wxUSE_TOOLTIPS
1112 but->SetToolTip( _("Go to home directory") );
1113 #endif
1114 buttonsizer->Add( but, 0, wxALL, 5);
1115
1116 buttonsizer->Add( 20, 20 );
1117 #endif //!__DOS__
1118
1119 wxWindow *butNewDir =
1120 new wxBitmapButton(this, ID_NEW_DIR,
1121 wxArtProvider::GetBitmap(wxART_NEW_DIR, wxART_CMN_DIALOG));
1122 #if wxUSE_TOOLTIPS
1123 butNewDir->SetToolTip( _("Create new directory") );
1124 #endif
1125 buttonsizer->Add( butNewDir, 0, wxALL, 5 );
1126
1127 if (is_pda)
1128 mainsizer->Add( buttonsizer, 0, wxALL | wxEXPAND, 0 );
1129 else
1130 mainsizer->Add( buttonsizer, 0, wxALL | wxEXPAND, 5 );
1131
1132 wxBoxSizer *staticsizer = new wxBoxSizer( wxHORIZONTAL );
1133 if (is_pda)
1134 staticsizer->Add( new wxStaticText( this, -1, _("Current directory:") ), 0, wxRIGHT, 10 );
1135 m_static = new wxStaticText( this, -1, m_dir );
1136 staticsizer->Add( m_static, 1 );
1137 mainsizer->Add( staticsizer, 0, wxEXPAND | wxLEFT|wxRIGHT|wxBOTTOM, 10 );
1138
1139 long style2 = ms_lastViewStyle | wxSUNKEN_BORDER;
1140 if ( !(m_dialogStyle & wxMULTIPLE) )
1141 style2 |= wxLC_SINGLE_SEL;
1142
1143 m_list = new wxFileCtrl( this, m_static, ID_LIST_CTRL,
1144 firstWild, ms_lastShowHidden,
1145 wxDefaultPosition, wxSize(540,200),
1146 style2);
1147
1148 m_list->SetNewDirControl(butNewDir);
1149 m_list->SetGoToParentControl(butDirUp);
1150
1151 if (is_pda)
1152 {
1153 // PDAs have a different screen layout
1154 mainsizer->Add( m_list, 1, wxEXPAND | wxLEFT|wxRIGHT, 5 );
1155
1156 wxBoxSizer *choicesizer = new wxBoxSizer( wxHORIZONTAL );
1157 m_choice = new wxChoice( this, ID_CHOICE );
1158 choicesizer->Add( m_choice, 1, wxCENTER|wxALL, 5 );
1159 mainsizer->Add( choicesizer, 0, wxEXPAND );
1160
1161 wxBoxSizer *textsizer = new wxBoxSizer( wxHORIZONTAL );
1162 m_text = new wxTextCtrl( this, ID_TEXT, m_fileName, wxDefaultPosition, wxDefaultSize, wxPROCESS_ENTER );
1163 textsizer->Add( m_text, 1, wxCENTER | wxALL, 5 );
1164 mainsizer->Add( textsizer, 0, wxEXPAND );
1165
1166 m_check = new wxCheckBox( this, ID_CHECK, _("Show hidden files") );
1167 m_check->SetValue( ms_lastShowHidden );
1168 textsizer->Add( m_check, 0, wxCENTER|wxALL, 5 );
1169
1170 buttonsizer = new wxBoxSizer( wxHORIZONTAL );
1171 buttonsizer->Add( new wxButton( this, wxID_OK, _("OK") ), 0, wxCENTER | wxALL, 5 );
1172 buttonsizer->Add( new wxButton( this, wxID_CANCEL, _("Cancel") ), 0, wxCENTER | wxALL, 5 );
1173 mainsizer->Add( buttonsizer, 0, wxALIGN_RIGHT );
1174 }
1175 else
1176 {
1177 mainsizer->Add( m_list, 1, wxEXPAND | wxLEFT|wxRIGHT, 10 );
1178
1179 wxBoxSizer *textsizer = new wxBoxSizer( wxHORIZONTAL );
1180 m_text = new wxTextCtrl( this, ID_TEXT, m_fileName, wxDefaultPosition, wxDefaultSize, wxPROCESS_ENTER );
1181 textsizer->Add( m_text, 1, wxCENTER | wxLEFT|wxRIGHT|wxTOP, 10 );
1182 textsizer->Add( new wxButton( this, wxID_OK, _("OK") ), 0, wxCENTER | wxLEFT|wxRIGHT|wxTOP, 10 );
1183 mainsizer->Add( textsizer, 0, wxEXPAND );
1184
1185 wxBoxSizer *choicesizer = new wxBoxSizer( wxHORIZONTAL );
1186 m_choice = new wxChoice( this, ID_CHOICE );
1187 choicesizer->Add( m_choice, 1, wxCENTER|wxALL, 10 );
1188 m_check = new wxCheckBox( this, ID_CHECK, _("Show hidden files") );
1189 m_check->SetValue( ms_lastShowHidden );
1190 choicesizer->Add( m_check, 0, wxCENTER|wxALL, 10 );
1191 choicesizer->Add( new wxButton( this, wxID_CANCEL, _("Cancel") ), 0, wxCENTER | wxALL, 10 );
1192 mainsizer->Add( choicesizer, 0, wxEXPAND );
1193 }
1194
1195 m_choice->Append( firstWildText, (void*) new wxString( firstWild ) );
1196 while (tokens.HasMoreTokens())
1197 {
1198 firstWildText = tokens.GetNextToken();
1199 firstWild = tokens.GetNextToken();
1200 m_choice->Append( firstWildText, (void*) new wxString( firstWild ) );
1201 }
1202 m_choice->SetSelection( 0 );
1203
1204 SetAutoLayout( TRUE );
1205 SetSizer( mainsizer );
1206
1207 mainsizer->Fit( this );
1208 mainsizer->SetSizeHints( this );
1209
1210 Centre( wxBOTH );
1211
1212 m_text->SetFocus();
1213 }
1214
1215 wxFileDialog::~wxFileDialog()
1216 {
1217 if (wxConfig::Get(FALSE))
1218 {
1219 wxConfig::Get()->Write(wxT("/wxWindows/wxFileDialog/ViewStyle"),
1220 ms_lastViewStyle);
1221 wxConfig::Get()->Write(wxT("/wxWindows/wxFileDialog/ShowHidden"),
1222 ms_lastShowHidden);
1223 }
1224 }
1225
1226 int wxFileDialog::ShowModal()
1227 {
1228 m_list->GoToDir(m_dir);
1229 m_text->SetValue(m_fileName);
1230
1231 return wxDialog::ShowModal();
1232 }
1233
1234 void wxFileDialog::DoSetFilterIndex(int filterindex)
1235 {
1236 wxString *str = (wxString*) m_choice->GetClientData( filterindex );
1237 m_list->SetWild( *str );
1238 m_filterIndex = filterindex;
1239 if ( str->Left(2) == wxT("*.") )
1240 {
1241 m_filterExtension = str->Mid(2);
1242 if (m_filterExtension == _T("*"))
1243 m_filterExtension.clear();
1244 }
1245 else
1246 {
1247 m_filterExtension.clear();
1248 }
1249 }
1250
1251 void wxFileDialog::SetFilterIndex( int filterindex )
1252 {
1253 m_choice->SetSelection( filterindex );
1254
1255 DoSetFilterIndex(filterindex);
1256 }
1257
1258 void wxFileDialog::OnChoiceFilter( wxCommandEvent &event )
1259 {
1260 DoSetFilterIndex((int)event.GetInt());
1261 }
1262
1263 void wxFileDialog::OnCheck( wxCommandEvent &event )
1264 {
1265 m_list->ShowHidden( (ms_lastShowHidden = event.GetInt() != 0) );
1266 }
1267
1268 void wxFileDialog::OnActivated( wxListEvent &event )
1269 {
1270 HandleAction( event.m_item.m_text );
1271 }
1272
1273 void wxFileDialog::OnTextEnter( wxCommandEvent &WXUNUSED(event) )
1274 {
1275 wxCommandEvent cevent(wxEVT_COMMAND_BUTTON_CLICKED, wxID_OK);
1276 cevent.SetEventObject( this );
1277 GetEventHandler()->ProcessEvent( cevent );
1278 }
1279
1280 static bool ignoreChanges = FALSE;
1281
1282 void wxFileDialog::OnTextChange( wxCommandEvent &WXUNUSED(event) )
1283 {
1284 if (!ignoreChanges)
1285 {
1286 // Clear selections. Otherwise when the user types in a value they may
1287 // not get the file whose name they typed.
1288 if (m_list->GetSelectedItemCount() > 0)
1289 {
1290 long item = m_list->GetNextItem(-1, wxLIST_NEXT_ALL,
1291 wxLIST_STATE_SELECTED);
1292 while ( item != -1 )
1293 {
1294 m_list->SetItemState(item,0, wxLIST_STATE_SELECTED);
1295 item = m_list->GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
1296 }
1297 }
1298 }
1299 }
1300
1301 void wxFileDialog::OnSelected( wxListEvent &event )
1302 {
1303 wxString filename( event.m_item.m_text );
1304 if (filename == wxT("..")) return;
1305
1306 wxString dir;
1307 m_list->GetDir( dir );
1308 if (!IsTopMostDir(dir))
1309 dir += wxFILE_SEP_PATH;
1310 dir += filename;
1311 if (wxDirExists(dir)) return;
1312
1313 ignoreChanges = TRUE;
1314 m_text->SetValue( filename );
1315 ignoreChanges = FALSE;
1316 }
1317
1318 void wxFileDialog::HandleAction( const wxString &fn )
1319 {
1320 wxString filename( fn );
1321 wxString dir;
1322 m_list->GetDir( dir );
1323 if (filename.IsEmpty()) return;
1324 if (filename == wxT(".")) return;
1325
1326 if (filename == wxT(".."))
1327 {
1328 m_list->GoToParentDir();
1329 m_list->SetFocus();
1330 return;
1331 }
1332
1333 #ifdef __UNIX__
1334 if (filename == wxT("~"))
1335 {
1336 m_list->GoToHomeDir();
1337 m_list->SetFocus();
1338 return;
1339 }
1340
1341 if (filename[0u] == wxT('~'))
1342 {
1343 filename.Remove( 0, 1 );
1344 wxString tmp( wxGetUserHome() );
1345 tmp += wxT('/');
1346 tmp += filename;
1347 filename = tmp;
1348 }
1349 #endif // __UNIX__
1350
1351 if ((filename.Find(wxT('*')) != wxNOT_FOUND) ||
1352 (filename.Find(wxT('?')) != wxNOT_FOUND))
1353 {
1354 if (filename.Find(wxFILE_SEP_PATH) != wxNOT_FOUND)
1355 {
1356 wxMessageBox(_("Illegal file specification."), _("Error"), wxOK | wxICON_ERROR );
1357 return;
1358 }
1359 m_list->SetWild( filename );
1360 return;
1361 }
1362
1363 if (!IsTopMostDir(dir))
1364 dir += wxFILE_SEP_PATH;
1365 if (!wxIsAbsolutePath(filename))
1366 {
1367 dir += filename;
1368 filename = dir;
1369 }
1370
1371 if (wxDirExists(filename))
1372 {
1373 m_list->GoToDir( filename );
1374 return;
1375 }
1376
1377 // append the default extension to the filename if it doesn't have any
1378 //
1379 // VZ: the logic of testing for !wxFileExists() only for the open file
1380 // dialog is not entirely clear to me, why don't we allow saving to a
1381 // file without extension as well?
1382 if ( !(m_dialogStyle & wxOPEN) || !wxFileExists(filename) )
1383 {
1384 wxString ext;
1385 wxSplitPath(filename, NULL, NULL, &ext);
1386 if ( ext.empty() )
1387 {
1388 // append the first extension of the filter string
1389 filename += m_filterExtension.BeforeFirst(_T(';'));
1390 }
1391 }
1392
1393 // check that the file [doesn't] exist if necessary
1394 if ( (m_dialogStyle & wxSAVE) &&
1395 (m_dialogStyle & wxOVERWRITE_PROMPT) &&
1396 wxFileExists( filename ) )
1397 {
1398 wxString msg;
1399 msg.Printf( _("File '%s' already exists, do you really want to "
1400 "overwrite it?"), filename.c_str() );
1401
1402 if (wxMessageBox(msg, _("Confirm"), wxYES_NO) != wxYES)
1403 return;
1404 }
1405 else if ( (m_dialogStyle & wxOPEN) &&
1406 (m_dialogStyle & wxFILE_MUST_EXIST) &&
1407 !wxFileExists(filename) )
1408 {
1409 wxMessageBox(_("Please choose an existing file."), _("Error"),
1410 wxOK | wxICON_ERROR );
1411 }
1412
1413 SetPath( filename );
1414
1415 // change to the directory where the user went if asked
1416 if ( m_dialogStyle & wxCHANGE_DIR )
1417 {
1418 wxString cwd;
1419 wxSplitPath(filename, &cwd, NULL, NULL);
1420
1421 if ( cwd != wxGetWorkingDirectory() )
1422 {
1423 wxSetWorkingDirectory(cwd);
1424 }
1425 }
1426
1427 wxCommandEvent event;
1428 wxDialog::OnOK(event);
1429 }
1430
1431 void wxFileDialog::OnListOk( wxCommandEvent &WXUNUSED(event) )
1432 {
1433 HandleAction( m_text->GetValue() );
1434 }
1435
1436 void wxFileDialog::OnList( wxCommandEvent &WXUNUSED(event) )
1437 {
1438 m_list->ChangeToListMode();
1439 ms_lastViewStyle = wxLC_LIST;
1440 m_list->SetFocus();
1441 }
1442
1443 void wxFileDialog::OnReport( wxCommandEvent &WXUNUSED(event) )
1444 {
1445 m_list->ChangeToReportMode();
1446 ms_lastViewStyle = wxLC_REPORT;
1447 m_list->SetFocus();
1448 }
1449
1450 void wxFileDialog::OnUp( wxCommandEvent &WXUNUSED(event) )
1451 {
1452 m_list->GoToParentDir();
1453 m_list->SetFocus();
1454 }
1455
1456 void wxFileDialog::OnHome( wxCommandEvent &WXUNUSED(event) )
1457 {
1458 m_list->GoToHomeDir();
1459 m_list->SetFocus();
1460 }
1461
1462 void wxFileDialog::OnNew( wxCommandEvent &WXUNUSED(event) )
1463 {
1464 m_list->MakeDir();
1465 }
1466
1467 void wxFileDialog::SetPath( const wxString& path )
1468 {
1469 // not only set the full path but also update filename and dir
1470 m_path = path;
1471 if ( !path.empty() )
1472 {
1473 wxString ext;
1474 wxSplitPath(path, &m_dir, &m_fileName, &ext);
1475 if (!ext.empty())
1476 {
1477 m_fileName += wxT(".");
1478 m_fileName += ext;
1479 }
1480 }
1481 }
1482
1483 void wxFileDialog::GetPaths( wxArrayString& paths ) const
1484 {
1485 paths.Empty();
1486 if (m_list->GetSelectedItemCount() == 0)
1487 {
1488 paths.Add( GetPath() );
1489 return;
1490 }
1491
1492 paths.Alloc( m_list->GetSelectedItemCount() );
1493
1494 wxString dir;
1495 m_list->GetDir( dir );
1496 #ifdef __UNIX__
1497 if (dir != wxT("/"))
1498 #endif
1499 dir += wxFILE_SEP_PATH;
1500
1501 wxListItem item;
1502 item.m_mask = wxLIST_MASK_TEXT;
1503
1504 item.m_itemId = m_list->GetNextItem( -1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );
1505 while ( item.m_itemId != -1 )
1506 {
1507 m_list->GetItem( item );
1508 paths.Add( dir + item.m_text );
1509 item.m_itemId = m_list->GetNextItem( item.m_itemId,
1510 wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );
1511 }
1512 }
1513
1514 void wxFileDialog::GetFilenames(wxArrayString& files) const
1515 {
1516 files.Empty();
1517 if (m_list->GetSelectedItemCount() == 0)
1518 {
1519 files.Add( GetFilename() );
1520 return;
1521 }
1522 files.Alloc( m_list->GetSelectedItemCount() );
1523
1524 wxListItem item;
1525 item.m_mask = wxLIST_MASK_TEXT;
1526
1527 item.m_itemId = m_list->GetNextItem( -1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );
1528 while ( item.m_itemId != -1 )
1529 {
1530 m_list->GetItem( item );
1531 files.Add( item.m_text );
1532 item.m_itemId = m_list->GetNextItem( item.m_itemId,
1533 wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );
1534 }
1535 }
1536
1537
1538
1539 // ----------------------------------------------------------------------------
1540 // global functions
1541 // ----------------------------------------------------------------------------
1542
1543 // common part of both wxFileSelectorEx() and wxFileSelector()
1544 static wxString
1545 DoSelectFile(const wxChar *title,
1546 const wxChar *defaultDir,
1547 const wxChar *defaultFileName,
1548 const wxChar *defaultExtension,
1549 int *indexDefaultExtension,
1550 const wxChar *filter,
1551 int flags,
1552 wxWindow *parent,
1553 int x,
1554 int y)
1555 {
1556 // the filter may be either given explicitly or created automatically from
1557 // the default extension
1558 wxString filterReal;
1559 if ( filter )
1560 {
1561 // the user has specified the filter explicitly, use it
1562 filterReal = filter;
1563 }
1564 else if ( !wxIsEmpty(defaultExtension) )
1565 {
1566 // create the filter to match the given extension
1567 filterReal << wxT("*.") << defaultExtension;
1568 }
1569
1570 wxFileDialog fileDialog(parent,
1571 title,
1572 defaultDir,
1573 defaultFileName,
1574 filterReal,
1575 flags,
1576 wxPoint(x, y));
1577
1578 wxString path;
1579 if ( fileDialog.ShowModal() == wxID_OK )
1580 {
1581 path = fileDialog.GetPath();
1582 if ( indexDefaultExtension )
1583 {
1584 *indexDefaultExtension = fileDialog.GetFilterIndex();
1585 }
1586 }
1587
1588 return path;
1589 }
1590
1591 wxString
1592 wxFileSelectorEx(const wxChar *title,
1593 const wxChar *defaultDir,
1594 const wxChar *defaultFileName,
1595 int *indexDefaultExtension,
1596 const wxChar *filter,
1597 int flags,
1598 wxWindow *parent,
1599 int x,
1600 int y)
1601 {
1602 return DoSelectFile(title,
1603 defaultDir,
1604 defaultFileName,
1605 wxT(""), // def ext determined by index
1606 indexDefaultExtension,
1607 filter,
1608 flags,
1609 parent,
1610 x,
1611 y);
1612 }
1613
1614 wxString
1615 wxFileSelector(const wxChar *title,
1616 const wxChar *defaultDir,
1617 const wxChar *defaultFileName,
1618 const wxChar *defaultExtension,
1619 const wxChar *filter,
1620 int flags,
1621 wxWindow *parent,
1622 int x,
1623 int y)
1624 {
1625 return DoSelectFile(title,
1626 defaultDir,
1627 defaultFileName,
1628 defaultExtension,
1629 NULL, // not interested in filter index
1630 filter,
1631 flags,
1632 parent,
1633 x,
1634 y);
1635 }
1636
1637 static wxString GetWildcardString(const wxChar *ext)
1638 {
1639 wxString wild;
1640 if ( ext )
1641 {
1642 if ( *ext == wxT('.') )
1643 ext++;
1644
1645 wild << _T("*.") << ext;
1646 }
1647 else // no extension specified
1648 {
1649 wild = wxFileSelectorDefaultWildcardStr;
1650 }
1651
1652 return wild;
1653 }
1654
1655 wxString wxLoadFileSelector(const wxChar *what,
1656 const wxChar *ext,
1657 const wxChar *nameDef,
1658 wxWindow *parent)
1659 {
1660 wxString prompt;
1661 if ( what && *what )
1662 prompt = wxString::Format(_("Load %s file"), what);
1663 else
1664 prompt = _("Load file");
1665
1666 return wxFileSelector(prompt, NULL, nameDef, ext,
1667 GetWildcardString(ext), 0, parent);
1668 }
1669
1670 wxString wxSaveFileSelector(const wxChar *what,
1671 const wxChar *ext,
1672 const wxChar *nameDef,
1673 wxWindow *parent)
1674 {
1675 wxString prompt;
1676 if ( what && *what )
1677 prompt = wxString::Format(_("Save %s file"), what);
1678 else
1679 prompt = _("Save file");
1680
1681 return wxFileSelector(prompt, NULL, nameDef, ext,
1682 GetWildcardString(ext), 0, parent);
1683 }
1684
1685 // A module to allow icons table cleanup
1686
1687 class wxFileDialogGenericModule: public wxModule
1688 {
1689 DECLARE_DYNAMIC_CLASS(wxFileDialogGenericModule)
1690 public:
1691 wxFileDialogGenericModule() {}
1692 bool OnInit() { return TRUE; }
1693 void OnExit() { if (g_IconsTable) {delete g_IconsTable; g_IconsTable = NULL;} }
1694 };
1695
1696 IMPLEMENT_DYNAMIC_CLASS(wxFileDialogGenericModule, wxModule)
1697
1698 #endif // wxUSE_FILEDLG
1699