merged fix from the 2.2 branch but the test I changed seems to have disappeared ...
[wxWidgets.git] / src / generic / dirdlgg.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: dirdlg.cpp
3 // Purpose: wxDirDialog
4 // Author: Harm van der Heijden and Robert Roebling
5 // Modified by:
6 // Created: 12/12/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Harm van der Heijden and Robert Roebling
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifdef __GNUG__
13 #pragma implementation "dirdlgg.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 #if wxUSE_DIRDLG
26
27 #include "wx/utils.h"
28 #include "wx/dialog.h"
29 #include "wx/button.h"
30 #include "wx/layout.h"
31 #include "wx/msgdlg.h"
32 #include "wx/textdlg.h"
33 #include "wx/filefn.h"
34 #include "wx/cmndata.h"
35 #include "wx/gdicmn.h"
36 #include "wx/intl.h"
37 #include "wx/imaglist.h"
38 #include "wx/icon.h"
39 #include "wx/log.h"
40 #include "wx/sizer.h"
41 #include "wx/tokenzr.h"
42
43 #if wxUSE_STATLINE
44 #include "wx/statline.h"
45 #endif
46
47 #include "wx/generic/dirdlgg.h"
48
49 // If compiled under Windows, this macro can cause problems
50 #ifdef GetFirstChild
51 #undef GetFirstChild
52 #endif
53
54 #ifndef __WXMSW__
55 /* XPM */
56 static char * icon1_xpm[] = {
57 /* width height ncolors chars_per_pixel */
58 "16 16 6 1",
59 /* colors */
60 " s None c None",
61 ". c #000000",
62 "+ c #c0c0c0",
63 "@ c #808080",
64 "# c #ffff00",
65 "$ c #ffffff",
66 /* pixels */
67 " ",
68 " @@@@@ ",
69 " @#+#+#@ ",
70 " @#+#+#+#@@@@@@ ",
71 " @$$$$$$$$$$$$@.",
72 " @$#+#+#+#+#+#@.",
73 " @$+#+#+#+#+#+@.",
74 " @$#+#+#+#+#+#@.",
75 " @$+#+#+#+#+#+@.",
76 " @$#+#+#+#+#+#@.",
77 " @$+#+#+#+#+#+@.",
78 " @$#+#+#+#+#+#@.",
79 " @@@@@@@@@@@@@@.",
80 " ..............",
81 " ",
82 " "};
83
84 /* XPM */
85 static char * icon2_xpm[] = {
86 /* width height ncolors chars_per_pixel */
87 "16 16 6 1",
88 /* colors */
89 " s None c None",
90 ". c #000000",
91 "+ c #c0c0c0",
92 "@ c #808080",
93 "# c #ffff00",
94 "$ c #ffffff",
95 /* pixels */
96 " ",
97 " @@@@@ ",
98 " @$$$$$@ ",
99 " @$#+#+#$@@@@@@ ",
100 " @$+#+#+$$$$$$@.",
101 " @$#+#+#+#+#+#@.",
102 "@@@@@@@@@@@@@#@.",
103 "@$$$$$$$$$$@@+@.",
104 "@$#+#+#+#+##.@@.",
105 " @$#+#+#+#+#+.@.",
106 " @$+#+#+#+#+#.@.",
107 " @$+#+#+#+##@..",
108 " @@@@@@@@@@@@@.",
109 " .............",
110 " ",
111 " "};
112
113 #endif // !wxMSW
114
115 static const int ID_DIRCTRL = 1000;
116 static const int ID_TEXTCTRL = 1001;
117 static const int ID_OK = 1002;
118 static const int ID_CANCEL = 1003;
119 static const int ID_NEW = 1004;
120 //static const int ID_CHECK = 1005;
121
122 //-----------------------------------------------------------------------------
123 // wxDirItemData
124 //-----------------------------------------------------------------------------
125
126 wxDirItemData::wxDirItemData(wxString& path, wxString& name)
127 {
128 m_path = path;
129 m_name = name;
130 /* Insert logic to detect hidden files here
131 * In UnixLand we just check whether the first char is a dot
132 * For FileNameFromPath read LastDirNameInThisPath ;-) */
133 // m_isHidden = (bool)(wxFileNameFromPath(*m_path)[0] == '.');
134 m_isHidden = FALSE;
135 m_hasSubDirs = HasSubDirs();
136 }
137
138 wxDirItemData::~wxDirItemData()
139 {
140 }
141
142 void wxDirItemData::SetNewDirName( wxString path )
143 {
144 m_path = path;
145 m_name = wxFileNameFromPath( path );
146 }
147
148 bool wxDirItemData::HasSubDirs()
149 {
150 wxString search = m_path + wxT("/*");
151 wxLogNull log;
152 wxString path = wxFindFirstFile( search, wxDIR );
153 return (bool)(!path.IsNull());
154 }
155
156 //-----------------------------------------------------------------------------
157 // wxDirCtrl
158 //-----------------------------------------------------------------------------
159
160 IMPLEMENT_DYNAMIC_CLASS(wxDirCtrl,wxTreeCtrl)
161
162 BEGIN_EVENT_TABLE(wxDirCtrl,wxTreeCtrl)
163 EVT_TREE_ITEM_EXPANDING (-1, wxDirCtrl::OnExpandItem)
164 EVT_TREE_ITEM_COLLAPSED (-1, wxDirCtrl::OnCollapseItem)
165 EVT_TREE_BEGIN_LABEL_EDIT (-1, wxDirCtrl::OnBeginEditItem)
166 EVT_TREE_END_LABEL_EDIT (-1, wxDirCtrl::OnEndEditItem)
167 END_EVENT_TABLE()
168
169 wxDirCtrl::wxDirCtrl(void)
170 {
171 m_showHidden = FALSE;
172 }
173
174 wxDirCtrl::wxDirCtrl(wxWindow *parent,
175 const wxWindowID id,
176 const wxString &WXUNUSED(dir),
177 const wxPoint& pos,
178 const wxSize& size,
179 const long style,
180 const wxString& name )
181 : wxTreeCtrl( parent, id, pos, size, style, wxDefaultValidator, name )
182 {
183 #ifndef __WXMSW__
184 m_imageListNormal = new wxImageList(16, 16, TRUE);
185 m_imageListNormal->Add(wxICON(icon1));
186 m_imageListNormal->Add(wxICON(icon2));
187 SetImageList(m_imageListNormal);
188 #endif // !MSW
189
190 m_showHidden = FALSE;
191 m_rootId = AddRoot( _("Sections") );
192 SetItemHasChildren(m_rootId);
193 Expand(m_rootId); // automatically expand first level
194 }
195
196 /* Quick macro. Don't worry, I'll #undef it later */
197 #define ADD_SECTION(a,b) \
198 if (wxPathExists((a))) { m_paths.Add( (a) ); m_names.Add( (b) ); };
199
200 void wxDirCtrl::SetupSections()
201 {
202 wxString home;
203
204 m_paths.Clear();
205 m_names.Clear();
206 #ifdef __WXMSW__
207 // better than nothing
208 ADD_SECTION(wxT("c:\\"), _("My Harddisk") )
209 #else
210 ADD_SECTION(wxT("/"), _("The Computer") )
211 wxGetHomeDir(&home);
212 ADD_SECTION(home, _("My Home") )
213 ADD_SECTION(wxT("/mnt"), _("Mounted Devices") )
214 ADD_SECTION(wxT("/usr/local"), _("User Local") )
215 ADD_SECTION(wxT("/usr"), _("User") )
216 ADD_SECTION(wxT("/var"), _("Variables") )
217 ADD_SECTION(wxT("/etc"), _("Etcetera") )
218 ADD_SECTION(wxT("/tmp"), _("Temporary") )
219 #endif
220 }
221 #undef ADD_SECTION
222
223 void wxDirCtrl::CreateItems(const wxTreeItemId &parent)
224 {
225 wxTreeItemId id;
226 wxDirItemData *dir_item;
227
228 // wxASSERT(m_paths.Count() == m_names.Count()); ?
229
230 size_t count = m_paths.GetCount();
231 for ( size_t i=0; i<count; i++)
232 {
233 dir_item = new wxDirItemData(m_paths[i],m_names[i]);
234 #ifdef __WXMSW__
235 id = AppendItem( parent, m_names[i], -1, -1, dir_item);
236 #else
237 id = AppendItem( parent, m_names[i], 0, -1, dir_item);
238 SetItemImage( id, 1, wxTreeItemIcon_Expanded );
239 #endif
240 if (dir_item->m_hasSubDirs) SetItemHasChildren(id);
241 }
242 }
243
244 void wxDirCtrl::OnBeginEditItem(wxTreeEvent &event)
245 {
246 // don't rename the main entry "Sections"
247 if (event.GetItem() == m_rootId)
248 {
249 event.Veto();
250 return;
251 }
252
253 // don't rename the individual sections
254 if (GetParent( event.GetItem() ) == m_rootId)
255 {
256 event.Veto();
257 return;
258 }
259 }
260
261 void wxDirCtrl::OnEndEditItem(wxTreeEvent &event)
262 {
263 if ((event.GetLabel().IsEmpty()) ||
264 (event.GetLabel() == _(".")) ||
265 (event.GetLabel() == _("..")) ||
266 (event.GetLabel().First( wxT("/") ) != wxNOT_FOUND))
267 {
268 wxMessageDialog dialog(this, _("Illegal directory name."), _("Error"), wxOK | wxICON_ERROR );
269 dialog.ShowModal();
270 event.Veto();
271 return;
272 }
273
274 wxTreeItemId id = event.GetItem();
275 wxDirItemData *data = (wxDirItemData*)GetItemData( id );
276 wxASSERT( data );
277
278 wxString new_name( wxPathOnly( data->m_path ) );
279 new_name += wxT("/");
280 new_name += event.GetLabel();
281
282 wxLogNull log;
283
284 if (wxFileExists(new_name))
285 {
286 wxMessageDialog dialog(this, _("File name exists already."), _("Error"), wxOK | wxICON_ERROR );
287 dialog.ShowModal();
288 event.Veto();
289 }
290
291 if (wxRenameFile(data->m_path,new_name))
292 {
293 data->SetNewDirName( new_name );
294 }
295 else
296 {
297 wxMessageDialog dialog(this, _("Operation not permitted."), _("Error"), wxOK | wxICON_ERROR );
298 dialog.ShowModal();
299 event.Veto();
300 }
301 }
302
303 void wxDirCtrl::OnExpandItem(wxTreeEvent &event)
304 {
305 if (event.GetItem() == m_rootId)
306 {
307 SetupSections();
308 CreateItems(m_rootId);
309 return;
310 }
311
312 // This may take a longish time. Go to busy cursor
313 wxBeginBusyCursor();
314
315 wxDirItemData *data = (wxDirItemData *)GetItemData(event.GetItem());
316 wxASSERT(data);
317
318 wxString search,path,filename;
319
320 m_paths.Clear();
321 m_names.Clear();
322 #ifdef __WXMSW__
323 search = data->m_path + _T("\\*.*");
324 #else
325 search = data->m_path + _T("/*");
326 #endif
327 for (path = wxFindFirstFile( search, wxDIR ); !path.IsNull();
328 path=wxFindNextFile() )
329 {
330 filename = wxFileNameFromPath( path );
331 /* Don't add "." and ".." to the tree. I think wxFindNextFile
332 * also checks this, but I don't quite understand what happens
333 * there. Also wxFindNextFile seems to swallow hidden dirs */
334 if ( (filename != _T(".")) && (filename != _T("..")) )
335 {
336 m_paths.Add(path);
337 m_names.Add(filename);
338 }
339 }
340
341 CreateItems( event.GetItem() );
342 SortChildren( event.GetItem() );
343
344 wxEndBusyCursor();
345 }
346
347 void wxDirCtrl::OnCollapseItem(wxTreeEvent &event )
348 {
349 wxTreeItemId child, parent = event.GetItem();
350 long cookie;
351 /* Workaround because DeleteChildren has disapeared (why?) and
352 * CollapseAndReset doesn't work as advertised (deletes parent too) */
353 child = GetFirstChild(parent, cookie);
354 while (child.IsOk())
355 {
356 Delete(child);
357 /* Not GetNextChild below, because the cookie mechanism can't
358 * handle disappearing children! */
359 child = GetFirstChild(parent, cookie);
360 }
361 }
362
363 //-----------------------------------------------------------------------------
364 // wxDirDialog
365 //-----------------------------------------------------------------------------
366
367
368 IMPLEMENT_DYNAMIC_CLASS( wxDirDialog, wxDialog )
369
370 BEGIN_EVENT_TABLE( wxDirDialog, wxDialog )
371 EVT_TREE_KEY_DOWN (ID_DIRCTRL, wxDirDialog::OnTreeKeyDown)
372 EVT_TREE_SEL_CHANGED (ID_DIRCTRL, wxDirDialog::OnTreeSelected)
373 EVT_SIZE ( wxDirDialog::OnSize)
374 EVT_BUTTON (ID_OK, wxDirDialog::OnOK)
375 EVT_BUTTON (ID_CANCEL, wxDirDialog::OnCancel)
376 EVT_BUTTON (ID_NEW, wxDirDialog::OnNew)
377 EVT_TEXT_ENTER (ID_TEXTCTRL, wxDirDialog::OnOK)
378 // EVT_CHECKBOX (ID_CHECK, wxDirDialog::OnCheck)
379 END_EVENT_TABLE()
380
381 wxDirDialog::wxDirDialog(wxWindow *parent,
382 const wxString& message,
383 const wxString& defaultPath,
384 long style,
385 const wxPoint& pos)
386 : wxDialog(parent, -1, message, pos, wxSize(300,300),
387 wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
388 {
389 m_message = message;
390 m_dialogStyle = style;
391 m_parent = parent;
392
393 m_path = defaultPath;
394
395 wxBeginBusyCursor();
396
397 wxBoxSizer *topsizer = new wxBoxSizer( wxVERTICAL );
398
399 // 1) dir ctrl
400 m_dir = new wxDirCtrl( this, ID_DIRCTRL, _T("/"),
401 wxDefaultPosition,
402 wxSize(200,200),
403 wxTR_HAS_BUTTONS |
404 wxSUNKEN_BORDER |
405 wxTR_EDIT_LABELS );
406 topsizer->Add( m_dir, 1, wxTOP|wxLEFT|wxRIGHT | wxEXPAND, 10 );
407
408 // 2) text ctrl
409 m_input = new wxTextCtrl( this, ID_TEXTCTRL, m_path, wxDefaultPosition );
410 topsizer->Add( m_input, 0, wxTOP|wxLEFT|wxRIGHT | wxEXPAND, 10 );
411
412 // m_check = new wxCheckBox( this, ID_CHECK, _("Show hidden") );
413 // m_check->SetValue(TRUE);
414
415 #if wxUSE_STATLINE
416 // 3) static line
417 topsizer->Add( new wxStaticLine( this, -1 ), 0, wxEXPAND | wxLEFT|wxRIGHT|wxTOP, 10 );
418 #endif
419
420 // 4) buttons
421 wxSizer* buttonsizer = new wxBoxSizer( wxHORIZONTAL );
422 m_ok = new wxButton( this, ID_OK, _("OK") );
423 buttonsizer->Add( m_ok, 0, wxLEFT|wxRIGHT, 10 );
424 m_cancel = new wxButton( this, ID_CANCEL, _("Cancel") );
425 buttonsizer->Add( m_cancel, 0, wxLEFT|wxRIGHT, 10 );
426 m_new = new wxButton( this, ID_NEW, _("New...") );
427 buttonsizer->Add( m_new, 0, wxLEFT|wxRIGHT, 10 );
428
429 topsizer->Add( buttonsizer, 0, wxALL | wxCENTER, 10 );
430
431 m_ok->SetDefault();
432 m_dir->SetFocus();
433
434 SetAutoLayout( TRUE );
435 SetSizer( topsizer );
436
437 topsizer->SetSizeHints( this );
438 topsizer->Fit( this );
439
440 Centre( wxBOTH );
441
442 if (m_path == wxT("~"))
443 wxGetHomeDir( &m_path );
444
445 // choose the directory corresponding to defaultPath in the tree
446 // VZ: using wxStringTokenizer is probably unsafe here (escaped slashes
447 // will not be processed correctly...)
448 wxStringTokenizer tk(m_path, wxFILE_SEP_PATH, wxTOKEN_STRTOK);
449
450 wxString path;
451
452 long cookie = 0;
453 // default to root dir
454 wxTreeItemId item = m_dir->GetFirstChild(m_dir->GetRootItem(), cookie);
455
456 if (!m_path.IsEmpty() && (m_path != wxT("/")) && (m_dir->m_paths.Count() > 1))
457 {
458 size_t count = m_dir->m_paths.GetCount();
459 for ( size_t i=1; i<count; i++)
460 {
461 if (m_path.Find( m_dir->m_paths[i] ) == 0)
462 {
463 path = m_dir->m_paths[i];
464
465 for (size_t j = 0; j < i; j++)
466 item = m_dir->GetNextChild(m_dir->GetRootItem(), cookie);
467
468 wxStringTokenizer tk2(path, wxFILE_SEP_PATH, wxTOKEN_STRTOK);
469 for (size_t h = 0; h < tk2.CountTokens(); h++)
470 tk.GetNextToken();
471
472 break;
473 }
474 }
475 }
476 while ( tk.HasMoreTokens() && item.IsOk() )
477 {
478 path << wxFILE_SEP_PATH << tk.GetNextToken();
479
480 m_dir->Expand(item);
481
482 wxTreeItemId child = m_dir->GetFirstChild(item, cookie);
483 while ( child.IsOk() )
484 {
485 wxDirItemData *data = (wxDirItemData*)m_dir->GetItemData(child);
486 if ( data->m_path == path )
487 break;
488
489 child = m_dir->GetNextChild(item, cookie);
490 }
491
492 item = child;
493 }
494
495 if ( item.IsOk() )
496 {
497 m_dir->Expand(item);
498 m_dir->SelectItem(item);
499 m_dir->EnsureVisible(item);
500 }
501
502 wxEndBusyCursor();
503 }
504
505 int wxDirDialog::ShowModal()
506 {
507 m_input->SetValue( m_path );
508 return wxDialog::ShowModal();
509 }
510
511 void wxDirDialog::OnTreeSelected( wxTreeEvent &event )
512 {
513 wxDirItemData *data = (wxDirItemData*)m_dir->GetItemData(event.GetItem());
514 if (data)
515 m_input->SetValue( data->m_path );
516 };
517
518 void wxDirDialog::OnTreeKeyDown( wxTreeEvent &WXUNUSED(event) )
519 {
520 wxDirItemData *data = (wxDirItemData*)m_dir->GetItemData(m_dir->GetSelection());
521 if (data)
522 m_input->SetValue( data->m_path );
523 };
524
525 void wxDirDialog::OnOK( wxCommandEvent& WXUNUSED(event) )
526 {
527 m_path = m_input->GetValue();
528 // Does the path exist? (User may have typed anything in m_input)
529 if (wxPathExists(m_path)) {
530 // OK, path exists, we're done.
531 EndModal(wxID_OK);
532 return;
533 }
534 // Interact with user, find out if the dir is a typo or to be created
535 wxString msg( _("The directory ") );
536 msg = msg + m_path;
537 msg = msg + _("\ndoes not exist\nCreate it now?") ;
538 wxMessageDialog dialog(this, msg, _("Directory does not exist"), wxYES_NO | wxICON_WARNING );
539 if ( dialog.ShowModal() == wxID_YES ) {
540 // Okay, let's make it
541 wxLogNull log;
542 if (wxMkdir(m_path)) {
543 // The new dir was created okay.
544 EndModal(wxID_OK);
545 return;
546 }
547 else {
548 // Trouble...
549 msg = _("Failed to create directory ")+m_path+
550 _("\n(Do you have the required permissions?)");
551 wxMessageDialog errmsg(this, msg, _("Error creating directory"), wxOK | wxICON_ERROR);
552 errmsg.ShowModal();
553 // We still don't have a valid dir. Back to the main dialog.
554 }
555 }
556 // User has answered NO to create dir.
557 }
558
559 void wxDirDialog::OnCancel( wxCommandEvent& WXUNUSED(event) )
560 {
561 EndModal(wxID_CANCEL);
562 }
563
564 void wxDirDialog::OnNew( wxCommandEvent& WXUNUSED(event) )
565 {
566 wxTreeItemId id = m_dir->GetSelection();
567 if ((id == m_dir->GetRootItem()) ||
568 (m_dir->GetParent(id) == m_dir->GetRootItem()))
569 {
570 wxMessageDialog msg(this, _("You cannot add a new directory to this section."),
571 _("Create directory"), wxOK | wxICON_INFORMATION );
572 msg.ShowModal();
573 return;
574 }
575
576 wxTreeItemId parent = m_dir->GetParent( id );
577 wxDirItemData *data = (wxDirItemData*)m_dir->GetItemData( parent );
578 wxASSERT( data );
579
580 wxString new_name( wxT("NewName") );
581 wxString path( data->m_path );
582 path += wxT("/");
583 path += new_name;
584 if (wxFileExists(path))
585 {
586 // try NewName0, NewName1 etc.
587 int i = 0;
588 do {
589 new_name = wxT("NewName");
590 wxString num;
591 num.Printf( wxT("%d"), i );
592 new_name += num;
593
594 path = data->m_path;
595 path += wxT("/");
596 path += new_name;
597 i++;
598 } while (wxFileExists(path));
599 }
600
601 wxLogNull log;
602 if (!wxMkdir(path))
603 {
604 wxMessageDialog dialog(this, _("Operation not permitted."), _("Error"), wxOK | wxICON_ERROR );
605 dialog.ShowModal();
606 return;
607 }
608
609 wxDirItemData *new_data = new wxDirItemData( path, new_name );
610 wxTreeItemId new_id = m_dir->AppendItem( parent, new_name, 0, 1, new_data );
611 m_dir->EnsureVisible( new_id );
612 m_dir->EditLabel( new_id );
613 }
614
615 /*
616 void wxDirDialog::OnCheck( wxCommandEvent& WXUNUSED(event) )
617 {
618 printf("Checkbox clicked: %s\n", ( m_check->GetValue() ? "on" : "off" ) );
619 }
620 */
621
622 #endif // wxUSE_DIRDLG