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