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