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