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