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