]> git.saurik.com Git - wxWidgets.git/blob - src/generic/dirctrlg.cpp
Font work.
[wxWidgets.git] / src / generic / dirctrlg.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: dirctrlg.cpp
3 // Purpose: wxGenericDirCtrl
4 // Author: Harm van der Heijden, Robert Roebling, Julian Smart
5 // Modified by:
6 // Created: 12/12/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Harm van der Heijden, Robert Roebling and Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifdef __GNUG__
13 #pragma implementation "dirctrlg.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 #if wxUSE_DIRDLG
24
25 #include "wx/utils.h"
26 #include "wx/dialog.h"
27 #include "wx/button.h"
28 #include "wx/layout.h"
29 #include "wx/msgdlg.h"
30 #include "wx/textctrl.h"
31 #include "wx/textdlg.h"
32 #include "wx/filefn.h"
33 #include "wx/cmndata.h"
34 #include "wx/gdicmn.h"
35 #include "wx/intl.h"
36 #include "wx/imaglist.h"
37 #include "wx/icon.h"
38 #include "wx/log.h"
39 #include "wx/sizer.h"
40 #include "wx/tokenzr.h"
41 #include "wx/dir.h"
42 #include "wx/settings.h"
43
44 #if wxUSE_STATLINE
45 #include "wx/statline.h"
46 #endif
47
48 #include "wx/generic/dirctrlg.h"
49
50 #if defined(__WXMAC__)
51 #include "wx/mac/private.h" // includes mac headers
52 #endif
53
54 #ifdef __WXMSW__
55 #include <windows.h>
56
57 // FIXME - Mingw32 1.0 has both _getdrive() and _chdrive(). For now, let's assume
58 // older releases don't, but it should be verified and the checks modified
59 // accordingly.
60 #if !defined(__GNUWIN32__) || (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
61 #include <direct.h>
62 #include <stdlib.h>
63 #include <ctype.h>
64 #endif
65
66 #endif
67
68 #ifdef __WXPM__
69
70 #define INCL_BASE
71 #include <os2.h>
72 #ifndef __EMX__
73 #include <direct.h>
74 #endif
75 #include <stdlib.h>
76 #include <ctype.h>
77
78 #endif // __WXPM__
79
80 #if defined(__WXMAC__)
81 # ifdef __DARWIN__
82 # include "MoreFilesX.h"
83 # else
84 # include "MoreFilesExtras.h"
85 # endif
86 #endif
87
88 #ifdef __BORLANDC__
89 #include "dos.h"
90 #endif
91
92 // If compiled under Windows, this macro can cause problems
93 #ifdef GetFirstChild
94 #undef GetFirstChild
95 #endif
96
97 /* Closed folder */
98 static const char * icon1_xpm[] = {
99 /* width height ncolors chars_per_pixel */
100 "16 16 6 1",
101 /* colors */
102 " s None c None",
103 ". c #000000",
104 "+ c #c0c0c0",
105 "@ c #808080",
106 "# c #ffff00",
107 "$ c #ffffff",
108 /* pixels */
109 " ",
110 " @@@@@ ",
111 " @#+#+#@ ",
112 " @#+#+#+#@@@@@@ ",
113 " @$$$$$$$$$$$$@.",
114 " @$#+#+#+#+#+#@.",
115 " @$+#+#+#+#+#+@.",
116 " @$#+#+#+#+#+#@.",
117 " @$+#+#+#+#+#+@.",
118 " @$#+#+#+#+#+#@.",
119 " @$+#+#+#+#+#+@.",
120 " @$#+#+#+#+#+#@.",
121 " @@@@@@@@@@@@@@.",
122 " ..............",
123 " ",
124 " "};
125
126 /* Open folder */
127 static const char * icon2_xpm[] = {
128 /* width height ncolors chars_per_pixel */
129 "16 16 6 1",
130 /* colors */
131 " s None c None",
132 ". c #000000",
133 "+ c #c0c0c0",
134 "@ c #808080",
135 "# c #ffff00",
136 "$ c #ffffff",
137 /* pixels */
138 " ",
139 " @@@@@ ",
140 " @$$$$$@ ",
141 " @$#+#+#$@@@@@@ ",
142 " @$+#+#+$$$$$$@.",
143 " @$#+#+#+#+#+#@.",
144 "@@@@@@@@@@@@@#@.",
145 "@$$$$$$$$$$@@+@.",
146 "@$#+#+#+#+##.@@.",
147 " @$#+#+#+#+#+.@.",
148 " @$+#+#+#+#+#.@.",
149 " @$+#+#+#+##@..",
150 " @@@@@@@@@@@@@.",
151 " .............",
152 " ",
153 " "};
154
155 /* File */
156 static const char * icon3_xpm[] = {
157 /* width height ncolors chars_per_pixel */
158 "16 16 3 1",
159 /* colors */
160 " s None c None",
161 ". c #000000",
162 "+ c #ffffff",
163 /* pixels */
164 " ",
165 " ........ ",
166 " .++++++.. ",
167 " .+.+.++.+. ",
168 " .++++++.... ",
169 " .+.+.+++++. ",
170 " .+++++++++. ",
171 " .+.+.+.+.+. ",
172 " .+++++++++. ",
173 " .+.+.+.+.+. ",
174 " .+++++++++. ",
175 " .+.+.+.+.+. ",
176 " .+++++++++. ",
177 " ........... ",
178 " ",
179 " "};
180
181 /* Computer */
182 static const char * icon4_xpm[] = {
183 "16 16 7 1",
184 " s None c None",
185 ". c #808080",
186 "X c #c0c0c0",
187 "o c Black",
188 "O c Gray100",
189 "+ c #008080",
190 "@ c Blue",
191 " ........... ",
192 " .XXXXXXXXXX.o",
193 " .OOOOOOOOO..o",
194 " .OoooooooX..o",
195 " .Oo+...@+X..o",
196 " .Oo+XXX.+X..o",
197 " .Oo+....+X..o",
198 " .Oo++++++X..o",
199 " .OXXXXXXXX.oo",
200 " ..........o.o",
201 " ...........Xo",
202 " .XXXXXXXXXX.o",
203 " .o.o.o.o.o...o",
204 " .oXoXoXoXoXo.o ",
205 ".XOXXXXXXXXX.o ",
206 "............o "};
207
208 /* Drive */
209 static const char * icon5_xpm[] = {
210 "16 16 7 1",
211 " s None c None",
212 ". c #808080",
213 "X c #c0c0c0",
214 "o c Black",
215 "O c Gray100",
216 "+ c Green",
217 "@ c #008000",
218 " ",
219 " ",
220 " ",
221 " ",
222 " ............. ",
223 " .XXXXXXXXXXXX.o",
224 ".OOOOOOOOOOOO..o",
225 ".XXXXXXXXX+@X..o",
226 ".XXXXXXXXXXXX..o",
227 ".X..........X..o",
228 ".XOOOOOOOOOOX..o",
229 "..............o ",
230 " ooooooooooooo ",
231 " ",
232 " ",
233 " "};
234
235 /* CD-ROM */
236 static const char *icon6_xpm[] = {
237 "16 16 10 1",
238 " s None c None",
239 ". c #808080",
240 "X c #c0c0c0",
241 "o c Yellow",
242 "O c Blue",
243 "+ c Black",
244 "@ c Gray100",
245 "# c #008080",
246 "$ c Green",
247 "% c #008000",
248 " ... ",
249 " ..XoX.. ",
250 " .O.XoXXX+ ",
251 " ...O.oXXXX+ ",
252 " .O..X.XXXX+ ",
253 " ....X.+..XXX+",
254 " .XXX.+@+.XXX+",
255 " .X@XX.+.X@@X+",
256 " .....X...#XX@+ ",
257 ".@@@...XXo.O@X+ ",
258 ".@XXX..XXoXOO+ ",
259 ".@++++..XoX+++ ",
260 ".@$%@@XX+++X.+ ",
261 ".............+ ",
262 " ++++++++++++ ",
263 " "};
264
265 /* Floppy */
266 static const char * icon7_xpm[] = {
267 "16 16 7 1",
268 " s None c None",
269 ". c #808080",
270 "X c Gray100",
271 "o c #c0c0c0",
272 "O c Black",
273 "+ c Cyan",
274 "@ c Red",
275 " ......X",
276 " .ooooooO",
277 " .+++++OO",
278 " .++++++O",
279 " .++++++O",
280 " .ooooooO",
281 " .......o....oO",
282 " .oooooo.o.O.XoO",
283 ".XXXXXXXXOOOOOO ",
284 ".ooooooooo@o..O ",
285 ".ooo....oooo..O ",
286 ".o..OOOO...o..O ",
287 ".oooXXXXoooo..O ",
288 ".............O ",
289 " OOOOOOOOOOOO ",
290 " "};
291
292 /* Removeable */
293 static const char * icon8_xpm[] = {
294 "16 16 7 1",
295 " s None c None",
296 ". c #808080",
297 "X c #c0c0c0",
298 "o c Black",
299 "O c Gray100",
300 "+ c Red",
301 "@ c #800000",
302 " ",
303 " ",
304 " ",
305 " ............. ",
306 " .XXXXXXXXXXXX.o",
307 ".OOOOOOOOOOOO..o",
308 ".OXXXXXXXXXXX..o",
309 ".O+@.oooooo.X..o",
310 ".OXXOooooooOX..o",
311 ".OXXXOOOOOOXX..o",
312 ".OXXXXXXXXXXX..o",
313 ".O............o ",
314 " ooooooooooooo ",
315 " ",
316 " ",
317 " "};
318
319
320 #if defined(__DOS__)
321
322 bool wxIsDriveAvailable(const wxString& dirName)
323 {
324 // FIXME_MGL - this method leads to hang up under Watcom for some reason
325 #ifndef __WATCOMC__
326 if ( dirName.Len() == 3 && dirName[1u] == wxT(':') )
327 {
328 wxString dirNameLower(dirName.Lower());
329 // VS: always return TRUE for removable media, since Win95 doesn't
330 // like it when MS-DOS app accesses empty floppy drive
331 return (dirNameLower[0u] == wxT('a') ||
332 dirNameLower[0u] == wxT('b') ||
333 wxPathExists(dirNameLower));
334 }
335 else
336 #endif
337 return TRUE;
338 }
339
340 #elif defined(__WINDOWS__) || defined(__WXPM__)
341
342 int setdrive(int drive)
343 {
344 #if defined(__GNUWIN32__) && \
345 (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
346 return _chdrive(drive);
347 #else
348 wxChar newdrive[3];
349
350 if (drive < 1 || drive > 31)
351 return -1;
352 newdrive[0] = (wxChar)(wxT('A') + drive - 1);
353 newdrive[1] = wxT(':');
354 newdrive[2] = wxT('\0');
355 #if defined(__WXMSW__)
356 #ifdef __WIN16__
357 if (wxSetWorkingDirectory(newdrive))
358 #else
359 if (::SetCurrentDirectory(newdrive))
360 #endif
361 #else
362 // VA doesn't know what LPSTR is and has its own set
363 if (DosSetCurrentDir((PSZ)newdrive))
364 #endif
365 return 0;
366 else
367 return -1;
368 #endif // !GNUWIN32
369 }
370
371 bool wxIsDriveAvailable(const wxString& dirName)
372 {
373 #ifdef __WIN32__
374 UINT errorMode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
375 #endif
376 bool success = TRUE;
377
378 // Check if this is a root directory and if so,
379 // whether the drive is available.
380 if (dirName.Len() == 3 && dirName[(size_t)1] == wxT(':'))
381 {
382 wxString dirNameLower(dirName.Lower());
383 #if defined(__GNUWIN32__) && !(defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
384 success = wxPathExists(dirNameLower);
385 #else
386 int currentDrive = _getdrive();
387 int thisDrive = (int) (dirNameLower[(size_t)0] - 'a' + 1) ;
388 int err = setdrive( thisDrive ) ;
389 setdrive( currentDrive );
390
391 if (err == -1)
392 {
393 success = FALSE;
394 }
395 #endif
396 }
397 #ifdef __WIN32__
398 (void) SetErrorMode(errorMode);
399 #endif
400
401 return success;
402 }
403 #endif // __WINDOWS__ || __WXPM__
404
405 // Function which is called by quick sort. We want to override the default wxArrayString behaviour,
406 // and sort regardless of case.
407 static int LINKAGEMODE wxDirCtrlStringCompareFunction(const void *first, const void *second)
408 {
409 wxString *strFirst = (wxString *)first;
410 wxString *strSecond = (wxString *)second;
411
412 return strFirst->CmpNoCase(*strSecond);
413 }
414
415 //-----------------------------------------------------------------------------
416 // wxDirItemData
417 //-----------------------------------------------------------------------------
418
419 wxDirItemData::wxDirItemData(const wxString& path, const wxString& name,
420 bool isDir)
421 {
422 m_path = path;
423 m_name = name;
424 /* Insert logic to detect hidden files here
425 * In UnixLand we just check whether the first char is a dot
426 * For FileNameFromPath read LastDirNameInThisPath ;-) */
427 // m_isHidden = (bool)(wxFileNameFromPath(*m_path)[0] == '.');
428 m_isHidden = FALSE;
429 m_isExpanded = FALSE;
430 m_isDir = isDir;
431 }
432
433 wxDirItemData::~wxDirItemData()
434 {
435 }
436
437 void wxDirItemData::SetNewDirName(const wxString& path)
438 {
439 m_path = path;
440 m_name = wxFileNameFromPath(path);
441 }
442
443 bool wxDirItemData::HasSubDirs() const
444 {
445 if (m_path.IsEmpty())
446 return FALSE;
447
448 wxDir dir;
449 {
450 wxLogNull nolog;
451 if ( !dir.Open(m_path) )
452 return FALSE;
453 }
454
455 return dir.HasSubDirs();
456 }
457
458 bool wxDirItemData::HasFiles(const wxString& WXUNUSED(spec)) const
459 {
460 if (m_path.IsEmpty())
461 return FALSE;
462
463 wxDir dir;
464 {
465 wxLogNull nolog;
466 if ( !dir.Open(m_path) )
467 return FALSE;
468 }
469
470 return dir.HasFiles();
471 }
472
473 //-----------------------------------------------------------------------------
474 // wxGenericDirCtrl
475 //-----------------------------------------------------------------------------
476
477 IMPLEMENT_DYNAMIC_CLASS(wxGenericDirCtrl, wxControl)
478
479 BEGIN_EVENT_TABLE(wxGenericDirCtrl, wxControl)
480 EVT_TREE_ITEM_EXPANDING (-1, wxGenericDirCtrl::OnExpandItem)
481 EVT_TREE_ITEM_COLLAPSED (-1, wxGenericDirCtrl::OnCollapseItem)
482 EVT_TREE_BEGIN_LABEL_EDIT (-1, wxGenericDirCtrl::OnBeginEditItem)
483 EVT_TREE_END_LABEL_EDIT (-1, wxGenericDirCtrl::OnEndEditItem)
484 EVT_SIZE (wxGenericDirCtrl::OnSize)
485 END_EVENT_TABLE()
486
487 wxGenericDirCtrl::wxGenericDirCtrl(void)
488 {
489 Init();
490 }
491
492 bool wxGenericDirCtrl::Create(wxWindow *parent,
493 const wxWindowID id,
494 const wxString& dir,
495 const wxPoint& pos,
496 const wxSize& size,
497 long style,
498 const wxString& filter,
499 int defaultFilter,
500 const wxString& name)
501 {
502 if (!wxControl::Create(parent, id, pos, size, style, wxDefaultValidator, name))
503 return FALSE;
504
505 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE));
506
507 Init();
508
509 long treeStyle = wxTR_HAS_BUTTONS | wxTR_HIDE_ROOT;
510
511 if (style & wxDIRCTRL_EDIT_LABELS)
512 treeStyle |= wxTR_EDIT_LABELS;
513
514 if ((style & wxDIRCTRL_3D_INTERNAL) == 0)
515 treeStyle |= wxNO_BORDER;
516
517 long filterStyle = 0;
518 if ((style & wxDIRCTRL_3D_INTERNAL) == 0)
519 filterStyle |= wxNO_BORDER;
520
521 m_treeCtrl = new wxTreeCtrl(this, wxID_TREECTRL, pos, size, treeStyle);
522
523 if (!filter.IsEmpty() && (style & wxDIRCTRL_SHOW_FILTERS))
524 m_filterListCtrl = new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL, wxDefaultPosition, wxDefaultSize, filterStyle);
525
526 m_defaultPath = dir;
527 m_filter = filter;
528
529 SetFilterIndex(defaultFilter);
530
531 if (m_filterListCtrl)
532 m_filterListCtrl->FillFilterList(filter, defaultFilter);
533
534 m_imageList = new wxImageList(16, 16, TRUE);
535 m_imageList->Add(wxIcon(icon1_xpm));
536 m_imageList->Add(wxIcon(icon2_xpm));
537 m_imageList->Add(wxIcon(icon3_xpm));
538 m_imageList->Add(wxIcon(icon4_xpm));
539 m_imageList->Add(wxIcon(icon5_xpm));
540 m_imageList->Add(wxIcon(icon6_xpm));
541 m_imageList->Add(wxIcon(icon7_xpm));
542 m_imageList->Add(wxIcon(icon8_xpm));
543 m_treeCtrl->AssignImageList(m_imageList);
544
545 m_showHidden = FALSE;
546 wxDirItemData* rootData = new wxDirItemData(wxT(""), wxT(""), TRUE);
547
548 wxString rootName;
549
550 #if defined(__WINDOWS__) || defined(__WXPM__) || defined(__DOS__)
551 rootName = _("Computer");
552 #else
553 rootName = _("Sections");
554 #endif
555
556 m_rootId = m_treeCtrl->AddRoot( rootName, 3, -1, rootData);
557 m_treeCtrl->SetItemHasChildren(m_rootId);
558 ExpandDir(m_rootId); // automatically expand first level
559
560 // Expand and select the default path
561 if (!m_defaultPath.IsEmpty())
562 ExpandPath(m_defaultPath);
563
564 DoResize();
565
566 return TRUE;
567 }
568
569 wxGenericDirCtrl::~wxGenericDirCtrl()
570 {
571 }
572
573 void wxGenericDirCtrl::Init()
574 {
575 m_showHidden = FALSE;
576 m_imageList = NULL;
577 m_currentFilter = 0;
578 m_currentFilterStr = wxEmptyString; // Default: any file
579 m_treeCtrl = NULL;
580 m_filterListCtrl = NULL;
581 }
582
583 void wxGenericDirCtrl::ShowHidden( bool show )
584 {
585 m_showHidden = show;
586
587 wxString path = GetPath();
588 ReCreateTree();
589 SetPath(path);
590 }
591
592 void wxGenericDirCtrl::AddSection(const wxString& path, const wxString& name, int imageId)
593 {
594 wxDirItemData *dir_item = new wxDirItemData(path,name,TRUE);
595
596 wxTreeItemId id = m_treeCtrl->AppendItem( m_rootId, name, imageId, -1, dir_item);
597
598 m_treeCtrl->SetItemHasChildren(id);
599 }
600
601 void wxGenericDirCtrl::SetupSections()
602 {
603 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
604
605 #ifdef __WIN32__
606 wxChar driveBuffer[256];
607 size_t n = (size_t) GetLogicalDriveStrings(255, driveBuffer);
608 size_t i = 0;
609 while (i < n)
610 {
611 wxString path, name;
612 path.Printf(wxT("%c:\\"), driveBuffer[i]);
613 name.Printf(wxT("(%c:)"), driveBuffer[i]);
614
615 int imageId = 4;
616 int driveType = ::GetDriveType(path);
617 switch (driveType)
618 {
619 case DRIVE_REMOVABLE:
620 if (path == wxT("a:\\") || path == wxT("b:\\"))
621 imageId = 6; // Floppy
622 else
623 imageId = 7;
624 break;
625 case DRIVE_FIXED:
626 imageId = 4;
627 break;
628 case DRIVE_REMOTE:
629 imageId = 4;
630 break;
631 case DRIVE_CDROM:
632 imageId = 5;
633 break;
634 default:
635 imageId = 4;
636 break;
637 }
638
639 AddSection(path, name, imageId);
640
641 while (driveBuffer[i] != wxT('\0'))
642 i ++;
643 i ++;
644 if (driveBuffer[i] == wxT('\0'))
645 break;
646 }
647 #else // !__WIN32__
648 int drive;
649
650 /* If we can switch to the drive, it exists. */
651 for( drive = 1; drive <= 26; drive++ )
652 {
653 wxString path, name;
654 path.Printf(wxT("%c:\\"), (char) (drive + 'a' - 1));
655 name.Printf(wxT("(%c:)"), (char) (drive + 'A' - 1));
656
657 if (wxIsDriveAvailable(path))
658 {
659 AddSection(path, name, (drive <= 2) ? 6/*floppy*/ : 4/*disk*/);
660 }
661 }
662 #endif // __WIN32__/!__WIN32__
663
664 #elif defined(__WXMAC__)
665 # ifdef __DARWIN__
666 FSRef **theVolRefs;
667 ItemCount theVolCount;
668 char thePath[FILENAME_MAX];
669
670 if (FSGetMountedVolumes(&theVolRefs, &theVolCount) == noErr) {
671 ItemCount index;
672 ::HLock( (Handle)theVolRefs ) ;
673 for (index = 0; index < theVolCount; ++index) {
674 // get the POSIX path associated with the FSRef
675 if ( FSRefMakePath(&((*theVolRefs)[index]),
676 (UInt8 *)thePath, sizeof(thePath)) != noErr ) {
677 continue;
678 }
679 // add path separator at end if necessary
680 wxString path( thePath ) ;
681 if (path.Last() != wxFILE_SEP_PATH) {
682 path += wxFILE_SEP_PATH;
683 }
684 // get Mac volume name for display
685 FSVolumeRefNum vRefNum ;
686 HFSUniStr255 volumeName ;
687
688 if ( FSGetVRefNum(&((*theVolRefs)[index]), &vRefNum) != noErr ) {
689 continue;
690 }
691 if ( FSGetVInfo(vRefNum, &volumeName, NULL, NULL) != noErr ) {
692 continue;
693 }
694 // get C string from Unicode HFS name
695 // see: http://developer.apple.com/carbon/tipsandtricks.html
696 CFStringRef cfstr = CFStringCreateWithCharacters( kCFAllocatorDefault,
697 volumeName.unicode,
698 volumeName.length );
699 // Do something with str
700 char *cstr = NewPtr(CFStringGetLength(cfstr) + 1);
701 if (( cstr == NULL ) ||
702 !CFStringGetCString(cfstr, cstr, CFStringGetLength(cfstr) + 1,
703 kCFStringEncodingMacRoman)) {
704 CFRelease( cstr );
705 continue;
706 }
707 wxString name( cstr ) ;
708 DisposePtr( cstr ) ;
709 CFRelease( cfstr );
710
711 GetVolParmsInfoBuffer volParmsInfo;
712 UInt32 actualSize;
713 if ( FSGetVolParms(vRefNum, sizeof(volParmsInfo), &volParmsInfo, &actualSize) != noErr ) {
714 continue;
715 }
716
717 if ( VolIsEjectable(&volParmsInfo) ) {
718 AddSection(path, name, 5/*cd-rom*/);
719 }
720 else {
721 AddSection(path, name, 4/*disk*/);
722 }
723 }
724 ::HUnlock( (Handle)theVolRefs ) ;
725 ::DisposeHandle( (Handle)theVolRefs ) ;
726 }
727 # else
728 FSSpec volume ;
729 short index = 1 ;
730 while(1) {
731 short actualCount = 0 ;
732 if ( OnLine( &volume , 1 , &actualCount , &index ) != noErr || actualCount == 0 ) {
733 break ;
734 }
735
736 wxString name = wxMacFSSpec2MacFilename( &volume ) ;
737 AddSection(name + wxFILE_SEP_PATH, name, 4/*disk*/);
738 }
739 # endif /* __DARWIN__ */
740 #elif defined(__UNIX__)
741 AddSection(wxT("/"), wxT("/"), 3/*computer icon*/);
742 #else
743 #error "Unsupported platform in wxGenericDirCtrl!"
744 #endif
745 }
746
747 void wxGenericDirCtrl::OnBeginEditItem(wxTreeEvent &event)
748 {
749 // don't rename the main entry "Sections"
750 if (event.GetItem() == m_rootId)
751 {
752 event.Veto();
753 return;
754 }
755
756 // don't rename the individual sections
757 if (m_treeCtrl->GetItemParent( event.GetItem() ) == m_rootId)
758 {
759 event.Veto();
760 return;
761 }
762 }
763
764 void wxGenericDirCtrl::OnEndEditItem(wxTreeEvent &event)
765 {
766 if ((event.GetLabel().IsEmpty()) ||
767 (event.GetLabel() == _(".")) ||
768 (event.GetLabel() == _("..")) ||
769 (event.GetLabel().First( wxT("/") ) != wxNOT_FOUND))
770 {
771 wxMessageDialog dialog(this, _("Illegal directory name."), _("Error"), wxOK | wxICON_ERROR );
772 dialog.ShowModal();
773 event.Veto();
774 return;
775 }
776
777 wxTreeItemId id = event.GetItem();
778 wxDirItemData *data = (wxDirItemData*)m_treeCtrl->GetItemData( id );
779 wxASSERT( data );
780
781 wxString new_name( wxPathOnly( data->m_path ) );
782 new_name += wxString(wxFILE_SEP_PATH);
783 new_name += event.GetLabel();
784
785 wxLogNull log;
786
787 if (wxFileExists(new_name))
788 {
789 wxMessageDialog dialog(this, _("File name exists already."), _("Error"), wxOK | wxICON_ERROR );
790 dialog.ShowModal();
791 event.Veto();
792 }
793
794 if (wxRenameFile(data->m_path,new_name))
795 {
796 data->SetNewDirName( new_name );
797 }
798 else
799 {
800 wxMessageDialog dialog(this, _("Operation not permitted."), _("Error"), wxOK | wxICON_ERROR );
801 dialog.ShowModal();
802 event.Veto();
803 }
804 }
805
806 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent &event)
807 {
808 wxTreeItemId parentId = event.GetItem();
809
810 // VS: this is needed because the event handler is called from wxTreeCtrl
811 // ctor when wxTR_HIDE_ROOT was specified
812 if (m_rootId == 0)
813 m_rootId = m_treeCtrl->GetRootItem();
814
815 ExpandDir(parentId);
816 }
817
818 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent &event )
819 {
820 CollapseDir(event.GetItem());
821 }
822
823 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId)
824 {
825 wxTreeItemId child;
826
827 wxDirItemData *data = (wxDirItemData *) m_treeCtrl->GetItemData(parentId);
828 if (!data->m_isExpanded)
829 return;
830
831 data->m_isExpanded = FALSE;
832 long cookie;
833 /* Workaround because DeleteChildren has disapeared (why?) and
834 * CollapseAndReset doesn't work as advertised (deletes parent too) */
835 child = m_treeCtrl->GetFirstChild(parentId, cookie);
836 while (child.IsOk())
837 {
838 m_treeCtrl->Delete(child);
839 /* Not GetNextChild below, because the cookie mechanism can't
840 * handle disappearing children! */
841 child = m_treeCtrl->GetFirstChild(parentId, cookie);
842 }
843 }
844
845 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId)
846 {
847 wxDirItemData *data = (wxDirItemData *) m_treeCtrl->GetItemData(parentId);
848
849 if (data->m_isExpanded)
850 return;
851
852 data->m_isExpanded = TRUE;
853
854 if (parentId == m_treeCtrl->GetRootItem())
855 {
856 SetupSections();
857 return;
858 }
859
860 wxASSERT(data);
861
862 wxString search,path,filename;
863
864 wxString dirName(data->m_path);
865
866 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
867 // Check if this is a root directory and if so,
868 // whether the drive is avaiable.
869 if (!wxIsDriveAvailable(dirName))
870 {
871 data->m_isExpanded = FALSE;
872 //wxMessageBox(wxT("Sorry, this drive is not available."));
873 return;
874 }
875 #endif
876
877 // This may take a longish time. Go to busy cursor
878 wxBusyCursor busy;
879
880 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
881 if (dirName.Last() == ':')
882 dirName += wxString(wxFILE_SEP_PATH);
883 #endif
884
885 wxArrayString dirs;
886 wxArrayString filenames;
887
888 wxDir d;
889 wxString eachFilename;
890
891 wxLogNull log;
892 d.Open(dirName);
893
894 if (d.IsOpened())
895 {
896 int style = wxDIR_DIRS;
897 if (m_showHidden) style |= wxDIR_HIDDEN;
898 if (d.GetFirst(& eachFilename, wxEmptyString, style))
899 {
900 do
901 {
902 if ((eachFilename != wxT(".")) && (eachFilename != wxT("..")))
903 {
904 dirs.Add(eachFilename);
905 }
906 }
907 while (d.GetNext(& eachFilename));
908 }
909 }
910 dirs.Sort((wxArrayString::CompareFunction) wxDirCtrlStringCompareFunction);
911
912 // Now do the filenames -- but only if we're allowed to
913 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY) == 0)
914 {
915 wxLogNull log;
916
917 d.Open(dirName);
918
919 if (d.IsOpened())
920 {
921 if (d.GetFirst(& eachFilename, m_currentFilterStr, wxDIR_FILES))
922 {
923 do
924 {
925 if ((eachFilename != wxT(".")) && (eachFilename != wxT("..")))
926 {
927 filenames.Add(eachFilename);
928 }
929 }
930 while (d.GetNext(& eachFilename));
931 }
932 }
933 filenames.Sort((wxArrayString::CompareFunction) wxDirCtrlStringCompareFunction);
934 }
935
936 // Add the sorted dirs
937 size_t i;
938 for (i = 0; i < dirs.Count(); i++)
939 {
940 wxString eachFilename(dirs[i]);
941 path = dirName;
942 if (path.Last() != wxFILE_SEP_PATH)
943 path += wxString(wxFILE_SEP_PATH);
944 path += eachFilename;
945
946 wxDirItemData *dir_item = new wxDirItemData(path,eachFilename,TRUE);
947 wxTreeItemId id = m_treeCtrl->AppendItem( parentId, eachFilename, 0, -1, dir_item);
948 m_treeCtrl->SetItemImage( id, 1, wxTreeItemIcon_Expanded );
949
950 // Has this got any children? If so, make it expandable.
951 // (There are two situations when a dir has children: either it
952 // has subdirectories or it contains files that weren't filtered
953 // out. The latter only applies to dirctrl with files.)
954 if ( dir_item->HasSubDirs() ||
955 (((GetWindowStyle() & wxDIRCTRL_DIR_ONLY) == 0) &&
956 dir_item->HasFiles(m_currentFilterStr)) )
957 {
958 m_treeCtrl->SetItemHasChildren(id);
959 }
960 }
961
962 // Add the sorted filenames
963 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY) == 0)
964 {
965 for (i = 0; i < filenames.Count(); i++)
966 {
967 wxString eachFilename(filenames[i]);
968 path = dirName;
969 if (path.Last() != wxFILE_SEP_PATH)
970 path += wxString(wxFILE_SEP_PATH);
971 path += eachFilename;
972 //path = dirName + wxString(wxT("/")) + eachFilename;
973 wxDirItemData *dir_item = new wxDirItemData(path,eachFilename,FALSE);
974 (void)m_treeCtrl->AppendItem( parentId, eachFilename, 2, -1, dir_item);
975 }
976 }
977 }
978
979 void wxGenericDirCtrl::ReCreateTree()
980 {
981 CollapseDir(m_treeCtrl->GetRootItem());
982 ExpandDir(m_treeCtrl->GetRootItem());
983 }
984
985 // Find the child that matches the first part of 'path'.
986 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
987 // then the child for /usr is returned.
988 wxTreeItemId wxGenericDirCtrl::FindChild(wxTreeItemId parentId, const wxString& path, bool& done)
989 {
990 wxString path2(path);
991
992 // Make sure all separators are as per the current platform
993 path2.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH));
994 path2.Replace(wxT("/"), wxString(wxFILE_SEP_PATH));
995
996 // Append a separator to foil bogus substring matching
997 path2 += wxString(wxFILE_SEP_PATH);
998
999 // In MSW or PM, case is not significant
1000 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
1001 path2.MakeLower();
1002 #endif
1003
1004 long cookie;
1005 wxTreeItemId childId = m_treeCtrl->GetFirstChild(parentId, cookie);
1006 while (childId.IsOk())
1007 {
1008 wxDirItemData* data = (wxDirItemData*) m_treeCtrl->GetItemData(childId);
1009
1010 if (data && !data->m_path.IsEmpty())
1011 {
1012 wxString childPath(data->m_path);
1013 if (childPath.Last() != wxFILE_SEP_PATH)
1014 childPath += wxString(wxFILE_SEP_PATH);
1015
1016 // In MSW and PM, case is not significant
1017 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__WXPM__)
1018 childPath.MakeLower();
1019 #endif
1020
1021 if (childPath.Len() <= path2.Len())
1022 {
1023 wxString path3 = path2.Mid(0, childPath.Len());
1024 if (childPath == path3)
1025 {
1026 if (path3.Len() == path2.Len())
1027 done = TRUE;
1028 else
1029 done = FALSE;
1030 return childId;
1031 }
1032 }
1033 }
1034
1035 childId = m_treeCtrl->GetNextChild(parentId, cookie);
1036 }
1037 wxTreeItemId invalid;
1038 return invalid;
1039 }
1040
1041 // Try to expand as much of the given path as possible,
1042 // and select the given tree item.
1043 bool wxGenericDirCtrl::ExpandPath(const wxString& path)
1044 {
1045 bool done = FALSE;
1046 wxTreeItemId id = FindChild(m_rootId, path, done);
1047 wxTreeItemId lastId = id; // The last non-zero id
1048 while (id.IsOk() && !done)
1049 {
1050 ExpandDir(id);
1051
1052 id = FindChild(id, path, done);
1053 if (id.IsOk())
1054 lastId = id;
1055 }
1056 if (lastId.IsOk())
1057 {
1058 wxDirItemData *data = (wxDirItemData *) m_treeCtrl->GetItemData(lastId);
1059 if (data->m_isDir)
1060 {
1061 m_treeCtrl->Expand(lastId);
1062 }
1063 if ((GetWindowStyle() & wxDIRCTRL_SELECT_FIRST) && data->m_isDir)
1064 {
1065 // Find the first file in this directory
1066 long cookie;
1067 wxTreeItemId childId = m_treeCtrl->GetFirstChild(lastId, cookie);
1068 bool selectedChild = FALSE;
1069 while (childId.IsOk())
1070 {
1071 wxDirItemData* data = (wxDirItemData*) m_treeCtrl->GetItemData(childId);
1072
1073 if (data && data->m_path != wxT("") && !data->m_isDir)
1074 {
1075 m_treeCtrl->SelectItem(childId);
1076 m_treeCtrl->EnsureVisible(childId);
1077 selectedChild = TRUE;
1078 break;
1079 }
1080 childId = m_treeCtrl->GetNextChild(lastId, cookie);
1081 }
1082 if (!selectedChild)
1083 {
1084 m_treeCtrl->SelectItem(lastId);
1085 m_treeCtrl->EnsureVisible(lastId);
1086 }
1087 }
1088 else
1089 {
1090 m_treeCtrl->SelectItem(lastId);
1091 m_treeCtrl->EnsureVisible(lastId);
1092 }
1093
1094 return TRUE;
1095 }
1096 else
1097 return FALSE;
1098 }
1099
1100 wxString wxGenericDirCtrl::GetPath() const
1101 {
1102 wxTreeItemId id = m_treeCtrl->GetSelection();
1103 if (id)
1104 {
1105 wxDirItemData* data = (wxDirItemData*) m_treeCtrl->GetItemData(id);
1106 return data->m_path;
1107 }
1108 else
1109 return wxEmptyString;
1110 }
1111
1112 wxString wxGenericDirCtrl::GetFilePath() const
1113 {
1114 wxTreeItemId id = m_treeCtrl->GetSelection();
1115 if (id)
1116 {
1117 wxDirItemData* data = (wxDirItemData*) m_treeCtrl->GetItemData(id);
1118 if (data->m_isDir)
1119 return wxEmptyString;
1120 else
1121 return data->m_path;
1122 }
1123 else
1124 return wxEmptyString;
1125 }
1126
1127 void wxGenericDirCtrl::SetPath(const wxString& path)
1128 {
1129 m_defaultPath = path;
1130 if (m_rootId)
1131 ExpandPath(path);
1132 }
1133
1134 // Not used
1135 #if 0
1136 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId id, int dirFlags, wxArrayString& filenames)
1137 {
1138 wxDirItemData *data = (wxDirItemData *) m_treeCtrl->GetItemData(id);
1139
1140 // This may take a longish time. Go to busy cursor
1141 wxBusyCursor busy;
1142
1143 wxASSERT(data);
1144
1145 wxString search,path,filename;
1146
1147 wxString dirName(data->m_path);
1148
1149 #if defined(__WXMSW__) || defined(__WXPM__)
1150 if (dirName.Last() == ':')
1151 dirName += wxString(wxFILE_SEP_PATH);
1152 #endif
1153
1154 wxDir d;
1155 wxString eachFilename;
1156
1157 wxLogNull log;
1158 d.Open(dirName);
1159
1160 if (d.IsOpened())
1161 {
1162 if (d.GetFirst(& eachFilename, m_currentFilterStr, dirFlags))
1163 {
1164 do
1165 {
1166 if ((eachFilename != wxT(".")) && (eachFilename != wxT("..")))
1167 {
1168 filenames.Add(eachFilename);
1169 }
1170 }
1171 while (d.GetNext(& eachFilename)) ;
1172 }
1173 }
1174 }
1175 #endif
1176
1177 void wxGenericDirCtrl::SetFilterIndex(int n)
1178 {
1179 m_currentFilter = n;
1180
1181 wxString f, d;
1182 if (ExtractWildcard(m_filter, n, f, d))
1183 m_currentFilterStr = f;
1184 else
1185 m_currentFilterStr = wxT("*.*");
1186 }
1187
1188 void wxGenericDirCtrl::SetFilter(const wxString& filter)
1189 {
1190 m_filter = filter;
1191
1192 wxString f, d;
1193 if (ExtractWildcard(m_filter, m_currentFilter, f, d))
1194 m_currentFilterStr = f;
1195 else
1196 m_currentFilterStr = wxT("*.*");
1197 }
1198
1199 // Extract description and actual filter from overall filter string
1200 bool wxGenericDirCtrl::ExtractWildcard(const wxString& filterStr, int n, wxString& filter, wxString& description)
1201 {
1202 wxArrayString filters, descriptions;
1203 int count = ParseFilter(filterStr, filters, descriptions);
1204 if (count > 0 && n < count)
1205 {
1206 filter = filters[n];
1207 description = descriptions[n];
1208 return TRUE;
1209 }
1210
1211 return FALSE;
1212 }
1213
1214 // Parses the global filter, returning the number of filters.
1215 // Returns 0 if none or if there's a problem.
1216 // filterStr is in the form:
1217 //
1218 // "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpg"
1219
1220 int wxGenericDirCtrl::ParseFilter(const wxString& filterStr, wxArrayString& filters, wxArrayString& descriptions)
1221 {
1222 wxString str(filterStr);
1223
1224 wxString description, filter;
1225 int pos;
1226 bool finished = FALSE;
1227 do
1228 {
1229 pos = str.Find(wxT('|'));
1230 if (pos == -1)
1231 return 0; // Problem
1232 description = str.Left(pos);
1233 str = str.Mid(pos+1);
1234 pos = str.Find(wxT('|'));
1235 if (pos == -1)
1236 {
1237 filter = str;
1238 finished = TRUE;
1239 }
1240 else
1241 {
1242 filter = str.Left(pos);
1243 str = str.Mid(pos+1);
1244 }
1245 descriptions.Add(description);
1246 filters.Add(filter);
1247 }
1248 while (!finished) ;
1249
1250 return filters.Count();
1251 }
1252
1253 void wxGenericDirCtrl::DoResize()
1254 {
1255 wxSize sz = GetClientSize();
1256 int verticalSpacing = 3;
1257 if (m_treeCtrl)
1258 {
1259 wxSize filterSz ;
1260 if (m_filterListCtrl)
1261 {
1262 #ifdef __WXMSW__
1263 // For some reason, this is required in order for the
1264 // correct control height to always be returned, rather
1265 // than the drop-down list height which is sometimes returned.
1266 wxSize oldSize = m_filterListCtrl->GetSize();
1267 m_filterListCtrl->SetSize(-1, -1, oldSize.x+10, -1, wxSIZE_USE_EXISTING);
1268 m_filterListCtrl->SetSize(-1, -1, oldSize.x, -1, wxSIZE_USE_EXISTING);
1269 #endif
1270 filterSz = m_filterListCtrl->GetSize();
1271 sz.y -= (filterSz.y + verticalSpacing);
1272 }
1273 m_treeCtrl->SetSize(0, 0, sz.x, sz.y);
1274 if (m_filterListCtrl)
1275 {
1276 m_filterListCtrl->SetSize(0, sz.y + verticalSpacing, sz.x, filterSz.y);
1277 // Don't know why, but this needs refreshing after a resize (wxMSW)
1278 m_filterListCtrl->Refresh();
1279 }
1280 }
1281 }
1282
1283
1284 void wxGenericDirCtrl::OnSize(wxSizeEvent& WXUNUSED(event))
1285 {
1286 DoResize();
1287 }
1288
1289 //-----------------------------------------------------------------------------
1290 // wxDirFilterListCtrl
1291 //-----------------------------------------------------------------------------
1292
1293 IMPLEMENT_CLASS(wxDirFilterListCtrl, wxChoice)
1294
1295 BEGIN_EVENT_TABLE(wxDirFilterListCtrl, wxChoice)
1296 EVT_CHOICE(-1, wxDirFilterListCtrl::OnSelFilter)
1297 END_EVENT_TABLE()
1298
1299 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl* parent, const wxWindowID id,
1300 const wxPoint& pos,
1301 const wxSize& size,
1302 long style)
1303 {
1304 m_dirCtrl = parent;
1305 return wxChoice::Create(parent, id, pos, size, 0, NULL, style);
1306 }
1307
1308 void wxDirFilterListCtrl::Init()
1309 {
1310 m_dirCtrl = NULL;
1311 }
1312
1313 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent& WXUNUSED(event))
1314 {
1315 int sel = GetSelection();
1316
1317 wxString currentPath = m_dirCtrl->GetPath();
1318
1319 m_dirCtrl->SetFilterIndex(sel);
1320
1321 // If the filter has changed, the view is out of date, so
1322 // collapse the tree.
1323 m_dirCtrl->ReCreateTree();
1324
1325 // Try to restore the selection, or at least the directory
1326 m_dirCtrl->ExpandPath(currentPath);
1327 }
1328
1329 void wxDirFilterListCtrl::FillFilterList(const wxString& filter, int defaultFilter)
1330 {
1331 Clear();
1332 wxArrayString descriptions, filters;
1333 size_t n = (size_t) m_dirCtrl->ParseFilter(filter, filters, descriptions);
1334
1335 if (n > 0 && defaultFilter < (int) n)
1336 {
1337 size_t i = 0;
1338 for (i = 0; i < n; i++)
1339 Append(descriptions[i]);
1340 SetSelection(defaultFilter);
1341 }
1342 }
1343
1344 #endif // wxUSE_DIRDLG