Code cleaning: wxID_ANY, wxDefaultSize, wxDefaultPosition, true, false, wxEmptyString...
[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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
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/generic/dirctrlg.h"
26
27 #include "wx/module.h"
28 #include "wx/utils.h"
29 #include "wx/button.h"
30 #include "wx/layout.h"
31 #include "wx/msgdlg.h"
32 #include "wx/textctrl.h"
33 #include "wx/textdlg.h"
34 #include "wx/filefn.h"
35 #include "wx/cmndata.h"
36 #include "wx/gdicmn.h"
37 #include "wx/intl.h"
38 #include "wx/imaglist.h"
39 #include "wx/icon.h"
40 #include "wx/log.h"
41 #include "wx/sizer.h"
42 #include "wx/tokenzr.h"
43 #include "wx/dir.h"
44 #include "wx/settings.h"
45 #include "wx/artprov.h"
46 #include "wx/hash.h"
47 #include "wx/mimetype.h"
48 #include "wx/image.h"
49 #include "wx/choice.h"
50
51 #if wxUSE_STATLINE
52 #include "wx/statline.h"
53 #endif
54
55 #if defined(__WXMAC__)
56 #include "wx/mac/private.h" // includes mac headers
57 #endif
58
59 #ifdef __WXMSW__
60 #include <windows.h>
61
62 // FIXME - Mingw32 1.0 has both _getdrive() and _chdrive(). For now, let's assume
63 // older releases don't, but it should be verified and the checks modified
64 // accordingly.
65 #if !defined(__GNUWIN32__) || (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
66 #if !defined(__WXWINCE__)
67 #include <direct.h>
68 #endif
69 #include <stdlib.h>
70 #include <ctype.h>
71 #endif
72
73 #endif
74
75 #if defined(__OS2__) || defined(__DOS__)
76 #ifdef __OS2__
77 #define INCL_BASE
78 #include <os2.h>
79 #ifndef __EMX__
80 #include <direct.h>
81 #endif
82 #include <stdlib.h>
83 #include <ctype.h>
84 #endif
85 extern bool wxIsDriveAvailable(const wxString& dirName);
86 #endif // __OS2__
87
88 #if defined(__WXMAC__)
89 # ifdef __DARWIN__
90 # include "MoreFilesX.h"
91 # else
92 # include "MoreFilesExtras.h"
93 # endif
94 #endif
95
96 #ifdef __BORLANDC__
97 #include "dos.h"
98 #endif
99
100 // If compiled under Windows, this macro can cause problems
101 #ifdef GetFirstChild
102 #undef GetFirstChild
103 #endif
104
105 // ----------------------------------------------------------------------------
106 // wxGetAvailableDrives, for WINDOWS, DOS, OS2, MAC, UNIX (returns "/")
107 // ----------------------------------------------------------------------------
108
109 size_t wxGetAvailableDrives(wxArrayString &paths, wxArrayString &names, wxArrayInt &icon_ids)
110 {
111 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
112
113 #ifdef __WXWINCE__
114 // No logical drives; return "\"
115 paths.Add(wxT("\\"));
116 names.Add(wxT("\\"));
117 return 1;
118 #elif defined(__WIN32__)
119 wxChar driveBuffer[256];
120 size_t n = (size_t) GetLogicalDriveStrings(255, driveBuffer);
121 size_t i = 0;
122 while (i < n)
123 {
124 wxString path, name;
125 path.Printf(wxT("%c:\\"), driveBuffer[i]);
126 name.Printf(wxT("%c:"), driveBuffer[i]);
127
128 int imageId;
129 int driveType = ::GetDriveType(path);
130 switch (driveType)
131 {
132 case DRIVE_REMOVABLE:
133 if (path == wxT("a:\\") || path == wxT("b:\\"))
134 imageId = wxFileIconsTable::floppy;
135 else
136 imageId = wxFileIconsTable::removeable;
137 break;
138 case DRIVE_CDROM:
139 imageId = wxFileIconsTable::cdrom;
140 break;
141 case DRIVE_REMOTE:
142 case DRIVE_FIXED:
143 default:
144 imageId = wxFileIconsTable::drive;
145 break;
146 }
147
148 paths.Add(path);
149 names.Add(name);
150 icon_ids.Add(imageId);
151
152 while (driveBuffer[i] != wxT('\0'))
153 i ++;
154 i ++;
155 if (driveBuffer[i] == wxT('\0'))
156 break;
157 }
158 #elif defined(__OS2__)
159 APIRET rc;
160 ULONG ulDriveNum = 0;
161 ULONG ulDriveMap = 0;
162 rc = ::DosQueryCurrentDisk(&ulDriveNum, &ulDriveMap);
163 if ( rc == 0)
164 {
165 size_t i = 0;
166 while (i < 26)
167 {
168 if (ulDriveMap & ( 1 << i ))
169 {
170 wxString path, name;
171 path.Printf(wxT("%c:\\"), 'A' + i);
172 name.Printf(wxT("%c:"), 'A' + i);
173
174 int imageId;
175 if (path == wxT("A:\\") || path == wxT("B:\\"))
176 imageId = wxFileIconsTable::floppy;
177 else
178 imageId = wxFileIconsTable::drive;
179 paths.Add(path);
180 names.Add(name);
181 icon_ids.Add(imageId);
182 }
183 i ++;
184 }
185 }
186 #else // !__WIN32__, !__OS2__
187 int drive;
188
189 /* If we can switch to the drive, it exists. */
190 for( drive = 1; drive <= 26; drive++ )
191 {
192 wxString path, name;
193 path.Printf(wxT("%c:\\"), (char) (drive + 'a' - 1));
194 name.Printf(wxT("%c:"), (char) (drive + 'A' - 1));
195
196 if (wxIsDriveAvailable(path))
197 {
198 paths.Add(path);
199 names.Add(name);
200 icon_ids.Add((drive <= 2) ? wxFileIconsTable::floppy : wxFileIconsTable::drive);
201 }
202 }
203 #endif // __WIN32__/!__WIN32__
204
205 #elif defined(__WXMAC__)
206 #ifdef __DARWIN__
207 FSRef **theVolRefs;
208 ItemCount theVolCount;
209 char thePath[FILENAME_MAX];
210
211 if (FSGetMountedVolumes(&theVolRefs, &theVolCount) == noErr) {
212 ItemCount index;
213 ::HLock( (Handle)theVolRefs ) ;
214 for (index = 0; index < theVolCount; ++index) {
215 // get the POSIX path associated with the FSRef
216 if ( FSRefMakePath(&((*theVolRefs)[index]),
217 (UInt8 *)thePath, sizeof(thePath)) != noErr ) {
218 continue;
219 }
220 // add path separator at end if necessary
221 wxString path( thePath , wxConvLocal) ;
222 if (path.Last() != wxFILE_SEP_PATH) {
223 path += wxFILE_SEP_PATH;
224 }
225 // get Mac volume name for display
226 FSVolumeRefNum vRefNum ;
227 HFSUniStr255 volumeName ;
228
229 if ( FSGetVRefNum(&((*theVolRefs)[index]), &vRefNum) != noErr ) {
230 continue;
231 }
232 if ( FSGetVInfo(vRefNum, &volumeName, NULL, NULL) != noErr ) {
233 continue;
234 }
235 // get C string from Unicode HFS name
236 // see: http://developer.apple.com/carbon/tipsandtricks.html
237 CFStringRef cfstr = CFStringCreateWithCharacters( kCFAllocatorDefault,
238 volumeName.unicode,
239 volumeName.length );
240 // Do something with str
241 char *cstr = NewPtr(CFStringGetLength(cfstr) + 1);
242 if (( cstr == NULL ) ||
243 !CFStringGetCString(cfstr, cstr, CFStringGetLength(cfstr) + 1,
244 kCFStringEncodingMacRoman))
245 {
246 CFRelease( cstr );
247 continue;
248 }
249 wxString name( cstr , wxConvLocal );
250 DisposePtr( cstr );
251 CFRelease( cfstr );
252
253 GetVolParmsInfoBuffer volParmsInfo;
254 UInt32 actualSize;
255 if ( FSGetVolParms(vRefNum, sizeof(volParmsInfo), &volParmsInfo, &actualSize) != noErr ) {
256 continue;
257 }
258
259 paths.Add(path);
260 names.Add(name);
261
262 if ( VolIsEjectable(&volParmsInfo) )
263 icon_ids.Add(wxFileIconsTable::cdrom);
264 else
265 icon_ids.Add(wxFileIconsTable::drive);
266 }
267 ::HUnlock( (Handle)theVolRefs );
268 ::DisposeHandle( (Handle)theVolRefs );
269 }
270 #else // !__DARWIN__
271 FSSpec volume;
272 short index = 1;
273 while(1)
274 {
275 short actualCount = 0 ;
276 if (OnLine(&volume, 1, &actualCount, &index ) != noErr || actualCount==0)
277 {
278 break;
279 }
280
281 wxString name = wxMacFSSpec2MacFilename( &volume );
282 paths.Add(name + wxFILE_SEP_PATH);
283 names.Add(name);
284 icon_ids.Add(wxFileIconsTable::drive);
285 }
286 #endif // __DARWIN__
287
288 #elif defined(__UNIX__)
289 paths.Add(wxT("/"));
290 names.Add(wxT("/"));
291 icon_ids.Add(wxFileIconsTable::computer);
292 #else
293 #error "Unsupported platform in wxGenericDirCtrl!"
294 #endif
295 return paths.GetCount();
296 }
297
298 // ----------------------------------------------------------------------------
299 // wxIsDriveAvailable
300 // ----------------------------------------------------------------------------
301
302 #if defined(__DOS__)
303
304 bool wxIsDriveAvailable(const wxString& dirName)
305 {
306 // FIXME_MGL - this method leads to hang up under Watcom for some reason
307 #ifndef __WATCOMC__
308 if ( dirName.Len() == 3 && dirName[1u] == wxT(':') )
309 {
310 wxString dirNameLower(dirName.Lower());
311 // VS: always return true for removable media, since Win95 doesn't
312 // like it when MS-DOS app accesses empty floppy drive
313 return (dirNameLower[0u] == wxT('a') ||
314 dirNameLower[0u] == wxT('b') ||
315 wxPathExists(dirNameLower));
316 }
317 else
318 #endif
319 return true;
320 }
321
322 #elif defined(__WINDOWS__) || defined(__OS2__)
323
324 int setdrive(int drive)
325 {
326 #ifdef __WXWINCE__
327 return 0;
328 #elif defined(__GNUWIN32__) && \
329 (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
330 return _chdrive(drive);
331 #else
332 wxChar newdrive[4];
333
334 if (drive < 1 || drive > 31)
335 return -1;
336 newdrive[0] = (wxChar)(wxT('A') + drive - 1);
337 newdrive[1] = wxT(':');
338 #ifdef __OS2__
339 newdrive[2] = wxT('\\');
340 newdrive[3] = wxT('\0');
341 #else
342 newdrive[2] = wxT('\0');
343 #endif
344 #if defined(__WXMSW__)
345 if (::SetCurrentDirectory(newdrive))
346 #else
347 // VA doesn't know what LPSTR is and has its own set
348 if (!DosSetCurrentDir((PSZ)newdrive))
349 #endif
350 return 0;
351 else
352 return -1;
353 #endif // !GNUWIN32
354 }
355
356 bool wxIsDriveAvailable(const wxString& dirName)
357 {
358 #ifdef __WXWINCE__
359 return false;
360 #else
361 #ifdef __WIN32__
362 UINT errorMode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
363 #endif
364 bool success = true;
365
366 // Check if this is a root directory and if so,
367 // whether the drive is available.
368 if (dirName.Len() == 3 && dirName[(size_t)1] == wxT(':'))
369 {
370 wxString dirNameLower(dirName.Lower());
371 #if defined(__GNUWIN32__) && !(defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
372 success = wxPathExists(dirNameLower);
373 #else
374 #if defined(__OS2__)
375 // Avoid changing to drive since no media may be inserted.
376 if (dirNameLower[(size_t)0] == 'a' || dirNameLower[(size_t)0] == 'b')
377 return success;
378 #endif
379 int currentDrive = _getdrive();
380 int thisDrive = (int) (dirNameLower[(size_t)0] - 'a' + 1) ;
381 int err = setdrive( thisDrive ) ;
382 setdrive( currentDrive );
383
384 if (err == -1)
385 {
386 success = false;
387 }
388 #endif
389 }
390 #ifdef __WIN32__
391 (void) SetErrorMode(errorMode);
392 #endif
393
394 return success;
395 #endif
396 }
397 #endif // __WINDOWS__ || __OS2__
398
399
400 // Function which is called by quick sort. We want to override the default wxArrayString behaviour,
401 // and sort regardless of case.
402 static int wxCMPFUNC_CONV wxDirCtrlStringCompareFunction(wxString* strFirst, wxString* strSecond)
403 {
404 return strFirst->CmpNoCase(*strSecond);
405 }
406
407 //-----------------------------------------------------------------------------
408 // wxDirItemData
409 //-----------------------------------------------------------------------------
410
411 wxDirItemData::wxDirItemData(const wxString& path, const wxString& name,
412 bool isDir)
413 {
414 m_path = path;
415 m_name = name;
416 /* Insert logic to detect hidden files here
417 * In UnixLand we just check whether the first char is a dot
418 * For FileNameFromPath read LastDirNameInThisPath ;-) */
419 // m_isHidden = (bool)(wxFileNameFromPath(*m_path)[0] == '.');
420 m_isHidden = false;
421 m_isExpanded = false;
422 m_isDir = isDir;
423 }
424
425 wxDirItemData::~wxDirItemData()
426 {
427 }
428
429 void wxDirItemData::SetNewDirName(const wxString& path)
430 {
431 m_path = path;
432 m_name = wxFileNameFromPath(path);
433 }
434
435 bool wxDirItemData::HasSubDirs() const
436 {
437 if (m_path.IsEmpty())
438 return false;
439
440 wxDir dir;
441 {
442 wxLogNull nolog;
443 if ( !dir.Open(m_path) )
444 return false;
445 }
446
447 return dir.HasSubDirs();
448 }
449
450 bool wxDirItemData::HasFiles(const wxString& WXUNUSED(spec)) const
451 {
452 if (m_path.IsEmpty())
453 return false;
454
455 wxDir dir;
456 {
457 wxLogNull nolog;
458 if ( !dir.Open(m_path) )
459 return false;
460 }
461
462 return dir.HasFiles();
463 }
464
465 //-----------------------------------------------------------------------------
466 // wxGenericDirCtrl
467 //-----------------------------------------------------------------------------
468
469
470 #if wxUSE_EXTENDED_RTTI
471 WX_DEFINE_FLAGS( wxGenericDirCtrlStyle )
472
473 wxBEGIN_FLAGS( wxGenericDirCtrlStyle )
474 // new style border flags, we put them first to
475 // use them for streaming out
476 wxFLAGS_MEMBER(wxBORDER_SIMPLE)
477 wxFLAGS_MEMBER(wxBORDER_SUNKEN)
478 wxFLAGS_MEMBER(wxBORDER_DOUBLE)
479 wxFLAGS_MEMBER(wxBORDER_RAISED)
480 wxFLAGS_MEMBER(wxBORDER_STATIC)
481 wxFLAGS_MEMBER(wxBORDER_NONE)
482
483 // old style border flags
484 wxFLAGS_MEMBER(wxSIMPLE_BORDER)
485 wxFLAGS_MEMBER(wxSUNKEN_BORDER)
486 wxFLAGS_MEMBER(wxDOUBLE_BORDER)
487 wxFLAGS_MEMBER(wxRAISED_BORDER)
488 wxFLAGS_MEMBER(wxSTATIC_BORDER)
489 wxFLAGS_MEMBER(wxBORDER)
490
491 // standard window styles
492 wxFLAGS_MEMBER(wxTAB_TRAVERSAL)
493 wxFLAGS_MEMBER(wxCLIP_CHILDREN)
494 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW)
495 wxFLAGS_MEMBER(wxWANTS_CHARS)
496 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE)
497 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB )
498 wxFLAGS_MEMBER(wxVSCROLL)
499 wxFLAGS_MEMBER(wxHSCROLL)
500
501 wxFLAGS_MEMBER(wxDIRCTRL_DIR_ONLY)
502 wxFLAGS_MEMBER(wxDIRCTRL_3D_INTERNAL)
503 wxFLAGS_MEMBER(wxDIRCTRL_SELECT_FIRST)
504 wxFLAGS_MEMBER(wxDIRCTRL_SHOW_FILTERS)
505
506 wxEND_FLAGS( wxGenericDirCtrlStyle )
507
508 IMPLEMENT_DYNAMIC_CLASS_XTI(wxGenericDirCtrl, wxControl,"wx/dirctrl.h")
509
510 wxBEGIN_PROPERTIES_TABLE(wxGenericDirCtrl)
511 wxHIDE_PROPERTY( Children )
512 wxPROPERTY( DefaultPath , wxString , SetDefaultPath , GetDefaultPath , EMPTY_MACROVALUE , 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
513 wxPROPERTY( Filter , wxString , SetFilter , GetFilter , EMPTY_MACROVALUE , 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
514 wxPROPERTY( DefaultFilter , int , SetFilterIndex, GetFilterIndex, EMPTY_MACROVALUE , 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
515 wxPROPERTY_FLAGS( WindowStyle, wxGenericDirCtrlStyle, long, SetWindowStyleFlag, GetWindowStyleFlag, EMPTY_MACROVALUE , 0, wxT("Helpstring"), wxT("group") )
516 wxEND_PROPERTIES_TABLE()
517
518 wxBEGIN_HANDLERS_TABLE(wxGenericDirCtrl)
519 wxEND_HANDLERS_TABLE()
520
521 wxCONSTRUCTOR_8( wxGenericDirCtrl , wxWindow* , Parent , wxWindowID , Id , wxString , DefaultPath ,
522 wxPoint , Position , wxSize , Size , long , WindowStyle , wxString , Filter , int , DefaultFilter )
523 #else
524 IMPLEMENT_DYNAMIC_CLASS(wxGenericDirCtrl, wxControl)
525 #endif
526
527 BEGIN_EVENT_TABLE(wxGenericDirCtrl, wxControl)
528 EVT_TREE_ITEM_EXPANDING (wxID_TREECTRL, wxGenericDirCtrl::OnExpandItem)
529 EVT_TREE_ITEM_COLLAPSED (wxID_TREECTRL, wxGenericDirCtrl::OnCollapseItem)
530 EVT_TREE_BEGIN_LABEL_EDIT (wxID_TREECTRL, wxGenericDirCtrl::OnBeginEditItem)
531 EVT_TREE_END_LABEL_EDIT (wxID_TREECTRL, wxGenericDirCtrl::OnEndEditItem)
532 EVT_SIZE (wxGenericDirCtrl::OnSize)
533 END_EVENT_TABLE()
534
535 wxGenericDirCtrl::wxGenericDirCtrl(void)
536 {
537 Init();
538 }
539
540 bool wxGenericDirCtrl::Create(wxWindow *parent,
541 const wxWindowID id,
542 const wxString& dir,
543 const wxPoint& pos,
544 const wxSize& size,
545 long style,
546 const wxString& filter,
547 int defaultFilter,
548 const wxString& name)
549 {
550 if (!wxControl::Create(parent, id, pos, size, style, wxDefaultValidator, name))
551 return false;
552
553 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE));
554
555 Init();
556
557 long treeStyle = wxTR_HAS_BUTTONS | wxTR_HIDE_ROOT;
558
559 if (style & wxDIRCTRL_EDIT_LABELS)
560 treeStyle |= wxTR_EDIT_LABELS;
561
562 if ((style & wxDIRCTRL_3D_INTERNAL) == 0)
563 treeStyle |= wxNO_BORDER;
564 else
565 treeStyle |= wxBORDER_SUNKEN;
566
567 long filterStyle = 0;
568 if ((style & wxDIRCTRL_3D_INTERNAL) == 0)
569 filterStyle |= wxNO_BORDER;
570 else
571 filterStyle |= wxBORDER_SUNKEN;
572
573 m_treeCtrl = new wxTreeCtrl(this, wxID_TREECTRL, pos, size, treeStyle);
574
575 if (!filter.IsEmpty() && (style & wxDIRCTRL_SHOW_FILTERS))
576 m_filterListCtrl = new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL, wxDefaultPosition, wxDefaultSize, filterStyle);
577
578 m_defaultPath = dir;
579 m_filter = filter;
580
581 SetFilterIndex(defaultFilter);
582
583 if (m_filterListCtrl)
584 m_filterListCtrl->FillFilterList(filter, defaultFilter);
585
586 m_treeCtrl->SetImageList(wxTheFileIconsTable->GetSmallImageList());
587
588 m_showHidden = false;
589 wxDirItemData* rootData = new wxDirItemData(wxEmptyString, wxEmptyString, true);
590
591 wxString rootName;
592
593 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
594 rootName = _("Computer");
595 #else
596 rootName = _("Sections");
597 #endif
598
599 m_rootId = m_treeCtrl->AddRoot( rootName, 3, -1, rootData);
600 m_treeCtrl->SetItemHasChildren(m_rootId);
601 ExpandDir(m_rootId); // automatically expand first level
602
603 // Expand and select the default path
604 if (!m_defaultPath.IsEmpty())
605 ExpandPath(m_defaultPath);
606
607 SetBestSize(size);
608 DoResize();
609
610 return true;
611 }
612
613 wxGenericDirCtrl::~wxGenericDirCtrl()
614 {
615 }
616
617 void wxGenericDirCtrl::Init()
618 {
619 m_showHidden = false;
620 m_currentFilter = 0;
621 m_currentFilterStr = wxEmptyString; // Default: any file
622 m_treeCtrl = NULL;
623 m_filterListCtrl = NULL;
624 }
625
626 void wxGenericDirCtrl::ShowHidden( bool show )
627 {
628 m_showHidden = show;
629
630 wxString path = GetPath();
631 ReCreateTree();
632 SetPath(path);
633 }
634
635 const wxTreeItemId
636 wxGenericDirCtrl::AddSection(const wxString& path, const wxString& name, int imageId)
637 {
638 wxDirItemData *dir_item = new wxDirItemData(path,name,true);
639
640 wxTreeItemId id = AppendItem( m_rootId, name, imageId, -1, dir_item);
641
642 m_treeCtrl->SetItemHasChildren(id);
643
644 return id;
645 }
646
647 void wxGenericDirCtrl::SetupSections()
648 {
649 wxArrayString paths, names;
650 wxArrayInt icons;
651
652 size_t n, count = wxGetAvailableDrives(paths, names, icons);
653
654 for (n = 0; n < count; n++)
655 {
656 AddSection(paths[n], names[n], icons[n]);
657 }
658 }
659
660 void wxGenericDirCtrl::OnBeginEditItem(wxTreeEvent &event)
661 {
662 // don't rename the main entry "Sections"
663 if (event.GetItem() == m_rootId)
664 {
665 event.Veto();
666 return;
667 }
668
669 // don't rename the individual sections
670 if (m_treeCtrl->GetItemParent( event.GetItem() ) == m_rootId)
671 {
672 event.Veto();
673 return;
674 }
675 }
676
677 void wxGenericDirCtrl::OnEndEditItem(wxTreeEvent &event)
678 {
679 if ((event.GetLabel().IsEmpty()) ||
680 (event.GetLabel() == _(".")) ||
681 (event.GetLabel() == _("..")) ||
682 (event.GetLabel().Find(wxT('/')) != wxNOT_FOUND) ||
683 (event.GetLabel().Find(wxT('\\')) != wxNOT_FOUND) ||
684 (event.GetLabel().Find(wxT('|')) != wxNOT_FOUND))
685 {
686 wxMessageDialog dialog(this, _("Illegal directory name."), _("Error"), wxOK | wxICON_ERROR );
687 dialog.ShowModal();
688 event.Veto();
689 return;
690 }
691
692 wxTreeItemId id = event.GetItem();
693 wxDirItemData *data = (wxDirItemData*)m_treeCtrl->GetItemData( id );
694 wxASSERT( data );
695
696 wxString new_name( wxPathOnly( data->m_path ) );
697 new_name += wxString(wxFILE_SEP_PATH);
698 new_name += event.GetLabel();
699
700 wxLogNull log;
701
702 if (wxFileExists(new_name))
703 {
704 wxMessageDialog dialog(this, _("File name exists already."), _("Error"), wxOK | wxICON_ERROR );
705 dialog.ShowModal();
706 event.Veto();
707 }
708
709 if (wxRenameFile(data->m_path,new_name))
710 {
711 data->SetNewDirName( new_name );
712 }
713 else
714 {
715 wxMessageDialog dialog(this, _("Operation not permitted."), _("Error"), wxOK | wxICON_ERROR );
716 dialog.ShowModal();
717 event.Veto();
718 }
719 }
720
721 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent &event)
722 {
723 wxTreeItemId parentId = event.GetItem();
724
725 // VS: this is needed because the event handler is called from wxTreeCtrl
726 // ctor when wxTR_HIDE_ROOT was specified
727
728 if (!m_rootId.IsOk())
729
730 m_rootId = m_treeCtrl->GetRootItem();
731
732 ExpandDir(parentId);
733 }
734
735 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent &event )
736 {
737 CollapseDir(event.GetItem());
738 }
739
740 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId)
741 {
742 wxTreeItemId child;
743
744 wxDirItemData *data = (wxDirItemData *) m_treeCtrl->GetItemData(parentId);
745 if (!data->m_isExpanded)
746 return;
747
748 data->m_isExpanded = false;
749 wxTreeItemIdValue cookie;
750 /* Workaround because DeleteChildren has disapeared (why?) and
751 * CollapseAndReset doesn't work as advertised (deletes parent too) */
752 child = m_treeCtrl->GetFirstChild(parentId, cookie);
753 while (child.IsOk())
754 {
755 m_treeCtrl->Delete(child);
756 /* Not GetNextChild below, because the cookie mechanism can't
757 * handle disappearing children! */
758 child = m_treeCtrl->GetFirstChild(parentId, cookie);
759 }
760 }
761
762 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId)
763 {
764 wxDirItemData *data = (wxDirItemData *) m_treeCtrl->GetItemData(parentId);
765
766 if (data->m_isExpanded)
767 return;
768
769 data->m_isExpanded = true;
770
771 if (parentId == m_treeCtrl->GetRootItem())
772 {
773 SetupSections();
774 return;
775 }
776
777 wxASSERT(data);
778
779 wxString search,path,filename;
780
781 wxString dirName(data->m_path);
782
783 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
784 // Check if this is a root directory and if so,
785 // whether the drive is avaiable.
786 if (!wxIsDriveAvailable(dirName))
787 {
788 data->m_isExpanded = false;
789 //wxMessageBox(wxT("Sorry, this drive is not available."));
790 return;
791 }
792 #endif
793
794 // This may take a longish time. Go to busy cursor
795 wxBusyCursor busy;
796
797 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
798 if (dirName.Last() == ':')
799 dirName += wxString(wxFILE_SEP_PATH);
800 #endif
801
802 wxArrayString dirs;
803 wxArrayString filenames;
804
805 wxDir d;
806 wxString eachFilename;
807
808 wxLogNull log;
809 d.Open(dirName);
810
811 if (d.IsOpened())
812 {
813 int style = wxDIR_DIRS;
814 if (m_showHidden) style |= wxDIR_HIDDEN;
815 if (d.GetFirst(& eachFilename, wxEmptyString, style))
816 {
817 do
818 {
819 if ((eachFilename != wxT(".")) && (eachFilename != wxT("..")))
820 {
821 dirs.Add(eachFilename);
822 }
823 }
824 while (d.GetNext(&eachFilename));
825 }
826 }
827 dirs.Sort(wxDirCtrlStringCompareFunction);
828
829 // Now do the filenames -- but only if we're allowed to
830 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY) == 0)
831 {
832 wxLogNull log;
833
834 d.Open(dirName);
835
836 if (d.IsOpened())
837 {
838 int style = wxDIR_FILES;
839 if (m_showHidden) style |= wxDIR_HIDDEN;
840 // Process each filter (ex: "JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg")
841 wxStringTokenizer strTok;
842 wxString curFilter;
843 strTok.SetString(m_currentFilterStr,wxT(";"));
844 while(strTok.HasMoreTokens())
845 {
846 curFilter = strTok.GetNextToken();
847 if (d.GetFirst(& eachFilename, m_currentFilterStr, style))
848 {
849 do
850 {
851 if ((eachFilename != wxT(".")) && (eachFilename != wxT("..")))
852 {
853 filenames.Add(eachFilename);
854 }
855 }
856 while (d.GetNext(& eachFilename));
857 }
858 }
859 }
860 filenames.Sort(wxDirCtrlStringCompareFunction);
861 }
862
863 // Add the sorted dirs
864 size_t i;
865 for (i = 0; i < dirs.Count(); i++)
866 {
867 wxString eachFilename(dirs[i]);
868 path = dirName;
869 if (!wxEndsWithPathSeparator(path))
870 path += wxString(wxFILE_SEP_PATH);
871 path += eachFilename;
872
873 wxDirItemData *dir_item = new wxDirItemData(path,eachFilename,true);
874 wxTreeItemId id = AppendItem( parentId, eachFilename,
875 wxFileIconsTable::folder, -1, dir_item);
876 m_treeCtrl->SetItemImage( id, wxFileIconsTable::folder_open,
877 wxTreeItemIcon_Expanded );
878
879 // Has this got any children? If so, make it expandable.
880 // (There are two situations when a dir has children: either it
881 // has subdirectories or it contains files that weren't filtered
882 // out. The latter only applies to dirctrl with files.)
883 if ( dir_item->HasSubDirs() ||
884 (((GetWindowStyle() & wxDIRCTRL_DIR_ONLY) == 0) &&
885 dir_item->HasFiles(m_currentFilterStr)) )
886 {
887 m_treeCtrl->SetItemHasChildren(id);
888 }
889 }
890
891 // Add the sorted filenames
892 if ((GetWindowStyle() & wxDIRCTRL_DIR_ONLY) == 0)
893 {
894 for (i = 0; i < filenames.Count(); i++)
895 {
896 wxString eachFilename(filenames[i]);
897 path = dirName;
898 if (!wxEndsWithPathSeparator(path))
899 path += wxString(wxFILE_SEP_PATH);
900 path += eachFilename;
901 //path = dirName + wxString(wxT("/")) + eachFilename;
902 wxDirItemData *dir_item = new wxDirItemData(path,eachFilename,false);
903 int image_id = wxFileIconsTable::file;
904 if (eachFilename.Find(wxT('.')) != wxNOT_FOUND)
905 image_id = wxTheFileIconsTable->GetIconID(eachFilename.AfterLast(wxT('.')));
906 (void) AppendItem( parentId, eachFilename, image_id, -1, dir_item);
907 }
908 }
909 }
910
911 void wxGenericDirCtrl::ReCreateTree()
912 {
913 CollapseDir(m_treeCtrl->GetRootItem());
914 ExpandDir(m_treeCtrl->GetRootItem());
915 }
916
917 // Find the child that matches the first part of 'path'.
918 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
919 // then the child for /usr is returned.
920 wxTreeItemId wxGenericDirCtrl::FindChild(wxTreeItemId parentId, const wxString& path, bool& done)
921 {
922 wxString path2(path);
923
924 // Make sure all separators are as per the current platform
925 path2.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH));
926 path2.Replace(wxT("/"), wxString(wxFILE_SEP_PATH));
927
928 // Append a separator to foil bogus substring matching
929 path2 += wxString(wxFILE_SEP_PATH);
930
931 // In MSW or PM, case is not significant
932 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
933 path2.MakeLower();
934 #endif
935
936 wxTreeItemIdValue cookie;
937 wxTreeItemId childId = m_treeCtrl->GetFirstChild(parentId, cookie);
938 while (childId.IsOk())
939 {
940 wxDirItemData* data = (wxDirItemData*) m_treeCtrl->GetItemData(childId);
941
942 if (data && !data->m_path.IsEmpty())
943 {
944 wxString childPath(data->m_path);
945 if (!wxEndsWithPathSeparator(childPath))
946 childPath += wxString(wxFILE_SEP_PATH);
947
948 // In MSW and PM, case is not significant
949 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
950 childPath.MakeLower();
951 #endif
952
953 if (childPath.Len() <= path2.Len())
954 {
955 wxString path3 = path2.Mid(0, childPath.Len());
956 if (childPath == path3)
957 {
958 if (path3.Len() == path2.Len())
959 done = true;
960 else
961 done = false;
962 return childId;
963 }
964 }
965 }
966
967 childId = m_treeCtrl->GetNextChild(parentId, cookie);
968 }
969 wxTreeItemId invalid;
970 return invalid;
971 }
972
973 // Try to expand as much of the given path as possible,
974 // and select the given tree item.
975 bool wxGenericDirCtrl::ExpandPath(const wxString& path)
976 {
977 bool done = false;
978 wxTreeItemId id = FindChild(m_rootId, path, done);
979 wxTreeItemId lastId = id; // The last non-zero id
980 while (id.IsOk() && !done)
981 {
982 ExpandDir(id);
983
984 id = FindChild(id, path, done);
985 if (id.IsOk())
986 lastId = id;
987 }
988 if (lastId.IsOk())
989 {
990 wxDirItemData *data = (wxDirItemData *) m_treeCtrl->GetItemData(lastId);
991 if (data->m_isDir)
992 {
993 m_treeCtrl->Expand(lastId);
994 }
995 if ((GetWindowStyle() & wxDIRCTRL_SELECT_FIRST) && data->m_isDir)
996 {
997 // Find the first file in this directory
998 wxTreeItemIdValue cookie;
999 wxTreeItemId childId = m_treeCtrl->GetFirstChild(lastId, cookie);
1000 bool selectedChild = false;
1001 while (childId.IsOk())
1002 {
1003 wxDirItemData* data = (wxDirItemData*) m_treeCtrl->GetItemData(childId);
1004
1005 if (data && data->m_path != wxEmptyString && !data->m_isDir)
1006 {
1007 m_treeCtrl->SelectItem(childId);
1008 m_treeCtrl->EnsureVisible(childId);
1009 selectedChild = true;
1010 break;
1011 }
1012 childId = m_treeCtrl->GetNextChild(lastId, cookie);
1013 }
1014 if (!selectedChild)
1015 {
1016 m_treeCtrl->SelectItem(lastId);
1017 m_treeCtrl->EnsureVisible(lastId);
1018 }
1019 }
1020 else
1021 {
1022 m_treeCtrl->SelectItem(lastId);
1023 m_treeCtrl->EnsureVisible(lastId);
1024 }
1025
1026 return true;
1027 }
1028 else
1029 return false;
1030 }
1031
1032 wxString wxGenericDirCtrl::GetPath() const
1033 {
1034 wxTreeItemId id = m_treeCtrl->GetSelection();
1035 if (id)
1036 {
1037 wxDirItemData* data = (wxDirItemData*) m_treeCtrl->GetItemData(id);
1038 return data->m_path;
1039 }
1040 else
1041 return wxEmptyString;
1042 }
1043
1044 wxString wxGenericDirCtrl::GetFilePath() const
1045 {
1046 wxTreeItemId id = m_treeCtrl->GetSelection();
1047 if (id)
1048 {
1049 wxDirItemData* data = (wxDirItemData*) m_treeCtrl->GetItemData(id);
1050 if (data->m_isDir)
1051 return wxEmptyString;
1052 else
1053 return data->m_path;
1054 }
1055 else
1056 return wxEmptyString;
1057 }
1058
1059 void wxGenericDirCtrl::SetPath(const wxString& path)
1060 {
1061 m_defaultPath = path;
1062 if (m_rootId)
1063 ExpandPath(path);
1064 }
1065
1066 // Not used
1067 #if 0
1068 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId id, int dirFlags, wxArrayString& filenames)
1069 {
1070 wxDirItemData *data = (wxDirItemData *) m_treeCtrl->GetItemData(id);
1071
1072 // This may take a longish time. Go to busy cursor
1073 wxBusyCursor busy;
1074
1075 wxASSERT(data);
1076
1077 wxString search,path,filename;
1078
1079 wxString dirName(data->m_path);
1080
1081 #if defined(__WXMSW__) || defined(__OS2__)
1082 if (dirName.Last() == ':')
1083 dirName += wxString(wxFILE_SEP_PATH);
1084 #endif
1085
1086 wxDir d;
1087 wxString eachFilename;
1088
1089 wxLogNull log;
1090 d.Open(dirName);
1091
1092 if (d.IsOpened())
1093 {
1094 if (d.GetFirst(& eachFilename, m_currentFilterStr, dirFlags))
1095 {
1096 do
1097 {
1098 if ((eachFilename != wxT(".")) && (eachFilename != wxT("..")))
1099 {
1100 filenames.Add(eachFilename);
1101 }
1102 }
1103 while (d.GetNext(& eachFilename)) ;
1104 }
1105 }
1106 }
1107 #endif
1108
1109 void wxGenericDirCtrl::SetFilterIndex(int n)
1110 {
1111 m_currentFilter = n;
1112
1113 wxString f, d;
1114 if (ExtractWildcard(m_filter, n, f, d))
1115 m_currentFilterStr = f;
1116 else
1117 m_currentFilterStr = wxT("*.*");
1118 }
1119
1120 void wxGenericDirCtrl::SetFilter(const wxString& filter)
1121 {
1122 m_filter = filter;
1123
1124 wxString f, d;
1125 if (ExtractWildcard(m_filter, m_currentFilter, f, d))
1126 m_currentFilterStr = f;
1127 else
1128 m_currentFilterStr = wxT("*.*");
1129 }
1130
1131 // Extract description and actual filter from overall filter string
1132 bool wxGenericDirCtrl::ExtractWildcard(const wxString& filterStr, int n, wxString& filter, wxString& description)
1133 {
1134 wxArrayString filters, descriptions;
1135 int count = wxParseWildcard(filterStr, filters, descriptions);
1136 if (count > 0 && n < count)
1137 {
1138 filter = filters[n];
1139 description = descriptions[n];
1140 return true;
1141 }
1142
1143 return false;
1144 }
1145
1146 #if WXWIN_COMPATIBILITY_2_4
1147 // Parses the global filter, returning the number of filters.
1148 // Returns 0 if none or if there's a problem.
1149 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpg"
1150 int wxGenericDirCtrl::ParseFilter(const wxString& filterStr, wxArrayString& filters, wxArrayString& descriptions)
1151 {
1152 return wxParseWildcard(filterStr, descriptions, filters );
1153 }
1154 #endif // WXWIN_COMPATIBILITY_2_4
1155
1156 void wxGenericDirCtrl::DoResize()
1157 {
1158 wxSize sz = GetClientSize();
1159 int verticalSpacing = 3;
1160 if (m_treeCtrl)
1161 {
1162 wxSize filterSz ;
1163 if (m_filterListCtrl)
1164 {
1165 #ifdef __WXMSW__
1166 // For some reason, this is required in order for the
1167 // correct control height to always be returned, rather
1168 // than the drop-down list height which is sometimes returned.
1169 wxSize oldSize = m_filterListCtrl->GetSize();
1170 m_filterListCtrl->SetSize(wxDefaultPosition.x,
1171 wxDefaultPosition.y,
1172 oldSize.x+10,
1173 wxDefaultSize.y,
1174 wxSIZE_USE_EXISTING);
1175 m_filterListCtrl->SetSize(wxDefaultPosition.x,
1176 wxDefaultPosition.y,
1177 oldSize.x,
1178 wxDefaultSize.y,
1179 wxSIZE_USE_EXISTING);
1180 #endif
1181 filterSz = m_filterListCtrl->GetSize();
1182 sz.y -= (filterSz.y + verticalSpacing);
1183 }
1184 m_treeCtrl->SetSize(0, 0, sz.x, sz.y);
1185 if (m_filterListCtrl)
1186 {
1187 m_filterListCtrl->SetSize(0, sz.y + verticalSpacing, sz.x, filterSz.y);
1188 // Don't know why, but this needs refreshing after a resize (wxMSW)
1189 m_filterListCtrl->Refresh();
1190 }
1191 }
1192 }
1193
1194
1195 void wxGenericDirCtrl::OnSize(wxSizeEvent& WXUNUSED(event))
1196 {
1197 DoResize();
1198 }
1199
1200 wxTreeItemId wxGenericDirCtrl::AppendItem (const wxTreeItemId & parent,
1201 const wxString & text,
1202 int image, int selectedImage,
1203 wxTreeItemData * data)
1204 {
1205 wxTreeCtrl *treeCtrl = GetTreeCtrl ();
1206
1207 wxASSERT (treeCtrl);
1208
1209 if (treeCtrl)
1210 {
1211 return treeCtrl->AppendItem (parent, text, image, selectedImage, data);
1212 }
1213 else
1214 {
1215 return wxTreeItemId();
1216 }
1217 }
1218
1219
1220 //-----------------------------------------------------------------------------
1221 // wxDirFilterListCtrl
1222 //-----------------------------------------------------------------------------
1223
1224 IMPLEMENT_CLASS(wxDirFilterListCtrl, wxChoice)
1225
1226 BEGIN_EVENT_TABLE(wxDirFilterListCtrl, wxChoice)
1227 EVT_CHOICE(wxID_ANY, wxDirFilterListCtrl::OnSelFilter)
1228 END_EVENT_TABLE()
1229
1230 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl* parent, const wxWindowID id,
1231 const wxPoint& pos,
1232 const wxSize& size,
1233 long style)
1234 {
1235 m_dirCtrl = parent;
1236 return wxChoice::Create(parent, id, pos, size, 0, NULL, style);
1237 }
1238
1239 void wxDirFilterListCtrl::Init()
1240 {
1241 m_dirCtrl = NULL;
1242 }
1243
1244 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent& WXUNUSED(event))
1245 {
1246 int sel = GetSelection();
1247
1248 wxString currentPath = m_dirCtrl->GetPath();
1249
1250 m_dirCtrl->SetFilterIndex(sel);
1251
1252 // If the filter has changed, the view is out of date, so
1253 // collapse the tree.
1254 m_dirCtrl->ReCreateTree();
1255
1256 // Try to restore the selection, or at least the directory
1257 m_dirCtrl->ExpandPath(currentPath);
1258 }
1259
1260 void wxDirFilterListCtrl::FillFilterList(const wxString& filter, int defaultFilter)
1261 {
1262 Clear();
1263 wxArrayString descriptions, filters;
1264 size_t n = (size_t) wxParseWildcard(filter, filters, descriptions);
1265
1266 if (n > 0 && defaultFilter < (int) n)
1267 {
1268 for (size_t i = 0; i < n; i++)
1269 Append(descriptions[i]);
1270 SetSelection(defaultFilter);
1271 }
1272 }
1273
1274
1275 // ----------------------------------------------------------------------------
1276 // wxFileIconsTable icons
1277 // ----------------------------------------------------------------------------
1278
1279 /* Open folder */
1280 static const char * file_icons_tbl_folder_open_xpm[] = {
1281 /* width height ncolors chars_per_pixel */
1282 "16 16 6 1",
1283 /* colors */
1284 " s None c None",
1285 ". c #000000",
1286 "+ c #c0c0c0",
1287 "@ c #808080",
1288 "# c #ffff00",
1289 "$ c #ffffff",
1290 /* pixels */
1291 " ",
1292 " @@@@@ ",
1293 " @$$$$$@ ",
1294 " @$#+#+#$@@@@@@ ",
1295 " @$+#+#+$$$$$$@.",
1296 " @$#+#+#+#+#+#@.",
1297 "@@@@@@@@@@@@@#@.",
1298 "@$$$$$$$$$$@@+@.",
1299 "@$#+#+#+#+##.@@.",
1300 " @$#+#+#+#+#+.@.",
1301 " @$+#+#+#+#+#.@.",
1302 " @$+#+#+#+##@..",
1303 " @@@@@@@@@@@@@.",
1304 " .............",
1305 " ",
1306 " "};
1307
1308 /* Computer */
1309 static const char * file_icons_tbl_computer_xpm[] = {
1310 "16 16 7 1",
1311 " s None c None",
1312 ". c #808080",
1313 "X c #c0c0c0",
1314 "o c Black",
1315 "O c Gray100",
1316 "+ c #008080",
1317 "@ c Blue",
1318 " ........... ",
1319 " .XXXXXXXXXX.o",
1320 " .OOOOOOOOO..o",
1321 " .OoooooooX..o",
1322 " .Oo+...@+X..o",
1323 " .Oo+XXX.+X..o",
1324 " .Oo+....+X..o",
1325 " .Oo++++++X..o",
1326 " .OXXXXXXXX.oo",
1327 " ..........o.o",
1328 " ...........Xo",
1329 " .XXXXXXXXXX.o",
1330 " .o.o.o.o.o...o",
1331 " .oXoXoXoXoXo.o ",
1332 ".XOXXXXXXXXX.o ",
1333 "............o "};
1334
1335 /* Drive */
1336 static const char * file_icons_tbl_drive_xpm[] = {
1337 "16 16 7 1",
1338 " s None c None",
1339 ". c #808080",
1340 "X c #c0c0c0",
1341 "o c Black",
1342 "O c Gray100",
1343 "+ c Green",
1344 "@ c #008000",
1345 " ",
1346 " ",
1347 " ",
1348 " ",
1349 " ............. ",
1350 " .XXXXXXXXXXXX.o",
1351 ".OOOOOOOOOOOO..o",
1352 ".XXXXXXXXX+@X..o",
1353 ".XXXXXXXXXXXX..o",
1354 ".X..........X..o",
1355 ".XOOOOOOOOOOX..o",
1356 "..............o ",
1357 " ooooooooooooo ",
1358 " ",
1359 " ",
1360 " "};
1361
1362 /* CD-ROM */
1363 static const char *file_icons_tbl_cdrom_xpm[] = {
1364 "16 16 10 1",
1365 " s None c None",
1366 ". c #808080",
1367 "X c #c0c0c0",
1368 "o c Yellow",
1369 "O c Blue",
1370 "+ c Black",
1371 "@ c Gray100",
1372 "# c #008080",
1373 "$ c Green",
1374 "% c #008000",
1375 " ... ",
1376 " ..XoX.. ",
1377 " .O.XoXXX+ ",
1378 " ...O.oXXXX+ ",
1379 " .O..X.XXXX+ ",
1380 " ....X.+..XXX+",
1381 " .XXX.+@+.XXX+",
1382 " .X@XX.+.X@@X+",
1383 " .....X...#XX@+ ",
1384 ".@@@...XXo.O@X+ ",
1385 ".@XXX..XXoXOO+ ",
1386 ".@++++..XoX+++ ",
1387 ".@$%@@XX+++X.+ ",
1388 ".............+ ",
1389 " ++++++++++++ ",
1390 " "};
1391
1392 /* Floppy */
1393 static const char * file_icons_tbl_floppy_xpm[] = {
1394 "16 16 7 1",
1395 " s None c None",
1396 ". c #808080",
1397 "X c Gray100",
1398 "o c #c0c0c0",
1399 "O c Black",
1400 "+ c Cyan",
1401 "@ c Red",
1402 " ......X",
1403 " .ooooooO",
1404 " .+++++OO",
1405 " .++++++O",
1406 " .++++++O",
1407 " .ooooooO",
1408 " .......o....oO",
1409 " .oooooo.o.O.XoO",
1410 ".XXXXXXXXOOOOOO ",
1411 ".ooooooooo@o..O ",
1412 ".ooo....oooo..O ",
1413 ".o..OOOO...o..O ",
1414 ".oooXXXXoooo..O ",
1415 ".............O ",
1416 " OOOOOOOOOOOO ",
1417 " "};
1418
1419 /* Removeable */
1420 static const char * file_icons_tbl_removeable_xpm[] = {
1421 "16 16 7 1",
1422 " s None c None",
1423 ". c #808080",
1424 "X c #c0c0c0",
1425 "o c Black",
1426 "O c Gray100",
1427 "+ c Red",
1428 "@ c #800000",
1429 " ",
1430 " ",
1431 " ",
1432 " ............. ",
1433 " .XXXXXXXXXXXX.o",
1434 ".OOOOOOOOOOOO..o",
1435 ".OXXXXXXXXXXX..o",
1436 ".O+@.oooooo.X..o",
1437 ".OXXOooooooOX..o",
1438 ".OXXXOOOOOOXX..o",
1439 ".OXXXXXXXXXXX..o",
1440 ".O............o ",
1441 " ooooooooooooo ",
1442 " ",
1443 " ",
1444 " "};
1445
1446 // ----------------------------------------------------------------------------
1447 // wxFileIconsTable & friends
1448 // ----------------------------------------------------------------------------
1449
1450 // global instance of a wxFileIconsTable
1451 wxFileIconsTable* wxTheFileIconsTable = (wxFileIconsTable *)NULL;
1452
1453 // A module to allow icons table cleanup
1454
1455 class wxFileIconsTableModule: public wxModule
1456 {
1457 DECLARE_DYNAMIC_CLASS(wxFileIconsTableModule)
1458 public:
1459 wxFileIconsTableModule() {}
1460 bool OnInit() { wxTheFileIconsTable = new wxFileIconsTable; return true; }
1461 void OnExit()
1462 {
1463 if (wxTheFileIconsTable)
1464 {
1465 delete wxTheFileIconsTable;
1466 wxTheFileIconsTable = NULL;
1467 }
1468 }
1469 };
1470
1471 IMPLEMENT_DYNAMIC_CLASS(wxFileIconsTableModule, wxModule)
1472
1473 class wxFileIconEntry : public wxObject
1474 {
1475 public:
1476 wxFileIconEntry(int i) { id = i; }
1477
1478 int id;
1479 };
1480
1481 wxFileIconsTable::wxFileIconsTable()
1482 {
1483 m_HashTable = NULL;
1484 m_smallImageList = NULL;
1485 }
1486
1487 wxFileIconsTable::~wxFileIconsTable()
1488 {
1489 if (m_HashTable)
1490 {
1491 WX_CLEAR_HASH_TABLE(*m_HashTable);
1492 delete m_HashTable;
1493 }
1494 if (m_smallImageList) delete m_smallImageList;
1495 }
1496
1497 // delayed initialization - wait until first use (wxArtProv not created yet)
1498 void wxFileIconsTable::Create()
1499 {
1500 wxCHECK_RET(!m_smallImageList && !m_HashTable, wxT("creating icons twice"));
1501 m_HashTable = new wxHashTable(wxKEY_STRING);
1502 m_smallImageList = new wxImageList(16, 16);
1503
1504 // folder:
1505 m_smallImageList->Add(wxArtProvider::GetBitmap(wxART_FOLDER, wxART_CMN_DIALOG));
1506 // folder_open
1507 m_smallImageList->Add(wxIcon(file_icons_tbl_folder_open_xpm));
1508 // computer
1509 m_smallImageList->Add(wxIcon(file_icons_tbl_computer_xpm));
1510 // drive
1511 m_smallImageList->Add(wxIcon(file_icons_tbl_drive_xpm));
1512 // cdrom
1513 m_smallImageList->Add(wxIcon(file_icons_tbl_cdrom_xpm));
1514 // floppy
1515 m_smallImageList->Add(wxIcon(file_icons_tbl_floppy_xpm));
1516 // removeable
1517 m_smallImageList->Add(wxIcon(file_icons_tbl_removeable_xpm));
1518 // file
1519 m_smallImageList->Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE, wxART_CMN_DIALOG));
1520 // executable
1521 if (GetIconID(wxEmptyString, _T("application/x-executable")) == file)
1522 {
1523 m_smallImageList->Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE, wxART_CMN_DIALOG));
1524 delete m_HashTable->Get(_T("exe"));
1525 m_HashTable->Delete(_T("exe"));
1526 m_HashTable->Put(_T("exe"), new wxFileIconEntry(executable));
1527 }
1528 /* else put into list by GetIconID
1529 (KDE defines application/x-executable for *.exe and has nice icon)
1530 */
1531 }
1532
1533 wxImageList *wxFileIconsTable::GetSmallImageList()
1534 {
1535 if (!m_smallImageList)
1536 Create();
1537
1538 return m_smallImageList;
1539 }
1540
1541 #if wxUSE_MIMETYPE && wxUSE_IMAGE
1542 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
1543 // one icon and we won't resize it
1544
1545 static wxBitmap CreateAntialiasedBitmap(const wxImage& img)
1546 {
1547 const unsigned int size = 16;
1548
1549 wxImage smallimg (size, size);
1550 unsigned char *p1, *p2, *ps;
1551 unsigned char mr = img.GetMaskRed(),
1552 mg = img.GetMaskGreen(),
1553 mb = img.GetMaskBlue();
1554
1555 unsigned x, y;
1556 unsigned sr, sg, sb, smask;
1557
1558 p1 = img.GetData(), p2 = img.GetData() + 3 * size*2, ps = smallimg.GetData();
1559 smallimg.SetMaskColour(mr, mr, mr);
1560
1561 for (y = 0; y < size; y++)
1562 {
1563 for (x = 0; x < size; x++)
1564 {
1565 sr = sg = sb = smask = 0;
1566 if (p1[0] != mr || p1[1] != mg || p1[2] != mb)
1567 sr += p1[0], sg += p1[1], sb += p1[2];
1568 else smask++;
1569 p1 += 3;
1570 if (p1[0] != mr || p1[1] != mg || p1[2] != mb)
1571 sr += p1[0], sg += p1[1], sb += p1[2];
1572 else smask++;
1573 p1 += 3;
1574 if (p2[0] != mr || p2[1] != mg || p2[2] != mb)
1575 sr += p2[0], sg += p2[1], sb += p2[2];
1576 else smask++;
1577 p2 += 3;
1578 if (p2[0] != mr || p2[1] != mg || p2[2] != mb)
1579 sr += p2[0], sg += p2[1], sb += p2[2];
1580 else smask++;
1581 p2 += 3;
1582
1583 if (smask > 2)
1584 ps[0] = ps[1] = ps[2] = mr;
1585 else
1586 ps[0] = sr >> 2, ps[1] = sg >> 2, ps[2] = sb >> 2;
1587 ps += 3;
1588 }
1589 p1 += size*2 * 3, p2 += size*2 * 3;
1590 }
1591
1592 return wxBitmap(smallimg);
1593 }
1594
1595 // This function is currently not unused anymore
1596 #if 0
1597 // finds empty borders and return non-empty area of image:
1598 static wxImage CutEmptyBorders(const wxImage& img)
1599 {
1600 unsigned char mr = img.GetMaskRed(),
1601 mg = img.GetMaskGreen(),
1602 mb = img.GetMaskBlue();
1603 unsigned char *dt = img.GetData(), *dttmp;
1604 unsigned w = img.GetWidth(), h = img.GetHeight();
1605
1606 unsigned top, bottom, left, right, i;
1607 bool empt;
1608
1609 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
1610 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = false; break;}
1611
1612 for (empt = true, top = 0; empt && top < h; top++)
1613 {
1614 MK_DTTMP(0, top);
1615 for (i = 0; i < w; i++, dttmp+=3)
1616 NOEMPTY_PIX(empt)
1617 }
1618 for (empt = true, bottom = h-1; empt && bottom > top; bottom--)
1619 {
1620 MK_DTTMP(0, bottom);
1621 for (i = 0; i < w; i++, dttmp+=3)
1622 NOEMPTY_PIX(empt)
1623 }
1624 for (empt = true, left = 0; empt && left < w; left++)
1625 {
1626 MK_DTTMP(left, 0);
1627 for (i = 0; i < h; i++, dttmp+=3*w)
1628 NOEMPTY_PIX(empt)
1629 }
1630 for (empt = true, right = w-1; empt && right > left; right--)
1631 {
1632 MK_DTTMP(right, 0);
1633 for (i = 0; i < h; i++, dttmp+=3*w)
1634 NOEMPTY_PIX(empt)
1635 }
1636 top--, left--, bottom++, right++;
1637
1638 return img.GetSubImage(wxRect(left, top, right - left + 1, bottom - top + 1));
1639 }
1640 #endif // #if 0
1641
1642 #endif // wxUSE_MIMETYPE
1643
1644 int wxFileIconsTable::GetIconID(const wxString& extension, const wxString& mime)
1645 {
1646 if (!m_smallImageList)
1647 Create();
1648
1649 #if wxUSE_MIMETYPE
1650 if (!extension.IsEmpty())
1651 {
1652 wxFileIconEntry *entry = (wxFileIconEntry*) m_HashTable->Get(extension);
1653 if (entry) return (entry -> id);
1654 }
1655
1656 wxFileType *ft = (mime.IsEmpty()) ?
1657 wxTheMimeTypesManager -> GetFileTypeFromExtension(extension) :
1658 wxTheMimeTypesManager -> GetFileTypeFromMimeType(mime);
1659
1660 wxIconLocation iconLoc;
1661 wxIcon ic;
1662
1663 {
1664 wxLogNull logNull;
1665 if ( ft && ft->GetIcon(&iconLoc) )
1666 {
1667 ic = wxIcon( iconLoc.GetFileName() );
1668 }
1669 }
1670
1671 delete ft;
1672
1673 if ( !ic.Ok() )
1674 {
1675 int newid = file;
1676 m_HashTable->Put(extension, new wxFileIconEntry(newid));
1677 return newid;
1678 }
1679
1680 wxBitmap bmp;
1681 bmp.CopyFromIcon(ic);
1682
1683 if ( !bmp.Ok() )
1684 {
1685 int newid = file;
1686 m_HashTable->Put(extension, new wxFileIconEntry(newid));
1687 return newid;
1688 }
1689
1690 const unsigned int size = 16;
1691
1692 int id = m_smallImageList->GetImageCount();
1693 if ((bmp.GetWidth() == (int) size) && (bmp.GetHeight() == (int) size))
1694 {
1695 m_smallImageList->Add(bmp);
1696 }
1697 #if wxUSE_IMAGE
1698 else
1699 {
1700 wxImage img = bmp.ConvertToImage();
1701
1702 if ((img.GetWidth() != size*2) || (img.GetHeight() != size*2))
1703 // m_smallImageList->Add(CreateAntialiasedBitmap(CutEmptyBorders(img).Rescale(size*2, size*2)));
1704 m_smallImageList->Add(CreateAntialiasedBitmap(img.Rescale(size*2, size*2)));
1705 else
1706 m_smallImageList->Add(CreateAntialiasedBitmap(img));
1707 }
1708 #endif // wxUSE_IMAGE
1709
1710 m_HashTable->Put(extension, new wxFileIconEntry(id));
1711 return id;
1712
1713 #else // !wxUSE_MIMETYPE
1714
1715 if (extension == wxT("exe"))
1716 return executable;
1717 else
1718 return file;
1719 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
1720 }
1721
1722 #endif // wxUSE_DIRDLG