]> git.saurik.com Git - wxWidgets.git/blob - src/generic/filedlgg.cpp
long -> wxCoord
[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 #ifdef __GNUG__
13 #pragma implementation "filedlgg.h"
14 #endif
15
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
18
19 #ifdef __BORLANDC__
20 #pragma hdrstop
21 #endif
22
23 #ifndef __UNIX__
24 #error wxFileDialog currently only supports unix
25 #endif
26
27 #include "wx/filedlg.h"
28 #include "wx/debug.h"
29 #include "wx/log.h"
30 #include "wx/intl.h"
31 #include "wx/msgdlg.h"
32 #include "wx/sizer.h"
33 #include "wx/bmpbuttn.h"
34 #include "wx/tokenzr.h"
35 #include "wx/mimetype.h"
36 #include "wx/image.h"
37 #include "wx/module.h"
38 #include "wx/config.h"
39 #include "wx/imaglist.h"
40
41 #if wxUSE_TOOLTIPS
42 #include "wx/tooltip.h"
43 #endif
44
45 #include <sys/types.h>
46 #include <sys/stat.h>
47 #include <dirent.h>
48 #include <pwd.h>
49 #include <grp.h>
50 #include <time.h>
51 #include <unistd.h>
52
53 #include "wx/generic/home.xpm"
54 #include "wx/generic/listview.xpm"
55 #include "wx/generic/repview.xpm"
56 #include "wx/generic/new_dir.xpm"
57 #include "wx/generic/dir_up.xpm"
58 #include "wx/generic/folder.xpm"
59 #include "wx/generic/deffile.xpm"
60 #include "wx/generic/exefile.xpm"
61
62 // ----------------------------------------------------------------------------
63 // private classes - icons list management
64 // ----------------------------------------------------------------------------
65
66 class wxFileIconEntry : public wxObject
67 {
68 public:
69 wxFileIconEntry(int i) { id = i; }
70
71 int id;
72 };
73
74
75 class wxFileIconsTable
76 {
77 public:
78 wxFileIconsTable();
79
80 int GetIconID(const wxString& extension, const wxString& mime = wxEmptyString);
81 wxImageList *GetImageList() { return &m_ImageList; }
82
83 protected:
84 wxImageList m_ImageList;
85 wxHashTable m_HashTable;
86 };
87
88 static wxFileIconsTable *g_IconsTable = NULL;
89
90 #define FI_FOLDER 0
91 #define FI_UNKNOWN 1
92 #define FI_EXECUTABLE 2
93
94 wxFileIconsTable::wxFileIconsTable() :
95 m_ImageList(16, 16),
96 m_HashTable(wxKEY_STRING)
97 {
98 m_HashTable.DeleteContents(TRUE);
99 m_ImageList.Add(wxBitmap(folder_xpm)); // FI_FOLDER
100 m_ImageList.Add(wxBitmap(deffile_xpm)); // FI_UNKNOWN
101 if (GetIconID(wxEmptyString, _T("application/x-executable")) == FI_UNKNOWN)
102 { // FI_EXECUTABLE
103 m_ImageList.Add(wxBitmap(exefile_xpm));
104 m_HashTable.Delete(_T("exe"));
105 m_HashTable.Put(_T("exe"), new wxFileIconEntry(FI_EXECUTABLE));
106 }
107 /* else put into list by GetIconID
108 (KDE defines application/x-executable for *.exe and has nice icon)
109 */
110 }
111
112
113
114 static wxBitmap CreateAntialiasedBitmap(const wxImage& img)
115 {
116 wxImage small(16, 16);
117 unsigned char *p1, *p2, *ps;
118 unsigned char mr = img.GetMaskRed(),
119 mg = img.GetMaskGreen(),
120 mb = img.GetMaskBlue();
121
122 unsigned x, y;
123 unsigned sr, sg, sb, smask;
124
125 p1 = img.GetData(), p2 = img.GetData() + 3 * 32, ps = small.GetData();
126 small.SetMaskColour(mr, mr, mr);
127
128 for (y = 0; y < 16; y++)
129 {
130 for (x = 0; x < 16; x++)
131 {
132 sr = sg = sb = smask = 0;
133 if (p1[0] != mr || p1[1] != mg || p1[2] != mb)
134 sr += p1[0], sg += p1[1], sb += p1[2];
135 else smask++;
136 p1 += 3;
137 if (p1[0] != mr || p1[1] != mg || p1[2] != mb)
138 sr += p1[0], sg += p1[1], sb += p1[2];
139 else smask++;
140 p1 += 3;
141 if (p2[0] != mr || p2[1] != mg || p2[2] != mb)
142 sr += p2[0], sg += p2[1], sb += p2[2];
143 else smask++;
144 p2 += 3;
145 if (p2[0] != mr || p2[1] != mg || p2[2] != mb)
146 sr += p2[0], sg += p2[1], sb += p2[2];
147 else smask++;
148 p2 += 3;
149
150 if (smask > 2)
151 ps[0] = ps[1] = ps[2] = mr;
152 else
153 ps[0] = sr >> 2, ps[1] = sg >> 2, ps[2] = sb >> 2;
154 ps += 3;
155 }
156 p1 += 32 * 3, p2 += 32 * 3;
157 }
158
159 return small.ConvertToBitmap();
160 }
161
162
163 // finds empty borders and return non-empty area of image:
164 static wxImage CutEmptyBorders(const wxImage& img)
165 {
166 unsigned char mr = img.GetMaskRed(),
167 mg = img.GetMaskGreen(),
168 mb = img.GetMaskBlue();
169 unsigned char *dt = img.GetData(), *dttmp;
170 unsigned w = img.GetWidth(), h = img.GetHeight();
171
172 unsigned top, bottom, left, right, i;
173 bool empt;
174
175 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
176 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = FALSE; break;}
177
178 for (empt = TRUE, top = 0; empt && top < h; top++)
179 {
180 MK_DTTMP(0, top);
181 for (i = 0; i < w; i++, dttmp+=3)
182 NOEMPTY_PIX(empt)
183 }
184 for (empt = TRUE, bottom = h-1; empt && bottom > top; bottom--)
185 {
186 MK_DTTMP(0, bottom);
187 for (i = 0; i < w; i++, dttmp+=3)
188 NOEMPTY_PIX(empt)
189 }
190 for (empt = TRUE, left = 0; empt && left < w; left++)
191 {
192 MK_DTTMP(left, 0);
193 for (i = 0; i < h; i++, dttmp+=3*w)
194 NOEMPTY_PIX(empt)
195 }
196 for (empt = TRUE, right = w-1; empt && right > left; right--)
197 {
198 MK_DTTMP(right, 0);
199 for (i = 0; i < h; i++, dttmp+=3*w)
200 NOEMPTY_PIX(empt)
201 }
202 top--, left--, bottom++, right++;
203
204 return img.GetSubImage(wxRect(left, top, right - left + 1, bottom - top + 1));
205 }
206
207
208
209 int wxFileIconsTable::GetIconID(const wxString& extension, const wxString& mime)
210 {
211 if (!extension.IsEmpty())
212 {
213 wxFileIconEntry *entry = (wxFileIconEntry*) m_HashTable.Get(extension);
214 if (entry) return (entry -> id);
215 }
216
217 wxFileType *ft = (mime.IsEmpty()) ?
218 wxTheMimeTypesManager -> GetFileTypeFromExtension(extension) :
219 wxTheMimeTypesManager -> GetFileTypeFromMimeType(mime);
220 wxIcon ic;
221 if (ft == NULL || (!ft -> GetIcon(&ic)) || (!ic.Ok()))
222 {
223 int newid = FI_UNKNOWN;
224 m_HashTable.Put(extension, new wxFileIconEntry(newid));
225 return newid;
226 }
227 wxImage img(ic);
228 delete ft;
229
230 int id = m_ImageList.GetImageCount();
231 if (img.GetWidth() == 16 && img.GetHeight() == 16)
232 m_ImageList.Add(img.ConvertToBitmap());
233 else
234 {
235 if (img.GetWidth() != 32 || img.GetHeight() != 32)
236 m_ImageList.Add(CreateAntialiasedBitmap(CutEmptyBorders(img).Rescale(32, 32)));
237 else
238 m_ImageList.Add(CreateAntialiasedBitmap(img));
239 }
240 m_HashTable.Put(extension, new wxFileIconEntry(id));
241 return id;
242 }
243
244
245
246 // ----------------------------------------------------------------------------
247 // private functions
248 // ----------------------------------------------------------------------------
249
250 static
251 int ListCompare( long data1, long data2, long WXUNUSED(data) )
252 {
253 wxFileData *fd1 = (wxFileData*)data1 ;
254 wxFileData *fd2 = (wxFileData*)data2 ;
255 if (fd1->GetName() == wxT("..")) return -1;
256 if (fd2->GetName() == wxT("..")) return 1;
257 if (fd1->IsDir() && !fd2->IsDir()) return -1;
258 if (fd2->IsDir() && !fd1->IsDir()) return 1;
259 return wxStrcmp( fd1->GetName(), fd2->GetName() );
260 }
261
262 //-----------------------------------------------------------------------------
263 // wxFileData
264 //-----------------------------------------------------------------------------
265
266 IMPLEMENT_DYNAMIC_CLASS(wxFileData,wxObject);
267
268 wxFileData::wxFileData( const wxString &name, const wxString &fname )
269 {
270 m_name = name;
271 m_fileName = fname;
272
273 struct stat buff;
274 stat( m_fileName.fn_str(), &buff );
275
276 #ifndef __EMX__
277 struct stat lbuff;
278 lstat( m_fileName.fn_str(), &lbuff );
279 m_isLink = S_ISLNK( lbuff.st_mode );
280 struct tm *t = localtime( &lbuff.st_mtime );
281 #else
282 m_isLink = FALSE;
283 struct tm *t = localtime( &buff.st_mtime );
284 #endif
285
286 // struct passwd *user = getpwuid( buff.st_uid );
287 // struct group *grp = getgrgid( buff.st_gid );
288
289 m_isDir = S_ISDIR( buff.st_mode );
290 m_isExe = ((buff.st_mode & S_IXUSR ) == S_IXUSR );
291
292 m_size = buff.st_size;
293
294 m_hour = t->tm_hour;
295 m_minute = t->tm_min;
296 m_month = t->tm_mon+1;
297 m_day = t->tm_mday;
298 m_year = t->tm_year;
299 m_year += 1900;
300
301 m_permissions.sprintf( wxT("%c%c%c"),
302 ((( buff.st_mode & S_IRUSR ) == S_IRUSR ) ? wxT('r') : wxT('-')),
303 ((( buff.st_mode & S_IWUSR ) == S_IWUSR ) ? wxT('w') : wxT('-')),
304 ((( buff.st_mode & S_IXUSR ) == S_IXUSR ) ? wxT('x') : wxT('-')) );
305 }
306
307 wxString wxFileData::GetName() const
308 {
309 return m_name;
310 }
311
312 wxString wxFileData::GetFullName() const
313 {
314 return m_fileName;
315 }
316
317 wxString wxFileData::GetHint() const
318 {
319 wxString s = m_fileName;
320 s += " ";
321 if (m_isDir) s += _("<DIR> ");
322 else if (m_isLink) s += _("<LINK> ");
323 else
324 {
325 s += LongToString( m_size );
326 s += _(" bytes ");
327 }
328 s += IntToString( m_day );
329 s += wxT(".");
330 s += IntToString( m_month );
331 s += wxT(".");
332 s += IntToString( m_year );
333 s += wxT(" ");
334 s += IntToString( m_hour );
335 s += wxT(":");
336 s += IntToString( m_minute );
337 s += wxT(" ");
338 s += m_permissions;
339 return s;
340 };
341
342 wxString wxFileData::GetEntry( int num )
343 {
344 wxString s;
345 switch (num)
346 {
347 case 0:
348 {
349 s = m_name;
350 }
351 break;
352 case 1:
353 {
354 if (m_isDir) s = _("<DIR>");
355 else if (m_isLink) s = _("<LINK>");
356 else s = LongToString( m_size );
357 }
358 break;
359 case 2:
360 {
361 if (m_day < 10) s = wxT("0"); else s = wxT("");
362 s += IntToString( m_day );
363 s += wxT(".");
364 if (m_month < 10) s += wxT("0");
365 s += IntToString( m_month );
366 s += wxT(".");
367 s += IntToString( m_year );
368 }
369 break;
370 case 3:
371 {
372 if (m_hour < 10) s = wxT("0"); else s = wxT("");
373 s += IntToString( m_hour );
374 s += wxT(":");
375 if (m_minute < 10) s += wxT("0");
376 s += IntToString( m_minute );
377 break;
378 }
379 case 4:
380 s = m_permissions;
381 break;
382 default:
383 s = wxT("No entry");
384 break;
385 }
386 return s;
387 }
388
389 bool wxFileData::IsDir()
390 {
391 return m_isDir;
392 }
393
394 bool wxFileData::IsExe()
395 {
396 return m_isExe;
397 }
398
399 bool wxFileData::IsLink()
400 {
401 return m_isLink;
402 }
403
404 long wxFileData::GetSize()
405 {
406 return m_size;
407 }
408
409 void wxFileData::SetNewName( const wxString &name, const wxString &fname )
410 {
411 m_name = name;
412 m_fileName = fname;
413 }
414
415 void wxFileData::MakeItem( wxListItem &item )
416 {
417 item.m_text = m_name;
418 item.ClearAttributes();
419 if (IsExe()) item.SetTextColour(*wxRED);
420 if (IsDir()) item.SetTextColour(*wxBLUE);
421
422 if (IsDir())
423 item.m_image = FI_FOLDER;
424 else if (IsExe())
425 item.m_image = FI_EXECUTABLE;
426 else if (m_name.Find(wxT('.')) != wxNOT_FOUND)
427 item.m_image = g_IconsTable -> GetIconID(m_name.AfterLast(wxT('.')));
428 else
429 item.m_image = FI_UNKNOWN;
430
431 if (IsLink())
432 {
433 wxColour *dg = wxTheColourDatabase->FindColour( "MEDIUM GREY" );
434 item.SetTextColour(*dg);
435 }
436 item.m_data = (long)this;
437 }
438
439 //-----------------------------------------------------------------------------
440 // wxFileCtrl
441 //-----------------------------------------------------------------------------
442
443 IMPLEMENT_DYNAMIC_CLASS(wxFileCtrl,wxListCtrl);
444
445 BEGIN_EVENT_TABLE(wxFileCtrl,wxListCtrl)
446 EVT_LIST_DELETE_ITEM(-1, wxFileCtrl::OnListDeleteItem)
447 EVT_LIST_END_LABEL_EDIT(-1, wxFileCtrl::OnListEndLabelEdit)
448 END_EVENT_TABLE()
449
450
451
452 wxFileCtrl::wxFileCtrl()
453 {
454 m_dirName = wxT("/");
455 m_showHidden = FALSE;
456 }
457
458 wxFileCtrl::wxFileCtrl( wxWindow *win, wxWindowID id,
459 const wxString &dirName, const wxString &wild,
460 const wxPoint &pos, const wxSize &size,
461 long style, const wxValidator &validator, const wxString &name ) :
462 wxListCtrl( win, id, pos, size, style, validator, name )
463 {
464 if (! g_IconsTable) g_IconsTable = new wxFileIconsTable;
465 wxImageList *imageList = g_IconsTable -> GetImageList();
466
467 SetImageList( imageList, wxIMAGE_LIST_SMALL );
468
469 m_dirName = dirName;
470 m_wild = wild;
471 m_showHidden = FALSE;
472 Update();
473 }
474
475 void wxFileCtrl::ChangeToListMode()
476 {
477 SetSingleStyle( wxLC_LIST );
478 Update();
479 }
480
481 void wxFileCtrl::ChangeToReportMode()
482 {
483 SetSingleStyle( wxLC_REPORT );
484 Update();
485 }
486
487 void wxFileCtrl::ChangeToIconMode()
488 {
489 SetSingleStyle( wxLC_ICON );
490 Update();
491 }
492
493 void wxFileCtrl::ShowHidden( bool show )
494 {
495 m_showHidden = show;
496 Update();
497 }
498
499 long wxFileCtrl::Add( wxFileData *fd, wxListItem &item )
500 {
501 long ret = -1;
502 item.m_mask = wxLIST_MASK_TEXT + wxLIST_MASK_DATA + wxLIST_MASK_IMAGE;
503 fd->MakeItem( item );
504 long my_style = GetWindowStyleFlag();
505 if (my_style & wxLC_REPORT)
506 {
507 ret = InsertItem( item );
508 for (int i = 1; i < 5; i++) SetItem( item.m_itemId, i, fd->GetEntry( i) );
509 }
510 else if (my_style & wxLC_LIST)
511 {
512 ret = InsertItem( item );
513 }
514 return ret;
515 }
516
517 void wxFileCtrl::Update()
518 {
519 long my_style = GetWindowStyleFlag();
520 int name_col_width = 0;
521 if (my_style & wxLC_REPORT)
522 {
523 if (GetColumnCount() > 0)
524 name_col_width = GetColumnWidth( 0 );
525 }
526
527 ClearAll();
528 if (my_style & wxLC_REPORT)
529 {
530 if (name_col_width < 140) name_col_width = 140;
531 InsertColumn( 0, _("Name"), wxLIST_FORMAT_LEFT, name_col_width );
532 InsertColumn( 1, _("Size"), wxLIST_FORMAT_LEFT, 60 );
533 InsertColumn( 2, _("Date"), wxLIST_FORMAT_LEFT, 65 );
534 InsertColumn( 3, _("Time"), wxLIST_FORMAT_LEFT, 50 );
535 InsertColumn( 4, _("Permissions"), wxLIST_FORMAT_LEFT, 120 );
536 }
537 wxFileData *fd = (wxFileData *) NULL;
538 wxListItem item;
539 item.m_itemId = 0;
540 item.m_col = 0;
541
542 if (m_dirName != wxT("/"))
543 {
544 wxString p( wxPathOnly(m_dirName) );
545 if (p.IsEmpty()) p = wxT("/");
546 fd = new wxFileData( wxT(".."), p );
547 Add( fd, item );
548 item.m_itemId++;
549 }
550
551 wxString res = m_dirName + wxT("/*");
552 wxString f( wxFindFirstFile( res.GetData(), wxDIR ) );
553 while (!f.IsEmpty())
554 {
555 res = wxFileNameFromPath( f );
556 fd = new wxFileData( res, f );
557 wxString s = fd->GetName();
558 if (m_showHidden || (s[0] != wxT('.')))
559 {
560 Add( fd, item );
561 item.m_itemId++;
562 }
563 f = wxFindNextFile();
564 }
565
566 res = m_dirName + wxT("/") + m_wild;
567 f = wxFindFirstFile( res.GetData(), wxFILE );
568 while (!f.IsEmpty())
569 {
570 res = wxFileNameFromPath( f );
571 fd = new wxFileData( res, f );
572 wxString s = fd->GetName();
573 if (m_showHidden || (s[0] != wxT('.')))
574 {
575 Add( fd, item );
576 item.m_itemId++;
577 }
578 f = wxFindNextFile();
579 }
580
581 SortItems( ListCompare, 0 );
582
583 SetColumnWidth( 1, wxLIST_AUTOSIZE );
584 SetColumnWidth( 2, wxLIST_AUTOSIZE );
585 SetColumnWidth( 3, wxLIST_AUTOSIZE );
586 }
587
588 void wxFileCtrl::SetWild( const wxString &wild )
589 {
590 m_wild = wild;
591 Update();
592 }
593
594 void wxFileCtrl::MakeDir()
595 {
596 wxString new_name( wxT("NewName") );
597 wxString path( m_dirName );
598 path += wxT("/");
599 path += new_name;
600 if (wxFileExists(path))
601 {
602 // try NewName0, NewName1 etc.
603 int i = 0;
604 do {
605 new_name = _("NewName");
606 wxString num;
607 num.Printf( wxT("%d"), i );
608 new_name += num;
609
610 path = m_dirName;
611 path += wxT("/");
612 path += new_name;
613 i++;
614 } while (wxFileExists(path));
615 }
616
617 wxLogNull log;
618 if (!wxMkdir(path))
619 {
620 wxMessageDialog dialog(this, _("Operation not permitted."), _("Error"), wxOK | wxICON_ERROR );
621 dialog.ShowModal();
622 return;
623 }
624
625 wxFileData *fd = new wxFileData( new_name, path );
626 wxListItem item;
627 item.m_itemId = 0;
628 item.m_col = 0;
629 long id = Add( fd, item );
630
631 if (id != -1)
632 {
633 SortItems( ListCompare, 0 );
634 id = FindItem( 0, (long)fd );
635 EnsureVisible( id );
636 EditLabel( id );
637 }
638 }
639
640 void wxFileCtrl::GoToParentDir()
641 {
642 if (m_dirName != wxT("/"))
643 {
644 wxString fname( wxFileNameFromPath(m_dirName) );
645 m_dirName = wxPathOnly( m_dirName );
646 if (m_dirName.IsEmpty()) m_dirName = wxT("/");
647 Update();
648 long id = FindItem( 0, fname );
649 if (id != -1)
650 {
651 SetItemState( id, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
652 EnsureVisible( id );
653 }
654 }
655 }
656
657 void wxFileCtrl::GoToHomeDir()
658 {
659 wxString s = wxGetUserHome( wxString() );
660 m_dirName = s;
661 Update();
662 SetItemState( 0, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
663 EnsureVisible( 0 );
664 }
665
666 void wxFileCtrl::GoToDir( const wxString &dir )
667 {
668 m_dirName = dir;
669 Update();
670 SetItemState( 0, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
671 EnsureVisible( 0 );
672 }
673
674 void wxFileCtrl::GetDir( wxString &dir )
675 {
676 dir = m_dirName;
677 }
678
679 void wxFileCtrl::OnListDeleteItem( wxListEvent &event )
680 {
681 wxFileData *fd = (wxFileData*)event.m_item.m_data;
682 delete fd;
683 }
684
685 void wxFileCtrl::OnListEndLabelEdit( wxListEvent &event )
686 {
687 wxFileData *fd = (wxFileData*)event.m_item.m_data;
688 wxASSERT( fd );
689
690 if ((event.GetLabel().IsEmpty()) ||
691 (event.GetLabel() == _(".")) ||
692 (event.GetLabel() == _("..")) ||
693 (event.GetLabel().First( wxT("/") ) != wxNOT_FOUND))
694 {
695 wxMessageDialog dialog(this, _("Illegal directory name."), _("Error"), wxOK | wxICON_ERROR );
696 dialog.ShowModal();
697 event.Veto();
698 return;
699 }
700
701 wxString new_name( wxPathOnly( fd->GetFullName() ) );
702 new_name += wxT("/");
703 new_name += event.GetLabel();
704
705 wxLogNull log;
706
707 if (wxFileExists(new_name))
708 {
709 wxMessageDialog dialog(this, _("File name exists already."), _("Error"), wxOK | wxICON_ERROR );
710 dialog.ShowModal();
711 event.Veto();
712 }
713
714 if (wxRenameFile(fd->GetFullName(),new_name))
715 {
716 fd->SetNewName( new_name, event.GetLabel() );
717 SetItemState( event.GetItem(), wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
718 EnsureVisible( event.GetItem() );
719 }
720 else
721 {
722 wxMessageDialog dialog(this, _("Operation not permitted."), _("Error"), wxOK | wxICON_ERROR );
723 dialog.ShowModal();
724 event.Veto();
725 }
726 }
727
728 //-----------------------------------------------------------------------------
729 // wxFileDialog
730 //-----------------------------------------------------------------------------
731
732 #define ID_LIST_MODE wxID_FILEDLGG
733 #define ID_REPORT_MODE wxID_FILEDLGG + 1
734 #define ID_UP_DIR wxID_FILEDLGG + 5
735 #define ID_PARENT_DIR wxID_FILEDLGG + 6
736 #define ID_NEW_DIR wxID_FILEDLGG + 7
737 #define ID_CHOICE wxID_FILEDLGG + 8
738 #define ID_TEXT wxID_FILEDLGG + 9
739 #define ID_LIST_CTRL wxID_FILEDLGG + 10
740 #define ID_ACTIVATED wxID_FILEDLGG + 11
741 #define ID_CHECK wxID_FILEDLGG + 12
742
743 IMPLEMENT_DYNAMIC_CLASS(wxFileDialog,wxDialog)
744
745 BEGIN_EVENT_TABLE(wxFileDialog,wxDialog)
746 EVT_BUTTON(ID_LIST_MODE, wxFileDialog::OnList)
747 EVT_BUTTON(ID_REPORT_MODE, wxFileDialog::OnReport)
748 EVT_BUTTON(ID_UP_DIR, wxFileDialog::OnUp)
749 EVT_BUTTON(ID_PARENT_DIR, wxFileDialog::OnHome)
750 EVT_BUTTON(ID_NEW_DIR, wxFileDialog::OnNew)
751 EVT_BUTTON(wxID_OK, wxFileDialog::OnListOk)
752 EVT_LIST_ITEM_SELECTED(ID_LIST_CTRL, wxFileDialog::OnSelected)
753 EVT_LIST_ITEM_ACTIVATED(ID_LIST_CTRL, wxFileDialog::OnActivated)
754 EVT_CHOICE(ID_CHOICE,wxFileDialog::OnChoice)
755 EVT_TEXT_ENTER(ID_TEXT,wxFileDialog::OnTextEnter)
756 EVT_CHECKBOX(ID_CHECK,wxFileDialog::OnCheck)
757 END_EVENT_TABLE()
758
759 long wxFileDialog::s_lastViewStyle = wxLC_LIST;
760 bool wxFileDialog::s_lastShowHidden = FALSE;
761
762 wxFileDialog::wxFileDialog(wxWindow *parent,
763 const wxString& message,
764 const wxString& defaultDir,
765 const wxString& defaultFile,
766 const wxString& wildCard,
767 long style,
768 const wxPoint& pos ) :
769 wxDialog( parent, -1, message, pos, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER )
770 {
771 wxBeginBusyCursor();
772
773 if (wxConfig::Get(FALSE))
774 {
775 wxConfig::Get() -> Read(wxT("/wxWindows/wxFileDialog/ViewStyle"), &s_lastViewStyle);
776 wxConfig::Get() -> Read(wxT("/wxWindows/wxFileDialog/ShowHidden"), &s_lastShowHidden);
777 }
778
779 m_message = message;
780 m_dialogStyle = style;
781
782 if (m_dialogStyle == 0) m_dialogStyle = wxOPEN;
783 if ((m_dialogStyle & wxMULTIPLE ) && !(m_dialogStyle & wxOPEN))
784 m_dialogStyle |= wxOPEN;
785
786 m_dir = defaultDir;
787 if ((m_dir.IsEmpty()) || (m_dir == wxT(".")))
788 {
789 char buf[200];
790 m_dir = getcwd( buf, sizeof(buf) );
791 }
792 m_path = defaultDir;
793 m_path += wxT("/");
794 m_path += defaultFile;
795 m_fileName = defaultFile;
796 m_wildCard = wildCard;
797 m_filterIndex = 0;
798 m_filterExtension = wxEmptyString;
799
800 // interpret wildcards
801
802 if (m_wildCard.IsEmpty())
803 m_wildCard = _("All files (*)|*");
804
805 wxStringTokenizer tokens( m_wildCard, wxT("|") );
806 wxString firstWild;
807 wxString firstWildText;
808 if (tokens.CountTokens() == 1)
809 {
810 firstWildText = tokens.GetNextToken();
811 firstWild = firstWildText;
812 }
813 else
814 {
815 wxASSERT_MSG( tokens.CountTokens() % 2 == 0, wxT("Wrong file type descripition") );
816 firstWildText = tokens.GetNextToken();
817 firstWild = tokens.GetNextToken();
818 }
819 if ( firstWild.Left( 2 ) == wxT("*.") )
820 m_filterExtension = firstWild.Mid( 1 );
821 if ( m_filterExtension == ".*" ) m_filterExtension = wxEmptyString;
822
823 // layout
824
825 wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL );
826
827 wxBoxSizer *buttonsizer = new wxBoxSizer( wxHORIZONTAL );
828
829 wxBitmapButton *but;
830
831 but = new wxBitmapButton( this, ID_LIST_MODE, wxBitmap( listview_xpm ) );
832 #if wxUSE_TOOLTIPS
833 but->SetToolTip( _("View files as a list view") );
834 #endif
835 buttonsizer->Add( but, 0, wxALL, 5 );
836
837 but = new wxBitmapButton( this, ID_REPORT_MODE, wxBitmap( repview_xpm ) );
838 #if wxUSE_TOOLTIPS
839 but->SetToolTip( _("View files as a detailed view") );
840 #endif
841 buttonsizer->Add( but, 0, wxALL, 5 );
842
843 buttonsizer->Add( 30, 5, 1 );
844
845 but = new wxBitmapButton( this, ID_UP_DIR, wxBitmap( dir_up_xpm ) );
846 #if wxUSE_TOOLTIPS
847 but->SetToolTip( _("Go to parent directory") );
848 #endif
849 buttonsizer->Add( but, 0, wxALL, 5 );
850
851 but = new wxBitmapButton( this, ID_PARENT_DIR, wxBitmap(home_xpm) );
852 #if wxUSE_TOOLTIPS
853 but->SetToolTip( _("Go to home directory") );
854 #endif
855 buttonsizer->Add( but, 0, wxALL, 5);
856
857 buttonsizer->Add( 20, 20 );
858
859 but = new wxBitmapButton( this, ID_NEW_DIR, wxBitmap(new_dir_xpm) );
860 #if wxUSE_TOOLTIPS
861 but->SetToolTip( _("Create new directory") );
862 #endif
863 buttonsizer->Add( but, 0, wxALL, 5 );
864
865 mainsizer->Add( buttonsizer, 0, wxALL | wxEXPAND, 5 );
866
867 wxBoxSizer *staticsizer = new wxBoxSizer( wxHORIZONTAL );
868 staticsizer->Add( new wxStaticText( this, -1, _("Current directory:") ), 0, wxRIGHT, 10 );
869 m_static = new wxStaticText( this, -1, m_dir );
870 staticsizer->Add( m_static, 1 );
871 mainsizer->Add( staticsizer, 0, wxEXPAND | wxLEFT|wxRIGHT|wxBOTTOM, 10 );
872
873 if (m_dialogStyle & wxMULTIPLE)
874 m_list = new wxFileCtrl( this, ID_LIST_CTRL, m_dir, firstWild, wxDefaultPosition,
875 wxSize(440,180), s_lastViewStyle | wxSUNKEN_BORDER );
876 else
877 m_list = new wxFileCtrl( this, ID_LIST_CTRL, m_dir, firstWild, wxDefaultPosition,
878 wxSize(440,180), s_lastViewStyle | wxSUNKEN_BORDER | wxLC_SINGLE_SEL );
879 m_list -> ShowHidden(s_lastShowHidden);
880 mainsizer->Add( m_list, 1, wxEXPAND | wxLEFT|wxRIGHT, 10 );
881
882 wxBoxSizer *textsizer = new wxBoxSizer( wxHORIZONTAL );
883 m_text = new wxTextCtrl( this, ID_TEXT, m_fileName, wxDefaultPosition, wxDefaultSize, wxPROCESS_ENTER );
884 textsizer->Add( m_text, 1, wxCENTER | wxLEFT|wxRIGHT|wxTOP, 10 );
885 textsizer->Add( new wxButton( this, wxID_OK, _("OK") ), 0, wxCENTER | wxLEFT|wxRIGHT|wxTOP, 10 );
886 mainsizer->Add( textsizer, 0, wxEXPAND );
887
888 wxBoxSizer *choicesizer = new wxBoxSizer( wxHORIZONTAL );
889 m_choice = new wxChoice( this, ID_CHOICE );
890 choicesizer->Add( m_choice, 1, wxCENTER|wxALL, 10 );
891 m_check = new wxCheckBox( this, ID_CHECK, _("Show hidden files") );
892 m_check->SetValue( s_lastShowHidden );
893 choicesizer->Add( m_check, 0, wxCENTER|wxALL, 10 );
894 choicesizer->Add( new wxButton( this, wxID_CANCEL, _("Cancel") ), 0, wxCENTER | wxALL, 10 );
895 mainsizer->Add( choicesizer, 0, wxEXPAND );
896
897 m_choice->Append( firstWildText, (void*) new wxString( firstWild ) );
898 while (tokens.HasMoreTokens())
899 {
900 firstWildText = tokens.GetNextToken();
901 firstWild = tokens.GetNextToken();
902 m_choice->Append( firstWildText, (void*) new wxString( firstWild ) );
903 }
904 m_choice->SetSelection( 0 );
905
906 SetAutoLayout( TRUE );
907 SetSizer( mainsizer );
908
909 mainsizer->Fit( this );
910 mainsizer->SetSizeHints( this );
911
912 Centre( wxBOTH );
913
914 if (m_fileName.IsEmpty())
915 m_list->SetFocus();
916 else
917 m_text->SetFocus();
918
919 wxEndBusyCursor();
920 }
921
922 wxFileDialog::~wxFileDialog()
923 {
924 if (wxConfig::Get(FALSE))
925 {
926 wxConfig::Get() -> Write(wxT("/wxWindows/wxFileDialog/ViewStyle"), s_lastViewStyle);
927 wxConfig::Get() -> Write(wxT("/wxWindows/wxFileDialog/ShowHidden"), s_lastShowHidden);
928 }
929 }
930
931 void wxFileDialog::OnChoice( wxCommandEvent &event )
932 {
933 int index = (int)event.GetInt();
934 wxString *str = (wxString*) m_choice->GetClientData( index );
935 m_list->SetWild( *str );
936 m_filterIndex = index;
937 if ( str -> Left( 2 ) == wxT("*.") )
938 {
939 m_filterExtension = str -> Mid( 1 );
940 if (m_filterExtension == ".*") m_filterExtension = wxEmptyString;
941 }
942 else
943 m_filterExtension = wxEmptyString;
944 }
945
946 void wxFileDialog::OnCheck( wxCommandEvent &event )
947 {
948 m_list->ShowHidden( (s_lastShowHidden = event.GetInt() != 0) );
949 }
950
951 void wxFileDialog::OnActivated( wxListEvent &event )
952 {
953 HandleAction( event.m_item.m_text );
954 }
955
956 void wxFileDialog::OnTextEnter( wxCommandEvent &WXUNUSED(event) )
957 {
958 wxCommandEvent cevent(wxEVT_COMMAND_BUTTON_CLICKED, wxID_OK);
959 cevent.SetEventObject( this );
960 GetEventHandler()->ProcessEvent( cevent );
961 }
962
963 void wxFileDialog::OnSelected( wxListEvent &event )
964 {
965 if (FindFocus() != m_list) return;
966
967 wxString filename( event.m_item.m_text );
968 if (filename == wxT("..")) return;
969
970 wxString dir;
971 m_list->GetDir( dir );
972 if (dir != wxT("/")) dir += wxT("/");
973 dir += filename;
974 if (wxDirExists(dir)) return;
975
976 m_text->SetValue( filename );
977 }
978
979 void wxFileDialog::HandleAction( const wxString &fn )
980 {
981 wxString filename( fn );
982 wxString dir;
983 m_list->GetDir( dir );
984 if (filename.IsEmpty()) return;
985 if (filename == wxT(".")) return;
986
987 if (filename == wxT(".."))
988 {
989 m_list->GoToParentDir();
990 m_list->SetFocus();
991 m_list->GetDir( dir );
992 m_static->SetLabel( dir );
993 return;
994 }
995
996 if (filename == wxT("~"))
997 {
998 m_list->GoToHomeDir();
999 m_list->SetFocus();
1000 m_list->GetDir( dir );
1001 m_static->SetLabel( dir );
1002 return;
1003 }
1004
1005 if (filename[0] == wxT('~'))
1006 {
1007 filename.Remove( 0, 1 );
1008 wxString tmp( wxGetUserHome() );
1009 tmp += wxT('/');
1010 tmp += filename;
1011 filename = tmp;
1012 }
1013
1014 if ((filename.Find(wxT('*')) != wxNOT_FOUND) ||
1015 (filename.Find(wxT('?')) != wxNOT_FOUND))
1016 {
1017 if (filename.Find(wxT('/')) != wxNOT_FOUND)
1018 {
1019 wxMessageBox(_("Illegal file specification."), _("Error"), wxOK | wxICON_ERROR );
1020 return;
1021 }
1022 m_list->SetWild( filename );
1023 return;
1024 }
1025
1026 if (dir != wxT("/")) dir += wxT("/");
1027 if (filename[0] != wxT('/'))
1028 {
1029 dir += filename;
1030 filename = dir;
1031 }
1032
1033 if (wxDirExists(filename))
1034 {
1035 m_list->GoToDir( filename );
1036 m_list->GetDir( dir );
1037 m_static->SetLabel( dir );
1038 return;
1039 }
1040
1041
1042 if ( (m_dialogStyle & wxSAVE) && (m_dialogStyle & wxOVERWRITE_PROMPT) )
1043 {
1044 if (filename.Find( wxT('.') ) == wxNOT_FOUND ||
1045 filename.AfterLast( wxT('.') ).Find( wxT('/') ) != wxNOT_FOUND)
1046 filename << m_filterExtension;
1047 if (wxFileExists( filename ))
1048 {
1049 wxString msg;
1050 msg.Printf( _("File '%s' already exists, do you really want to "
1051 "overwrite it?"), filename.c_str() );
1052
1053 if (wxMessageBox(msg, _("Confirm"), wxYES_NO) != wxYES)
1054 return;
1055 }
1056 }
1057 else if ( m_dialogStyle & wxOPEN )
1058 {
1059 if ( !wxFileExists( filename ) )
1060 if (filename.Find( wxT('.') ) == wxNOT_FOUND ||
1061 filename.AfterLast( wxT('.') ).Find( wxT('/') ) != wxNOT_FOUND)
1062 filename << m_filterExtension;
1063
1064 if ( m_dialogStyle & wxFILE_MUST_EXIST )
1065 {
1066 if ( !wxFileExists( filename ) )
1067 {
1068 wxMessageBox(_("Please choose an existing file."), _("Error"), wxOK | wxICON_ERROR );
1069 return;
1070 }
1071 }
1072 }
1073
1074 SetPath( filename );
1075
1076 wxCommandEvent event;
1077 wxDialog::OnOK(event);
1078 }
1079
1080 void wxFileDialog::OnListOk( wxCommandEvent &WXUNUSED(event) )
1081 {
1082 HandleAction( m_text->GetValue() );
1083 }
1084
1085 void wxFileDialog::OnList( wxCommandEvent &WXUNUSED(event) )
1086 {
1087 m_list->ChangeToListMode();
1088 s_lastViewStyle = wxLC_LIST;
1089 m_list->SetFocus();
1090 }
1091
1092 void wxFileDialog::OnReport( wxCommandEvent &WXUNUSED(event) )
1093 {
1094 m_list->ChangeToReportMode();
1095 s_lastViewStyle = wxLC_REPORT;
1096 m_list->SetFocus();
1097 }
1098
1099 void wxFileDialog::OnUp( wxCommandEvent &WXUNUSED(event) )
1100 {
1101 m_list->GoToParentDir();
1102 m_list->SetFocus();
1103 wxString dir;
1104 m_list->GetDir( dir );
1105 m_static->SetLabel( dir );
1106 }
1107
1108 void wxFileDialog::OnHome( wxCommandEvent &WXUNUSED(event) )
1109 {
1110 m_list->GoToHomeDir();
1111 m_list->SetFocus();
1112 wxString dir;
1113 m_list->GetDir( dir );
1114 m_static->SetLabel( dir );
1115 }
1116
1117 void wxFileDialog::OnNew( wxCommandEvent &WXUNUSED(event) )
1118 {
1119 m_list->MakeDir();
1120 }
1121
1122 void wxFileDialog::SetPath( const wxString& path )
1123 {
1124 // not only set the full path but also update filename and dir
1125 m_path = path;
1126 if ( !!path )
1127 {
1128 wxString ext;
1129 wxSplitPath(path, &m_dir, &m_fileName, &ext);
1130 if (!ext.IsEmpty())
1131 {
1132 m_fileName += wxT(".");
1133 m_fileName += ext;
1134 }
1135 }
1136 }
1137
1138 void wxFileDialog::GetPaths( wxArrayString& paths ) const
1139 {
1140 paths.Empty();
1141 if (m_list->GetSelectedItemCount() == 0)
1142 {
1143 paths.Add( GetPath() );
1144 return;
1145 }
1146
1147 paths.Alloc( m_list->GetSelectedItemCount() );
1148
1149 wxString dir;
1150 m_list->GetDir( dir );
1151 if (dir != wxT("/")) dir += wxT("/");
1152
1153 wxListItem item;
1154 item.m_mask = wxLIST_MASK_TEXT;
1155
1156 item.m_itemId = m_list->GetNextItem( -1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );
1157 while ( item.m_itemId != -1 )
1158 {
1159 m_list->GetItem( item );
1160 paths.Add( dir + item.m_text );
1161 item.m_itemId = m_list->GetNextItem( item.m_itemId,
1162 wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );
1163 }
1164 }
1165
1166 void wxFileDialog::GetFilenames(wxArrayString& files) const
1167 {
1168 files.Empty();
1169 if (m_list->GetSelectedItemCount() == 0)
1170 {
1171 files.Add( GetFilename() );
1172 return;
1173 }
1174 files.Alloc( m_list->GetSelectedItemCount() );
1175
1176 wxListItem item;
1177 item.m_mask = wxLIST_MASK_TEXT;
1178
1179 item.m_itemId = m_list->GetNextItem( -1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );
1180 while ( item.m_itemId != -1 )
1181 {
1182 m_list->GetItem( item );
1183 files.Add( item.m_text );
1184 item.m_itemId = m_list->GetNextItem( item.m_itemId,
1185 wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );
1186 }
1187 }
1188
1189
1190
1191 // ----------------------------------------------------------------------------
1192 // global functions
1193 // ----------------------------------------------------------------------------
1194
1195 wxString
1196 wxFileSelectorEx(const wxChar *message,
1197 const wxChar *default_path,
1198 const wxChar *default_filename,
1199 int *WXUNUSED(indexDefaultExtension),
1200 const wxChar *wildcard,
1201 int flags,
1202 wxWindow *parent,
1203 int x, int y)
1204 {
1205 // TODO: implement this somehow
1206 return wxFileSelector(message, default_path, default_filename, wxT(""),
1207 wildcard, flags, parent, x, y);
1208 }
1209
1210 wxString wxFileSelector( const wxChar *title,
1211 const wxChar *defaultDir, const wxChar *defaultFileName,
1212 const wxChar *defaultExtension, const wxChar *filter, int flags,
1213 wxWindow *parent, int x, int y )
1214 {
1215 wxString filter2;
1216 if ( defaultExtension && !filter )
1217 filter2 = wxString(wxT("*.")) + wxString(defaultExtension) ;
1218 else if ( filter )
1219 filter2 = filter;
1220
1221 wxString defaultDirString;
1222 if (defaultDir)
1223 defaultDirString = defaultDir;
1224
1225 wxString defaultFilenameString;
1226 if (defaultFileName)
1227 defaultFilenameString = defaultFileName;
1228
1229 wxFileDialog fileDialog( parent, title, defaultDirString, defaultFilenameString, filter2, flags, wxPoint(x, y) );
1230
1231 if ( fileDialog.ShowModal() == wxID_OK )
1232 {
1233 return fileDialog.GetPath();
1234 }
1235 else
1236 {
1237 return wxEmptyString;
1238 }
1239 }
1240
1241 wxString wxLoadFileSelector( const wxChar *what, const wxChar *extension, const wxChar *default_name, wxWindow *parent )
1242 {
1243 wxChar *ext = (wxChar *)extension;
1244
1245 wxChar prompt[50];
1246 wxString str = _("Load %s file");
1247 wxSprintf(prompt, str, what);
1248
1249 if (*ext == wxT('.')) ext++;
1250 wxChar wild[60];
1251 wxSprintf(wild, wxT("*.%s"), ext);
1252
1253 return wxFileSelector (prompt, (const wxChar *) NULL, default_name, ext, wild, 0, parent);
1254 }
1255
1256 wxString wxSaveFileSelector(const wxChar *what, const wxChar *extension, const wxChar *default_name,
1257 wxWindow *parent )
1258 {
1259 wxChar *ext = (wxChar *)extension;
1260
1261 wxChar prompt[50];
1262 wxString str = _("Save %s file");
1263 wxSprintf(prompt, str, what);
1264
1265 if (*ext == wxT('.')) ext++;
1266 wxChar wild[60];
1267 wxSprintf(wild, wxT("*.%s"), ext);
1268
1269 return wxFileSelector (prompt, (const wxChar *) NULL, default_name, ext, wild, 0, parent);
1270 }
1271
1272
1273
1274
1275
1276
1277 // A module to allow icons table cleanup
1278
1279 class wxFileDialogGenericModule: public wxModule
1280 {
1281 DECLARE_DYNAMIC_CLASS(wxFileDialogGenericModule)
1282 public:
1283 wxFileDialogGenericModule() {}
1284 bool OnInit() { return TRUE; }
1285 void OnExit() { if (g_IconsTable) {delete g_IconsTable; g_IconsTable = NULL;} }
1286 };
1287
1288 IMPLEMENT_DYNAMIC_CLASS(wxFileDialogGenericModule, wxModule)