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