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