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