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