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