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