Add wxDirCtrl::GetPath().
[wxWidgets.git] / src / generic / dirctrlg.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/generic/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 // For compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
14
15 #ifdef __BORLANDC__
16 #pragma hdrstop
17 #endif
18
19 #if wxUSE_DIRDLG || wxUSE_FILEDLG
20
21 #include "wx/generic/dirctrlg.h"
22
23 #ifndef WX_PRECOMP
24 #include "wx/hash.h"
25 #include "wx/intl.h"
26 #include "wx/log.h"
27 #include "wx/utils.h"
28 #include "wx/button.h"
29 #include "wx/icon.h"
30 #include "wx/settings.h"
31 #include "wx/msgdlg.h"
32 #include "wx/choice.h"
33 #include "wx/textctrl.h"
34 #include "wx/layout.h"
35 #include "wx/sizer.h"
36 #include "wx/textdlg.h"
37 #include "wx/gdicmn.h"
38 #include "wx/image.h"
39 #include "wx/module.h"
40 #endif
41
42 #include "wx/filename.h"
43 #include "wx/filefn.h"
44 #include "wx/imaglist.h"
45 #include "wx/tokenzr.h"
46 #include "wx/dir.h"
47 #include "wx/artprov.h"
48 #include "wx/mimetype.h"
49
50 #if wxUSE_STATLINE
51 #include "wx/statline.h"
52 #endif
53
54 #if defined(__WXMAC__)
55 #include "wx/osx/private.h" // includes mac headers
56 #endif
57
58 #ifdef __WINDOWS__
59 #include <windows.h>
60 #include "wx/msw/winundef.h"
61 #include "wx/volume.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 // __WINDOWS__
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 #endif // __OS2__
87
88 #if defined(__WXMAC__)
89 // #include "MoreFilesX.h"
90 #endif
91
92 #ifdef __BORLANDC__
93 #include "dos.h"
94 #endif
95
96 extern WXDLLEXPORT_DATA(const char) wxFileSelectorDefaultWildcardStr[];
97
98 // If compiled under Windows, this macro can cause problems
99 #ifdef GetFirstChild
100 #undef GetFirstChild
101 #endif
102
103 bool wxIsDriveAvailable(const wxString& dirName);
104
105 // ----------------------------------------------------------------------------
106 // wxGetAvailableDrives, for WINDOWS, DOS, OS2, MAC, UNIX (returns "/")
107 // ----------------------------------------------------------------------------
108
109 size_t wxGetAvailableDrives(wxArrayString &paths, wxArrayString &names, wxArrayInt &icon_ids)
110 {
111 #ifdef wxHAS_FILESYSTEM_VOLUMES
112
113 #ifdef __WXWINCE__
114 // No logical drives; return "\"
115 paths.Add(wxT("\\"));
116 names.Add(wxT("\\"));
117 icon_ids.Add(wxFileIconsTable::computer);
118 #elif defined(__WIN32__) && wxUSE_FSVOLUME
119 // TODO: this code (using wxFSVolumeBase) should be used for all platforms
120 // but unfortunately wxFSVolumeBase is not implemented everywhere
121 const wxArrayString as = wxFSVolumeBase::GetVolumes();
122
123 for (size_t i = 0; i < as.GetCount(); i++)
124 {
125 wxString path = as[i];
126 wxFSVolume vol(path);
127 int imageId;
128 switch (vol.GetKind())
129 {
130 case wxFS_VOL_FLOPPY:
131 if ( (path == wxT("a:\\")) || (path == wxT("b:\\")) )
132 imageId = wxFileIconsTable::floppy;
133 else
134 imageId = wxFileIconsTable::removeable;
135 break;
136 case wxFS_VOL_DVDROM:
137 case wxFS_VOL_CDROM:
138 imageId = wxFileIconsTable::cdrom;
139 break;
140 case wxFS_VOL_NETWORK:
141 if (path[0] == wxT('\\'))
142 continue; // skip "\\computer\folder"
143 imageId = wxFileIconsTable::drive;
144 break;
145 case wxFS_VOL_DISK:
146 case wxFS_VOL_OTHER:
147 default:
148 imageId = wxFileIconsTable::drive;
149 break;
150 }
151 paths.Add(path);
152 names.Add(vol.GetDisplayName());
153 icon_ids.Add(imageId);
154 }
155 #elif defined(__OS2__)
156 APIRET rc;
157 ULONG ulDriveNum = 0;
158 ULONG ulDriveMap = 0;
159 rc = ::DosQueryCurrentDisk(&ulDriveNum, &ulDriveMap);
160 if ( rc == 0)
161 {
162 size_t i = 0;
163 while (i < 26)
164 {
165 if (ulDriveMap & ( 1 << i ))
166 {
167 const wxString path = wxFileName::GetVolumeString(
168 'A' + i, wxPATH_GET_SEPARATOR);
169 const wxString name = wxFileName::GetVolumeString(
170 'A' + i, wxPATH_NO_SEPARATOR);
171
172 // Note: If _filesys is unsupported by some compilers,
173 // we can always replace it by DosQueryFSAttach
174 char filesysname[20];
175 #ifdef __WATCOMC__
176 ULONG cbBuffer = sizeof(filesysname);
177 PFSQBUFFER2 pfsqBuffer = (PFSQBUFFER2)filesysname;
178 APIRET rc = ::DosQueryFSAttach(name.fn_str(),0,FSAIL_QUERYNAME,pfsqBuffer,&cbBuffer);
179 if (rc != NO_ERROR)
180 {
181 filesysname[0] = '\0';
182 }
183 #else
184 _filesys(name.fn_str(), filesysname, sizeof(filesysname));
185 #endif
186 /* FAT, LAN, HPFS, CDFS, NFS */
187 int imageId;
188 if (path == wxT("A:\\") || path == wxT("B:\\"))
189 imageId = wxFileIconsTable::floppy;
190 else if (!strcmp(filesysname, "CDFS"))
191 imageId = wxFileIconsTable::cdrom;
192 else if (!strcmp(filesysname, "LAN") ||
193 !strcmp(filesysname, "NFS"))
194 imageId = wxFileIconsTable::drive;
195 else
196 imageId = wxFileIconsTable::drive;
197 paths.Add(path);
198 names.Add(name);
199 icon_ids.Add(imageId);
200 }
201 i ++;
202 }
203 }
204 #else // !__WIN32__, !__OS2__
205 /* If we can switch to the drive, it exists. */
206 for ( char drive = 'A'; drive <= 'Z'; drive++ )
207 {
208 const wxString
209 path = wxFileName::GetVolumeString(drive, wxPATH_GET_SEPARATOR);
210
211 if (wxIsDriveAvailable(path))
212 {
213 paths.Add(path);
214 names.Add(wxFileName::GetVolumeString(drive, wxPATH_NO_SEPARATOR));
215 icon_ids.Add(drive <= 2 ? wxFileIconsTable::floppy
216 : wxFileIconsTable::drive);
217 }
218 }
219 #endif // __WIN32__/!__WIN32__
220
221 #elif defined(__WXMAC__) && wxOSX_USE_COCOA_OR_CARBON
222
223 ItemCount volumeIndex = 1;
224 OSErr err = noErr ;
225
226 while( noErr == err )
227 {
228 HFSUniStr255 volumeName ;
229 FSRef fsRef ;
230 FSVolumeInfo volumeInfo ;
231 err = FSGetVolumeInfo(0, volumeIndex, NULL, kFSVolInfoFlags , &volumeInfo , &volumeName, &fsRef);
232 if( noErr == err )
233 {
234 wxString path = wxMacFSRefToPath( &fsRef ) ;
235 wxString name = wxMacHFSUniStrToString( &volumeName ) ;
236
237 if ( (volumeInfo.flags & kFSVolFlagSoftwareLockedMask) || (volumeInfo.flags & kFSVolFlagHardwareLockedMask) )
238 {
239 icon_ids.Add(wxFileIconsTable::cdrom);
240 }
241 else
242 {
243 icon_ids.Add(wxFileIconsTable::drive);
244 }
245 // todo other removable
246
247 paths.Add(path);
248 names.Add(name);
249 volumeIndex++ ;
250 }
251 }
252
253 #elif defined(__UNIX__)
254 paths.Add(wxT("/"));
255 names.Add(wxT("/"));
256 icon_ids.Add(wxFileIconsTable::computer);
257 #else
258 #error "Unsupported platform in wxGenericDirCtrl!"
259 #endif
260 wxASSERT_MSG( (paths.GetCount() == names.GetCount()), wxT("The number of paths and their human readable names should be equal in number."));
261 wxASSERT_MSG( (paths.GetCount() == icon_ids.GetCount()), wxT("Wrong number of icons for available drives."));
262 return paths.GetCount();
263 }
264
265 // ----------------------------------------------------------------------------
266 // wxIsDriveAvailable
267 // ----------------------------------------------------------------------------
268
269 #if defined(__DOS__)
270
271 bool wxIsDriveAvailable(const wxString& dirName)
272 {
273 // FIXME: this method leads to hang up under Watcom for some reason
274 #ifdef __WATCOMC__
275 wxUnusedVar(dirName);
276 #else
277 if ( dirName.length() == 3 && dirName[1u] == wxT(':') )
278 {
279 wxString dirNameLower(dirName.Lower());
280 // VS: always return true for removable media, since Win95 doesn't
281 // like it when MS-DOS app accesses empty floppy drive
282 return (dirNameLower[0u] == wxT('a') ||
283 dirNameLower[0u] == wxT('b') ||
284 wxDirExists(dirNameLower));
285 }
286 else
287 #endif
288 return true;
289 }
290
291 #elif defined(__WINDOWS__) || defined(__OS2__)
292
293 int setdrive(int WXUNUSED_IN_WINCE(drive))
294 {
295 #ifdef __WXWINCE__
296 return 0;
297 #elif defined(__GNUWIN32__) && \
298 (defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
299 return _chdrive(drive);
300 #else
301 wxChar newdrive[4];
302
303 if (drive < 1 || drive > 31)
304 return -1;
305 newdrive[0] = (wxChar)(wxT('A') + drive - 1);
306 newdrive[1] = wxT(':');
307 #ifdef __OS2__
308 newdrive[2] = wxT('\\');
309 newdrive[3] = wxT('\0');
310 #else
311 newdrive[2] = wxT('\0');
312 #endif
313 #if defined(__WINDOWS__)
314 if (::SetCurrentDirectory(newdrive))
315 #else
316 // VA doesn't know what LPSTR is and has its own set
317 if (!DosSetCurrentDir((PSZ)newdrive))
318 #endif
319 return 0;
320 else
321 return -1;
322 #endif // !GNUWIN32
323 }
324
325 bool wxIsDriveAvailable(const wxString& WXUNUSED_IN_WINCE(dirName))
326 {
327 #ifdef __WXWINCE__
328 return false;
329 #else
330 #ifdef __WIN32__
331 UINT errorMode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
332 #endif
333 bool success = true;
334
335 // Check if this is a root directory and if so,
336 // whether the drive is available.
337 if (dirName.length() == 3 && dirName[(size_t)1] == wxT(':'))
338 {
339 wxString dirNameLower(dirName.Lower());
340 #if defined(__GNUWIN32__) && !(defined(__MINGW32_MAJOR_VERSION) && __MINGW32_MAJOR_VERSION >= 1)
341 success = wxDirExists(dirNameLower);
342 #else
343 #if defined(__OS2__)
344 // Avoid changing to drive since no media may be inserted.
345 if (dirNameLower[(size_t)0] == 'a' || dirNameLower[(size_t)0] == 'b')
346 return success;
347 #endif
348 int currentDrive = _getdrive();
349 int thisDrive = (int) (dirNameLower[(size_t)0] - 'a' + 1) ;
350 int err = setdrive( thisDrive ) ;
351 setdrive( currentDrive );
352
353 if (err == -1)
354 {
355 success = false;
356 }
357 #endif
358 }
359 #ifdef __WIN32__
360 (void) SetErrorMode(errorMode);
361 #endif
362
363 return success;
364 #endif
365 }
366 #endif // __WINDOWS__ || __OS2__
367
368 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG
369
370
371
372 #if wxUSE_DIRDLG
373
374 // Function which is called by quick sort. We want to override the default wxArrayString behaviour,
375 // and sort regardless of case.
376 static int wxCMPFUNC_CONV wxDirCtrlStringCompareFunction(const wxString& strFirst, const wxString& strSecond)
377 {
378 return strFirst.CmpNoCase(strSecond);
379 }
380
381 //-----------------------------------------------------------------------------
382 // wxDirItemData
383 //-----------------------------------------------------------------------------
384
385 wxDirItemData::wxDirItemData(const wxString& path, const wxString& name,
386 bool isDir)
387 {
388 m_path = path;
389 m_name = name;
390 /* Insert logic to detect hidden files here
391 * In UnixLand we just check whether the first char is a dot
392 * For FileNameFromPath read LastDirNameInThisPath ;-) */
393 // m_isHidden = (bool)(wxFileNameFromPath(*m_path)[0] == '.');
394 m_isHidden = false;
395 m_isExpanded = false;
396 m_isDir = isDir;
397 }
398
399 void wxDirItemData::SetNewDirName(const wxString& path)
400 {
401 m_path = path;
402 m_name = wxFileNameFromPath(path);
403 }
404
405 bool wxDirItemData::HasSubDirs() const
406 {
407 if (m_path.empty())
408 return false;
409
410 wxDir dir;
411 {
412 wxLogNull nolog;
413 if ( !dir.Open(m_path) )
414 return false;
415 }
416
417 return dir.HasSubDirs();
418 }
419
420 bool wxDirItemData::HasFiles(const wxString& WXUNUSED(spec)) const
421 {
422 if (m_path.empty())
423 return false;
424
425 wxDir dir;
426 {
427 wxLogNull nolog;
428 if ( !dir.Open(m_path) )
429 return false;
430 }
431
432 return dir.HasFiles();
433 }
434
435 //-----------------------------------------------------------------------------
436 // wxGenericDirCtrl
437 //-----------------------------------------------------------------------------
438
439 BEGIN_EVENT_TABLE(wxGenericDirCtrl, wxControl)
440 EVT_TREE_ITEM_EXPANDING (wxID_TREECTRL, wxGenericDirCtrl::OnExpandItem)
441 EVT_TREE_ITEM_COLLAPSED (wxID_TREECTRL, wxGenericDirCtrl::OnCollapseItem)
442 EVT_TREE_BEGIN_LABEL_EDIT (wxID_TREECTRL, wxGenericDirCtrl::OnBeginEditItem)
443 EVT_TREE_END_LABEL_EDIT (wxID_TREECTRL, wxGenericDirCtrl::OnEndEditItem)
444 EVT_SIZE (wxGenericDirCtrl::OnSize)
445 END_EVENT_TABLE()
446
447 wxGenericDirCtrl::wxGenericDirCtrl(void)
448 {
449 Init();
450 }
451
452 void wxGenericDirCtrl::ExpandRoot()
453 {
454 ExpandDir(m_rootId); // automatically expand first level
455
456 // Expand and select the default path
457 if (!m_defaultPath.empty())
458 {
459 ExpandPath(m_defaultPath);
460 }
461 #ifdef __UNIX__
462 else
463 {
464 // On Unix, there's only one node under the (hidden) root node. It
465 // represents the / path, so the user would always have to expand it;
466 // let's do it ourselves
467 ExpandPath( wxT("/") );
468 }
469 #endif
470 }
471
472 bool wxGenericDirCtrl::Create(wxWindow *parent,
473 const wxWindowID treeid,
474 const wxString& dir,
475 const wxPoint& pos,
476 const wxSize& size,
477 long style,
478 const wxString& filter,
479 int defaultFilter,
480 const wxString& name)
481 {
482 if (!wxControl::Create(parent, treeid, pos, size, style, wxDefaultValidator, name))
483 return false;
484
485 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE));
486 SetForegroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT));
487
488 Init();
489
490 long treeStyle = wxTR_HAS_BUTTONS;
491
492 // On Windows CE, if you hide the root, you get a crash when
493 // attempting to access data for children of the root item.
494 #ifndef __WXWINCE__
495 treeStyle |= wxTR_HIDE_ROOT;
496 #endif
497
498 #ifdef __WXGTK20__
499 treeStyle |= wxTR_NO_LINES;
500 #endif
501
502 if (style & wxDIRCTRL_EDIT_LABELS)
503 treeStyle |= wxTR_EDIT_LABELS;
504
505 if (style & wxDIRCTRL_MULTIPLE)
506 treeStyle |= wxTR_MULTIPLE;
507
508 if ((style & wxDIRCTRL_3D_INTERNAL) == 0)
509 treeStyle |= wxNO_BORDER;
510
511 m_treeCtrl = CreateTreeCtrl(this, wxID_TREECTRL,
512 wxPoint(0,0), GetClientSize(), treeStyle);
513
514 if (!filter.empty())
515 m_filterListCtrl = new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL);
516
517 m_defaultPath = dir;
518 m_filter = filter;
519
520 if (m_filter.empty())
521 m_filter = wxFileSelectorDefaultWildcardStr;
522
523 SetFilterIndex(defaultFilter);
524
525 if (m_filterListCtrl)
526 m_filterListCtrl->FillFilterList(filter, defaultFilter);
527
528 m_treeCtrl->SetImageList(wxTheFileIconsTable->GetSmallImageList());
529
530 m_showHidden = false;
531 wxDirItemData* rootData = new wxDirItemData(wxEmptyString, wxEmptyString, true);
532
533 wxString rootName;
534
535 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
536 rootName = _("Computer");
537 #else
538 rootName = _("Sections");
539 #endif
540
541 m_rootId = m_treeCtrl->AddRoot( rootName, 3, -1, rootData);
542 m_treeCtrl->SetItemHasChildren(m_rootId);
543
544 ExpandRoot();
545
546 SetInitialSize(size);
547 DoResize();
548
549 return true;
550 }
551
552 wxGenericDirCtrl::~wxGenericDirCtrl()
553 {
554 }
555
556 void wxGenericDirCtrl::Init()
557 {
558 m_showHidden = false;
559 m_currentFilter = 0;
560 m_currentFilterStr = wxEmptyString; // Default: any file
561 m_treeCtrl = NULL;
562 m_filterListCtrl = NULL;
563 }
564
565 wxTreeCtrl* wxGenericDirCtrl::CreateTreeCtrl(wxWindow *parent, wxWindowID treeid, const wxPoint& pos, const wxSize& size, long treeStyle)
566 {
567 return new wxTreeCtrl(parent, treeid, pos, size, treeStyle);
568 }
569
570 void wxGenericDirCtrl::ShowHidden( bool show )
571 {
572 if ( m_showHidden == show )
573 return;
574
575 m_showHidden = show;
576
577 if ( HasFlag(wxDIRCTRL_MULTIPLE) )
578 {
579 wxArrayString paths;
580 GetPaths(paths);
581 ReCreateTree();
582 for ( unsigned n = 0; n < paths.size(); n++ )
583 {
584 ExpandPath(paths[n]);
585 }
586 }
587 else
588 {
589 wxString path = GetPath();
590 ReCreateTree();
591 SetPath(path);
592 }
593 }
594
595 const wxTreeItemId
596 wxGenericDirCtrl::AddSection(const wxString& path, const wxString& name, int imageId)
597 {
598 wxDirItemData *dir_item = new wxDirItemData(path,name,true);
599
600 wxTreeItemId treeid = AppendItem( m_rootId, name, imageId, -1, dir_item);
601
602 m_treeCtrl->SetItemHasChildren(treeid);
603
604 return treeid;
605 }
606
607 void wxGenericDirCtrl::SetupSections()
608 {
609 wxArrayString paths, names;
610 wxArrayInt icons;
611
612 size_t n, count = wxGetAvailableDrives(paths, names, icons);
613
614 #ifdef __WXGTK20__
615 wxString home = wxGetHomeDir();
616 AddSection( home, _("Home directory"), 1);
617 home += wxT("/Desktop");
618 AddSection( home, _("Desktop"), 1);
619 #endif
620
621 for (n = 0; n < count; n++)
622 AddSection(paths[n], names[n], icons[n]);
623 }
624
625 void wxGenericDirCtrl::SetFocus()
626 {
627 // we don't need focus ourselves, give it to the tree so that the user
628 // could navigate it
629 if (m_treeCtrl)
630 m_treeCtrl->SetFocus();
631 }
632
633 void wxGenericDirCtrl::OnBeginEditItem(wxTreeEvent &event)
634 {
635 // don't rename the main entry "Sections"
636 if (event.GetItem() == m_rootId)
637 {
638 event.Veto();
639 return;
640 }
641
642 // don't rename the individual sections
643 if (m_treeCtrl->GetItemParent( event.GetItem() ) == m_rootId)
644 {
645 event.Veto();
646 return;
647 }
648 }
649
650 void wxGenericDirCtrl::OnEndEditItem(wxTreeEvent &event)
651 {
652 if (event.IsEditCancelled())
653 return;
654
655 if ((event.GetLabel().empty()) ||
656 (event.GetLabel() == wxT(".")) ||
657 (event.GetLabel() == wxT("..")) ||
658 (event.GetLabel().Find(wxT('/')) != wxNOT_FOUND) ||
659 (event.GetLabel().Find(wxT('\\')) != wxNOT_FOUND) ||
660 (event.GetLabel().Find(wxT('|')) != wxNOT_FOUND))
661 {
662 wxMessageDialog dialog(this, _("Illegal directory name."), _("Error"), wxOK | wxICON_ERROR );
663 dialog.ShowModal();
664 event.Veto();
665 return;
666 }
667
668 wxTreeItemId treeid = event.GetItem();
669 wxDirItemData *data = (wxDirItemData*)m_treeCtrl->GetItemData( treeid );
670 wxASSERT( data );
671
672 wxString new_name( wxPathOnly( data->m_path ) );
673 new_name += wxString(wxFILE_SEP_PATH);
674 new_name += event.GetLabel();
675
676 wxLogNull log;
677
678 if (wxFileExists(new_name))
679 {
680 wxMessageDialog dialog(this, _("File name exists already."), _("Error"), wxOK | wxICON_ERROR );
681 dialog.ShowModal();
682 event.Veto();
683 }
684
685 if (wxRenameFile(data->m_path,new_name))
686 {
687 data->SetNewDirName( new_name );
688 }
689 else
690 {
691 wxMessageDialog dialog(this, _("Operation not permitted."), _("Error"), wxOK | wxICON_ERROR );
692 dialog.ShowModal();
693 event.Veto();
694 }
695 }
696
697 void wxGenericDirCtrl::OnExpandItem(wxTreeEvent &event)
698 {
699 wxTreeItemId parentId = event.GetItem();
700
701 // VS: this is needed because the event handler is called from wxTreeCtrl
702 // ctor when wxTR_HIDE_ROOT was specified
703
704 if (!m_rootId.IsOk())
705 m_rootId = m_treeCtrl->GetRootItem();
706
707 ExpandDir(parentId);
708 }
709
710 void wxGenericDirCtrl::OnCollapseItem(wxTreeEvent &event )
711 {
712 CollapseDir(event.GetItem());
713 }
714
715 void wxGenericDirCtrl::CollapseDir(wxTreeItemId parentId)
716 {
717 wxTreeItemId child;
718
719 wxDirItemData *data = (wxDirItemData *) m_treeCtrl->GetItemData(parentId);
720 if (!data->m_isExpanded)
721 return;
722
723 data->m_isExpanded = false;
724
725 m_treeCtrl->Freeze();
726 if (parentId != m_treeCtrl->GetRootItem())
727 m_treeCtrl->CollapseAndReset(parentId);
728 m_treeCtrl->DeleteChildren(parentId);
729 m_treeCtrl->Thaw();
730 }
731
732 void wxGenericDirCtrl::PopulateNode(wxTreeItemId parentId)
733 {
734 wxDirItemData *data = (wxDirItemData *) m_treeCtrl->GetItemData(parentId);
735
736 if (data->m_isExpanded)
737 return;
738
739 data->m_isExpanded = true;
740
741 if (parentId == m_treeCtrl->GetRootItem())
742 {
743 SetupSections();
744 return;
745 }
746
747 wxASSERT(data);
748
749 wxString search,path,filename;
750
751 wxString dirName(data->m_path);
752
753 #if (defined(__WINDOWS__) && !defined(__WXWINCE__)) || defined(__DOS__) || defined(__OS2__)
754 // Check if this is a root directory and if so,
755 // whether the drive is avaiable.
756 if (!wxIsDriveAvailable(dirName))
757 {
758 data->m_isExpanded = false;
759 //wxMessageBox(wxT("Sorry, this drive is not available."));
760 return;
761 }
762 #endif
763
764 // This may take a longish time. Go to busy cursor
765 wxBusyCursor busy;
766
767 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
768 if (dirName.Last() == ':')
769 dirName += wxString(wxFILE_SEP_PATH);
770 #endif
771
772 wxArrayString dirs;
773 wxArrayString filenames;
774
775 wxDir d;
776 wxString eachFilename;
777
778 wxLogNull log;
779 d.Open(dirName);
780
781 if (d.IsOpened())
782 {
783 int style = wxDIR_DIRS;
784 if (m_showHidden) style |= wxDIR_HIDDEN;
785 if (d.GetFirst(& eachFilename, wxEmptyString, style))
786 {
787 do
788 {
789 if ((eachFilename != wxT(".")) && (eachFilename != wxT("..")))
790 {
791 dirs.Add(eachFilename);
792 }
793 }
794 while (d.GetNext(&eachFilename));
795 }
796 }
797 dirs.Sort(wxDirCtrlStringCompareFunction);
798
799 // Now do the filenames -- but only if we're allowed to
800 if (!HasFlag(wxDIRCTRL_DIR_ONLY))
801 {
802 d.Open(dirName);
803
804 if (d.IsOpened())
805 {
806 int style = wxDIR_FILES;
807 if (m_showHidden) style |= wxDIR_HIDDEN;
808 // Process each filter (ex: "JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg")
809 wxStringTokenizer strTok;
810 wxString curFilter;
811 strTok.SetString(m_currentFilterStr,wxT(";"));
812 while(strTok.HasMoreTokens())
813 {
814 curFilter = strTok.GetNextToken();
815 if (d.GetFirst(& eachFilename, curFilter, style))
816 {
817 do
818 {
819 if ((eachFilename != wxT(".")) && (eachFilename != wxT("..")))
820 {
821 filenames.Add(eachFilename);
822 }
823 }
824 while (d.GetNext(& eachFilename));
825 }
826 }
827 }
828 filenames.Sort(wxDirCtrlStringCompareFunction);
829 }
830
831 // Now we really know whether we have any children so tell the tree control
832 // about it.
833 m_treeCtrl->SetItemHasChildren(parentId, !dirs.empty() || !filenames.empty());
834
835 // Add the sorted dirs
836 size_t i;
837 for (i = 0; i < dirs.GetCount(); i++)
838 {
839 eachFilename = dirs[i];
840 path = dirName;
841 if (!wxEndsWithPathSeparator(path))
842 path += wxString(wxFILE_SEP_PATH);
843 path += eachFilename;
844
845 wxDirItemData *dir_item = new wxDirItemData(path,eachFilename,true);
846 wxTreeItemId treeid = AppendItem( parentId, eachFilename,
847 wxFileIconsTable::folder, -1, dir_item);
848 m_treeCtrl->SetItemImage( treeid, wxFileIconsTable::folder_open,
849 wxTreeItemIcon_Expanded );
850
851 // assume that it does have children by default as it can take a long
852 // time to really check for this (think remote drives...)
853 //
854 // and if we're wrong, we'll correct the icon later if
855 // the user really tries to open this item
856 m_treeCtrl->SetItemHasChildren(treeid);
857 }
858
859 // Add the sorted filenames
860 if (!HasFlag(wxDIRCTRL_DIR_ONLY))
861 {
862 for (i = 0; i < filenames.GetCount(); i++)
863 {
864 eachFilename = filenames[i];
865 path = dirName;
866 if (!wxEndsWithPathSeparator(path))
867 path += wxString(wxFILE_SEP_PATH);
868 path += eachFilename;
869 //path = dirName + wxString(wxT("/")) + eachFilename;
870 wxDirItemData *dir_item = new wxDirItemData(path,eachFilename,false);
871 int image_id = wxFileIconsTable::file;
872 if (eachFilename.Find(wxT('.')) != wxNOT_FOUND)
873 image_id = wxTheFileIconsTable->GetIconID(eachFilename.AfterLast(wxT('.')));
874 (void) AppendItem( parentId, eachFilename, image_id, -1, dir_item);
875 }
876 }
877 }
878
879 void wxGenericDirCtrl::ExpandDir(wxTreeItemId parentId)
880 {
881 // ExpandDir() will not actually expand the tree node, just populate it
882 PopulateNode(parentId);
883 }
884
885 void wxGenericDirCtrl::ReCreateTree()
886 {
887 CollapseDir(m_treeCtrl->GetRootItem());
888 ExpandRoot();
889 }
890
891 void wxGenericDirCtrl::CollapseTree()
892 {
893 wxTreeItemIdValue cookie;
894 wxTreeItemId child = m_treeCtrl->GetFirstChild(m_rootId, cookie);
895 while (child.IsOk())
896 {
897 CollapseDir(child);
898 child = m_treeCtrl->GetNextChild(m_rootId, cookie);
899 }
900 }
901
902 // Find the child that matches the first part of 'path'.
903 // E.g. if a child path is "/usr" and 'path' is "/usr/include"
904 // then the child for /usr is returned.
905 wxTreeItemId wxGenericDirCtrl::FindChild(wxTreeItemId parentId, const wxString& path, bool& done)
906 {
907 wxString path2(path);
908
909 // Make sure all separators are as per the current platform
910 path2.Replace(wxT("\\"), wxString(wxFILE_SEP_PATH));
911 path2.Replace(wxT("/"), wxString(wxFILE_SEP_PATH));
912
913 // Append a separator to foil bogus substring matching
914 path2 += wxString(wxFILE_SEP_PATH);
915
916 // In MSW or PM, case is not significant
917 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
918 path2.MakeLower();
919 #endif
920
921 wxTreeItemIdValue cookie;
922 wxTreeItemId childId = m_treeCtrl->GetFirstChild(parentId, cookie);
923 while (childId.IsOk())
924 {
925 wxDirItemData* data = (wxDirItemData*) m_treeCtrl->GetItemData(childId);
926
927 if (data && !data->m_path.empty())
928 {
929 wxString childPath(data->m_path);
930 if (!wxEndsWithPathSeparator(childPath))
931 childPath += wxString(wxFILE_SEP_PATH);
932
933 // In MSW and PM, case is not significant
934 #if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
935 childPath.MakeLower();
936 #endif
937
938 if (childPath.length() <= path2.length())
939 {
940 wxString path3 = path2.Mid(0, childPath.length());
941 if (childPath == path3)
942 {
943 if (path3.length() == path2.length())
944 done = true;
945 else
946 done = false;
947 return childId;
948 }
949 }
950 }
951
952 childId = m_treeCtrl->GetNextChild(parentId, cookie);
953 }
954 wxTreeItemId invalid;
955 return invalid;
956 }
957
958 // Try to expand as much of the given path as possible,
959 // and select the given tree item.
960 bool wxGenericDirCtrl::ExpandPath(const wxString& path)
961 {
962 bool done = false;
963 wxTreeItemId treeid = FindChild(m_rootId, path, done);
964 wxTreeItemId lastId = treeid; // The last non-zero treeid
965 while (treeid.IsOk() && !done)
966 {
967 ExpandDir(treeid);
968
969 treeid = FindChild(treeid, path, done);
970 if (treeid.IsOk())
971 lastId = treeid;
972 }
973 if (!lastId.IsOk())
974 return false;
975
976 wxDirItemData *data = (wxDirItemData *) m_treeCtrl->GetItemData(lastId);
977 if (data->m_isDir)
978 {
979 m_treeCtrl->Expand(lastId);
980 }
981 if (HasFlag(wxDIRCTRL_SELECT_FIRST) && data->m_isDir)
982 {
983 // Find the first file in this directory
984 wxTreeItemIdValue cookie;
985 wxTreeItemId childId = m_treeCtrl->GetFirstChild(lastId, cookie);
986 bool selectedChild = false;
987 while (childId.IsOk())
988 {
989 data = (wxDirItemData*) m_treeCtrl->GetItemData(childId);
990
991 if (data && data->m_path != wxEmptyString && !data->m_isDir)
992 {
993 m_treeCtrl->SelectItem(childId);
994 m_treeCtrl->EnsureVisible(childId);
995 selectedChild = true;
996 break;
997 }
998 childId = m_treeCtrl->GetNextChild(lastId, cookie);
999 }
1000 if (!selectedChild)
1001 {
1002 m_treeCtrl->SelectItem(lastId);
1003 m_treeCtrl->EnsureVisible(lastId);
1004 }
1005 }
1006 else
1007 {
1008 m_treeCtrl->SelectItem(lastId);
1009 m_treeCtrl->EnsureVisible(lastId);
1010 }
1011
1012 return true;
1013 }
1014
1015
1016 bool wxGenericDirCtrl::CollapsePath(const wxString& path)
1017 {
1018 bool done = false;
1019 wxTreeItemId treeid = FindChild(m_rootId, path, done);
1020 wxTreeItemId lastId = treeid; // The last non-zero treeid
1021
1022 while ( treeid.IsOk() && !done )
1023 {
1024 CollapseDir(treeid);
1025
1026 treeid = FindChild(treeid, path, done);
1027
1028 if ( treeid.IsOk() )
1029 lastId = treeid;
1030 }
1031
1032 if ( !lastId.IsOk() )
1033 return false;
1034
1035 m_treeCtrl->SelectItem(lastId);
1036 m_treeCtrl->EnsureVisible(lastId);
1037
1038 return true;
1039 }
1040
1041 wxString wxGenericDirCtrl::GetPath(wxTreeItemId itemId) const
1042 {
1043 const wxDirItemData*
1044 data = static_cast<wxDirItemData*>(m_treeCtrl->GetItemData(itemId));
1045
1046 return data->m_path;
1047 }
1048
1049 wxString wxGenericDirCtrl::GetPath() const
1050 {
1051 // Allow calling GetPath() in multiple selection from OnSelFilter
1052 if (m_treeCtrl->HasFlag(wxTR_MULTIPLE))
1053 {
1054 wxArrayTreeItemIds items;
1055 m_treeCtrl->GetSelections(items);
1056 if (items.size() > 0)
1057 {
1058 // return first string only
1059 wxTreeItemId treeid = items[0];
1060 return GetPath(treeid);
1061 }
1062
1063 return wxEmptyString;
1064 }
1065
1066 wxTreeItemId treeid = m_treeCtrl->GetSelection();
1067 if (treeid)
1068 {
1069 return GetPath(treeid);
1070 }
1071 else
1072 return wxEmptyString;
1073 }
1074
1075 void wxGenericDirCtrl::GetPaths(wxArrayString& paths) const
1076 {
1077 paths.clear();
1078
1079 wxArrayTreeItemIds items;
1080 m_treeCtrl->GetSelections(items);
1081 for ( unsigned n = 0; n < items.size(); n++ )
1082 {
1083 wxTreeItemId treeid = items[n];
1084 paths.push_back(GetPath(treeid));
1085 }
1086 }
1087
1088 wxString wxGenericDirCtrl::GetFilePath() const
1089 {
1090 wxTreeItemId treeid = m_treeCtrl->GetSelection();
1091 if (treeid)
1092 {
1093 wxDirItemData* data = (wxDirItemData*) m_treeCtrl->GetItemData(treeid);
1094 if (data->m_isDir)
1095 return wxEmptyString;
1096 else
1097 return data->m_path;
1098 }
1099 else
1100 return wxEmptyString;
1101 }
1102
1103 void wxGenericDirCtrl::GetFilePaths(wxArrayString& paths) const
1104 {
1105 paths.clear();
1106
1107 wxArrayTreeItemIds items;
1108 m_treeCtrl->GetSelections(items);
1109 for ( unsigned n = 0; n < items.size(); n++ )
1110 {
1111 wxTreeItemId treeid = items[n];
1112 wxDirItemData* data = (wxDirItemData*) m_treeCtrl->GetItemData(treeid);
1113 if ( !data->m_isDir )
1114 paths.Add(data->m_path);
1115 }
1116 }
1117
1118 void wxGenericDirCtrl::SetPath(const wxString& path)
1119 {
1120 m_defaultPath = path;
1121 if (m_rootId)
1122 ExpandPath(path);
1123 }
1124
1125 void wxGenericDirCtrl::SelectPath(const wxString& path, bool select)
1126 {
1127 bool done = false;
1128 wxTreeItemId treeid = FindChild(m_rootId, path, done);
1129 wxTreeItemId lastId = treeid; // The last non-zero treeid
1130 while ( treeid.IsOk() && !done )
1131 {
1132 treeid = FindChild(treeid, path, done);
1133 if ( treeid.IsOk() )
1134 lastId = treeid;
1135 }
1136 if ( !lastId.IsOk() )
1137 return;
1138
1139 if ( done )
1140 {
1141 m_treeCtrl->SelectItem(treeid, select);
1142 }
1143 }
1144
1145 void wxGenericDirCtrl::SelectPaths(const wxArrayString& paths)
1146 {
1147 if ( HasFlag(wxDIRCTRL_MULTIPLE) )
1148 {
1149 UnselectAll();
1150 for ( unsigned n = 0; n < paths.size(); n++ )
1151 {
1152 SelectPath(paths[n]);
1153 }
1154 }
1155 }
1156
1157 void wxGenericDirCtrl::UnselectAll()
1158 {
1159 m_treeCtrl->UnselectAll();
1160 }
1161
1162 // Not used
1163 #if 0
1164 void wxGenericDirCtrl::FindChildFiles(wxTreeItemId treeid, int dirFlags, wxArrayString& filenames)
1165 {
1166 wxDirItemData *data = (wxDirItemData *) m_treeCtrl->GetItemData(treeid);
1167
1168 // This may take a longish time. Go to busy cursor
1169 wxBusyCursor busy;
1170
1171 wxASSERT(data);
1172
1173 wxString search,path,filename;
1174
1175 wxString dirName(data->m_path);
1176
1177 #if defined(__WINDOWS__) || defined(__OS2__)
1178 if (dirName.Last() == ':')
1179 dirName += wxString(wxFILE_SEP_PATH);
1180 #endif
1181
1182 wxDir d;
1183 wxString eachFilename;
1184
1185 wxLogNull log;
1186 d.Open(dirName);
1187
1188 if (d.IsOpened())
1189 {
1190 if (d.GetFirst(& eachFilename, m_currentFilterStr, dirFlags))
1191 {
1192 do
1193 {
1194 if ((eachFilename != wxT(".")) && (eachFilename != wxT("..")))
1195 {
1196 filenames.Add(eachFilename);
1197 }
1198 }
1199 while (d.GetNext(& eachFilename)) ;
1200 }
1201 }
1202 }
1203 #endif
1204
1205 void wxGenericDirCtrl::SetFilterIndex(int n)
1206 {
1207 m_currentFilter = n;
1208
1209 wxString f, d;
1210 if (ExtractWildcard(m_filter, n, f, d))
1211 m_currentFilterStr = f;
1212 else
1213 #ifdef __UNIX__
1214 m_currentFilterStr = wxT("*");
1215 #else
1216 m_currentFilterStr = wxT("*.*");
1217 #endif
1218 }
1219
1220 void wxGenericDirCtrl::SetFilter(const wxString& filter)
1221 {
1222 m_filter = filter;
1223
1224 if (!filter.empty() && !m_filterListCtrl)
1225 m_filterListCtrl = new wxDirFilterListCtrl(this, wxID_FILTERLISTCTRL);
1226 else if (filter.empty() && m_filterListCtrl)
1227 {
1228 m_filterListCtrl->Destroy();
1229 m_filterListCtrl = NULL;
1230 }
1231
1232 wxString f, d;
1233 if (ExtractWildcard(m_filter, m_currentFilter, f, d))
1234 m_currentFilterStr = f;
1235 else
1236 #ifdef __UNIX__
1237 m_currentFilterStr = wxT("*");
1238 #else
1239 m_currentFilterStr = wxT("*.*");
1240 #endif
1241 // current filter index is meaningless after filter change, set it to zero
1242 SetFilterIndex(0);
1243 if (m_filterListCtrl)
1244 m_filterListCtrl->FillFilterList(m_filter, 0);
1245 }
1246
1247 // Extract description and actual filter from overall filter string
1248 bool wxGenericDirCtrl::ExtractWildcard(const wxString& filterStr, int n, wxString& filter, wxString& description)
1249 {
1250 wxArrayString filters, descriptions;
1251 int count = wxParseCommonDialogsFilter(filterStr, descriptions, filters);
1252 if (count > 0 && n < count)
1253 {
1254 filter = filters[n];
1255 description = descriptions[n];
1256 return true;
1257 }
1258
1259 return false;
1260 }
1261
1262
1263 void wxGenericDirCtrl::DoResize()
1264 {
1265 wxSize sz = GetClientSize();
1266 int verticalSpacing = 3;
1267 if (m_treeCtrl)
1268 {
1269 wxSize filterSz ;
1270 if (m_filterListCtrl)
1271 {
1272 filterSz = m_filterListCtrl->GetSize();
1273 sz.y -= (filterSz.y + verticalSpacing);
1274 }
1275 m_treeCtrl->SetSize(0, 0, sz.x, sz.y);
1276 if (m_filterListCtrl)
1277 {
1278 m_filterListCtrl->SetSize(0, sz.y + verticalSpacing, sz.x, filterSz.y);
1279 // Don't know why, but this needs refreshing after a resize (wxMSW)
1280 m_filterListCtrl->Refresh();
1281 }
1282 }
1283 }
1284
1285
1286 void wxGenericDirCtrl::OnSize(wxSizeEvent& WXUNUSED(event))
1287 {
1288 DoResize();
1289 }
1290
1291 wxTreeItemId wxGenericDirCtrl::AppendItem (const wxTreeItemId & parent,
1292 const wxString & text,
1293 int image, int selectedImage,
1294 wxTreeItemData * data)
1295 {
1296 wxTreeCtrl *treeCtrl = GetTreeCtrl ();
1297
1298 wxASSERT (treeCtrl);
1299
1300 if (treeCtrl)
1301 {
1302 return treeCtrl->AppendItem (parent, text, image, selectedImage, data);
1303 }
1304 else
1305 {
1306 return wxTreeItemId();
1307 }
1308 }
1309
1310
1311 //-----------------------------------------------------------------------------
1312 // wxDirFilterListCtrl
1313 //-----------------------------------------------------------------------------
1314
1315 IMPLEMENT_CLASS(wxDirFilterListCtrl, wxChoice)
1316
1317 BEGIN_EVENT_TABLE(wxDirFilterListCtrl, wxChoice)
1318 EVT_CHOICE(wxID_ANY, wxDirFilterListCtrl::OnSelFilter)
1319 END_EVENT_TABLE()
1320
1321 bool wxDirFilterListCtrl::Create(wxGenericDirCtrl* parent,
1322 const wxWindowID treeid,
1323 const wxPoint& pos,
1324 const wxSize& size,
1325 long style)
1326 {
1327 m_dirCtrl = parent;
1328
1329 // by default our border style is determined by the style of our parent
1330 if ( !(style & wxBORDER_MASK) )
1331 {
1332 style |= parent->HasFlag(wxDIRCTRL_3D_INTERNAL) ? wxBORDER_SUNKEN
1333 : wxBORDER_NONE;
1334 }
1335
1336 return wxChoice::Create(parent, treeid, pos, size, 0, NULL, style);
1337 }
1338
1339 void wxDirFilterListCtrl::Init()
1340 {
1341 m_dirCtrl = NULL;
1342 }
1343
1344 void wxDirFilterListCtrl::OnSelFilter(wxCommandEvent& WXUNUSED(event))
1345 {
1346 int sel = GetSelection();
1347
1348 if (m_dirCtrl->HasFlag(wxDIRCTRL_MULTIPLE))
1349 {
1350 wxArrayString paths;
1351 m_dirCtrl->GetPaths(paths);
1352
1353 m_dirCtrl->SetFilterIndex(sel);
1354
1355 // If the filter has changed, the view is out of date, so
1356 // collapse the tree.
1357 m_dirCtrl->ReCreateTree();
1358
1359 // Expand and select the previously selected paths
1360 for (unsigned int i = 0; i < paths.GetCount(); i++)
1361 {
1362 m_dirCtrl->ExpandPath(paths.Item(i));
1363 }
1364 }
1365 else
1366 {
1367 wxString currentPath = m_dirCtrl->GetPath();
1368
1369 m_dirCtrl->SetFilterIndex(sel);
1370 m_dirCtrl->ReCreateTree();
1371
1372 // Try to restore the selection, or at least the directory
1373 m_dirCtrl->ExpandPath(currentPath);
1374 }
1375 }
1376
1377 void wxDirFilterListCtrl::FillFilterList(const wxString& filter, int defaultFilter)
1378 {
1379 Clear();
1380 wxArrayString descriptions, filters;
1381 size_t n = (size_t) wxParseCommonDialogsFilter(filter, descriptions, filters);
1382
1383 if (n > 0 && defaultFilter < (int) n)
1384 {
1385 for (size_t i = 0; i < n; i++)
1386 Append(descriptions[i]);
1387 SetSelection(defaultFilter);
1388 }
1389 }
1390 #endif // wxUSE_DIRDLG
1391
1392 #if wxUSE_DIRDLG || wxUSE_FILEDLG
1393
1394 // ----------------------------------------------------------------------------
1395 // wxFileIconsTable icons
1396 // ----------------------------------------------------------------------------
1397
1398 #ifndef __WXGTK20__
1399 /* Computer (c) Julian Smart */
1400 static const char* const file_icons_tbl_computer_xpm[] = {
1401 /* columns rows colors chars-per-pixel */
1402 "16 16 42 1",
1403 "r c #4E7FD0",
1404 "$ c #7198D9",
1405 "; c #DCE6F6",
1406 "q c #FFFFFF",
1407 "u c #4A7CCE",
1408 "# c #779DDB",
1409 "w c #95B2E3",
1410 "y c #7FA2DD",
1411 "f c #3263B4",
1412 "= c #EAF0FA",
1413 "< c #B1C7EB",
1414 "% c #6992D7",
1415 "9 c #D9E4F5",
1416 "o c #9BB7E5",
1417 "6 c #F7F9FD",
1418 ", c #BED0EE",
1419 "3 c #F0F5FC",
1420 "1 c #A8C0E8",
1421 " c None",
1422 "0 c #FDFEFF",
1423 "4 c #C4D5F0",
1424 "@ c #81A4DD",
1425 "e c #4377CD",
1426 "- c #E2EAF8",
1427 "i c #9FB9E5",
1428 "> c #CCDAF2",
1429 "+ c #89A9DF",
1430 "s c #5584D1",
1431 "t c #5D89D3",
1432 ": c #D2DFF4",
1433 "5 c #FAFCFE",
1434 "2 c #F5F8FD",
1435 "8 c #DFE8F7",
1436 "& c #5E8AD4",
1437 "X c #638ED5",
1438 "a c #CEDCF2",
1439 "p c #90AFE2",
1440 "d c #2F5DA9",
1441 "* c #5282D0",
1442 "7 c #E5EDF9",
1443 ". c #A2BCE6",
1444 "O c #8CACE0",
1445 /* pixels */
1446 " ",
1447 " .XXXXXXXXXXX ",
1448 " oXO++@#$%&*X ",
1449 " oX=-;:>,<1%X ",
1450 " oX23=-;:4,$X ",
1451 " oX5633789:@X ",
1452 " oX05623=78+X ",
1453 " oXqq05623=OX ",
1454 " oX,,,,,<<<$X ",
1455 " wXXXXXXXXXXe ",
1456 " XrtX%$$y@+O,, ",
1457 " uyiiiiiiiii@< ",
1458 " ouiiiiiiiiiip<a",
1459 " rustX%$$y@+Ow,,",
1460 " dfffffffffffffd",
1461 " "
1462 };
1463 #endif // !GTK+ 2
1464
1465 // ----------------------------------------------------------------------------
1466 // wxFileIconsTable & friends
1467 // ----------------------------------------------------------------------------
1468
1469 // global instance of a wxFileIconsTable
1470 wxFileIconsTable* wxTheFileIconsTable = NULL;
1471
1472 // A module to allow icons table cleanup
1473
1474 class wxFileIconsTableModule: public wxModule
1475 {
1476 DECLARE_DYNAMIC_CLASS(wxFileIconsTableModule)
1477 public:
1478 wxFileIconsTableModule() {}
1479 bool OnInit() { wxTheFileIconsTable = new wxFileIconsTable; return true; }
1480 void OnExit()
1481 {
1482 wxDELETE(wxTheFileIconsTable);
1483 }
1484 };
1485
1486 IMPLEMENT_DYNAMIC_CLASS(wxFileIconsTableModule, wxModule)
1487
1488 class wxFileIconEntry : public wxObject
1489 {
1490 public:
1491 wxFileIconEntry(int i) { iconid = i; }
1492
1493 int iconid;
1494 };
1495
1496 wxFileIconsTable::wxFileIconsTable()
1497 {
1498 m_HashTable = NULL;
1499 m_smallImageList = NULL;
1500 }
1501
1502 wxFileIconsTable::~wxFileIconsTable()
1503 {
1504 if (m_HashTable)
1505 {
1506 WX_CLEAR_HASH_TABLE(*m_HashTable);
1507 delete m_HashTable;
1508 }
1509 if (m_smallImageList) delete m_smallImageList;
1510 }
1511
1512 // delayed initialization - wait until first use (wxArtProv not created yet)
1513 void wxFileIconsTable::Create()
1514 {
1515 wxCHECK_RET(!m_smallImageList && !m_HashTable, wxT("creating icons twice"));
1516 m_HashTable = new wxHashTable(wxKEY_STRING);
1517 m_smallImageList = new wxImageList(16, 16);
1518
1519 // folder:
1520 m_smallImageList->Add(wxArtProvider::GetBitmap(wxART_FOLDER,
1521 wxART_CMN_DIALOG,
1522 wxSize(16, 16)));
1523 // folder_open
1524 m_smallImageList->Add(wxArtProvider::GetBitmap(wxART_FOLDER_OPEN,
1525 wxART_CMN_DIALOG,
1526 wxSize(16, 16)));
1527 // computer
1528 #ifdef __WXGTK20__
1529 // GTK24 uses this icon in the file open dialog
1530 m_smallImageList->Add(wxArtProvider::GetBitmap(wxART_HARDDISK,
1531 wxART_CMN_DIALOG,
1532 wxSize(16, 16)));
1533 #else
1534 m_smallImageList->Add(wxIcon(file_icons_tbl_computer_xpm));
1535 #endif
1536 // drive
1537 m_smallImageList->Add(wxArtProvider::GetBitmap(wxART_HARDDISK,
1538 wxART_CMN_DIALOG,
1539 wxSize(16, 16)));
1540 // cdrom
1541 m_smallImageList->Add(wxArtProvider::GetBitmap(wxART_CDROM,
1542 wxART_CMN_DIALOG,
1543 wxSize(16, 16)));
1544 // floppy
1545 m_smallImageList->Add(wxArtProvider::GetBitmap(wxART_FLOPPY,
1546 wxART_CMN_DIALOG,
1547 wxSize(16, 16)));
1548 // removeable
1549 m_smallImageList->Add(wxArtProvider::GetBitmap(wxART_REMOVABLE,
1550 wxART_CMN_DIALOG,
1551 wxSize(16, 16)));
1552 // file
1553 m_smallImageList->Add(wxArtProvider::GetBitmap(wxART_NORMAL_FILE,
1554 wxART_CMN_DIALOG,
1555 wxSize(16, 16)));
1556 // executable
1557 if (GetIconID(wxEmptyString, wxT("application/x-executable")) == file)
1558 {
1559 m_smallImageList->Add(wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE,
1560 wxART_CMN_DIALOG,
1561 wxSize(16, 16)));
1562 delete m_HashTable->Get(wxT("exe"));
1563 m_HashTable->Delete(wxT("exe"));
1564 m_HashTable->Put(wxT("exe"), new wxFileIconEntry(executable));
1565 }
1566 /* else put into list by GetIconID
1567 (KDE defines application/x-executable for *.exe and has nice icon)
1568 */
1569 }
1570
1571 wxImageList *wxFileIconsTable::GetSmallImageList()
1572 {
1573 if (!m_smallImageList)
1574 Create();
1575
1576 return m_smallImageList;
1577 }
1578
1579 #if wxUSE_MIMETYPE && wxUSE_IMAGE && (!defined(__WINDOWS__) || wxUSE_WXDIB)
1580 // VS: we don't need this function w/o wxMimeTypesManager because we'll only have
1581 // one icon and we won't resize it
1582
1583 static wxBitmap CreateAntialiasedBitmap(const wxImage& img)
1584 {
1585 const unsigned int size = 16;
1586
1587 wxImage smallimg (size, size);
1588 unsigned char *p1, *p2, *ps;
1589 unsigned char mr = img.GetMaskRed(),
1590 mg = img.GetMaskGreen(),
1591 mb = img.GetMaskBlue();
1592
1593 unsigned x, y;
1594 unsigned sr, sg, sb, smask;
1595
1596 p1 = img.GetData(), p2 = img.GetData() + 3 * size*2, ps = smallimg.GetData();
1597 smallimg.SetMaskColour(mr, mr, mr);
1598
1599 for (y = 0; y < size; y++)
1600 {
1601 for (x = 0; x < size; x++)
1602 {
1603 sr = sg = sb = smask = 0;
1604 if (p1[0] != mr || p1[1] != mg || p1[2] != mb)
1605 sr += p1[0], sg += p1[1], sb += p1[2];
1606 else smask++;
1607 p1 += 3;
1608 if (p1[0] != mr || p1[1] != mg || p1[2] != mb)
1609 sr += p1[0], sg += p1[1], sb += p1[2];
1610 else smask++;
1611 p1 += 3;
1612 if (p2[0] != mr || p2[1] != mg || p2[2] != mb)
1613 sr += p2[0], sg += p2[1], sb += p2[2];
1614 else smask++;
1615 p2 += 3;
1616 if (p2[0] != mr || p2[1] != mg || p2[2] != mb)
1617 sr += p2[0], sg += p2[1], sb += p2[2];
1618 else smask++;
1619 p2 += 3;
1620
1621 if (smask > 2)
1622 ps[0] = ps[1] = ps[2] = mr;
1623 else
1624 {
1625 ps[0] = (unsigned char)(sr >> 2);
1626 ps[1] = (unsigned char)(sg >> 2);
1627 ps[2] = (unsigned char)(sb >> 2);
1628 }
1629 ps += 3;
1630 }
1631 p1 += size*2 * 3, p2 += size*2 * 3;
1632 }
1633
1634 return wxBitmap(smallimg);
1635 }
1636
1637 // This function is currently not unused anymore
1638 #if 0
1639 // finds empty borders and return non-empty area of image:
1640 static wxImage CutEmptyBorders(const wxImage& img)
1641 {
1642 unsigned char mr = img.GetMaskRed(),
1643 mg = img.GetMaskGreen(),
1644 mb = img.GetMaskBlue();
1645 unsigned char *dt = img.GetData(), *dttmp;
1646 unsigned w = img.GetWidth(), h = img.GetHeight();
1647
1648 unsigned top, bottom, left, right, i;
1649 bool empt;
1650
1651 #define MK_DTTMP(x,y) dttmp = dt + ((x + y * w) * 3)
1652 #define NOEMPTY_PIX(empt) if (dttmp[0] != mr || dttmp[1] != mg || dttmp[2] != mb) {empt = false; break;}
1653
1654 for (empt = true, top = 0; empt && top < h; top++)
1655 {
1656 MK_DTTMP(0, top);
1657 for (i = 0; i < w; i++, dttmp+=3)
1658 NOEMPTY_PIX(empt)
1659 }
1660 for (empt = true, bottom = h-1; empt && bottom > top; bottom--)
1661 {
1662 MK_DTTMP(0, bottom);
1663 for (i = 0; i < w; i++, dttmp+=3)
1664 NOEMPTY_PIX(empt)
1665 }
1666 for (empt = true, left = 0; empt && left < w; left++)
1667 {
1668 MK_DTTMP(left, 0);
1669 for (i = 0; i < h; i++, dttmp+=3*w)
1670 NOEMPTY_PIX(empt)
1671 }
1672 for (empt = true, right = w-1; empt && right > left; right--)
1673 {
1674 MK_DTTMP(right, 0);
1675 for (i = 0; i < h; i++, dttmp+=3*w)
1676 NOEMPTY_PIX(empt)
1677 }
1678 top--, left--, bottom++, right++;
1679
1680 return img.GetSubImage(wxRect(left, top, right - left + 1, bottom - top + 1));
1681 }
1682 #endif // #if 0
1683
1684 #endif // wxUSE_MIMETYPE
1685
1686 int wxFileIconsTable::GetIconID(const wxString& extension, const wxString& mime)
1687 {
1688 if (!m_smallImageList)
1689 Create();
1690
1691 #if wxUSE_MIMETYPE
1692 if (!extension.empty())
1693 {
1694 wxFileIconEntry *entry = (wxFileIconEntry*) m_HashTable->Get(extension);
1695 if (entry) return (entry -> iconid);
1696 }
1697
1698 wxFileType *ft = (mime.empty()) ?
1699 wxTheMimeTypesManager -> GetFileTypeFromExtension(extension) :
1700 wxTheMimeTypesManager -> GetFileTypeFromMimeType(mime);
1701
1702 wxIconLocation iconLoc;
1703 wxIcon ic;
1704
1705 {
1706 wxLogNull logNull;
1707 if ( ft && ft->GetIcon(&iconLoc) )
1708 {
1709 ic = wxIcon( iconLoc );
1710 }
1711 }
1712
1713 delete ft;
1714
1715 if ( !ic.IsOk() )
1716 {
1717 int newid = file;
1718 m_HashTable->Put(extension, new wxFileIconEntry(newid));
1719 return newid;
1720 }
1721
1722 wxBitmap bmp;
1723 bmp.CopyFromIcon(ic);
1724
1725 if ( !bmp.IsOk() )
1726 {
1727 int newid = file;
1728 m_HashTable->Put(extension, new wxFileIconEntry(newid));
1729 return newid;
1730 }
1731
1732 const unsigned int size = 16;
1733
1734 int treeid = m_smallImageList->GetImageCount();
1735 if ((bmp.GetWidth() == (int) size) && (bmp.GetHeight() == (int) size))
1736 {
1737 m_smallImageList->Add(bmp);
1738 }
1739 #if wxUSE_IMAGE && (!defined(__WINDOWS__) || wxUSE_WXDIB)
1740 else
1741 {
1742 wxImage img = bmp.ConvertToImage();
1743
1744 if ((img.GetWidth() != size*2) || (img.GetHeight() != size*2))
1745 // m_smallImageList->Add(CreateAntialiasedBitmap(CutEmptyBorders(img).Rescale(size*2, size*2)));
1746 m_smallImageList->Add(CreateAntialiasedBitmap(img.Rescale(size*2, size*2)));
1747 else
1748 m_smallImageList->Add(CreateAntialiasedBitmap(img));
1749 }
1750 #endif // wxUSE_IMAGE
1751
1752 m_HashTable->Put(extension, new wxFileIconEntry(treeid));
1753 return treeid;
1754
1755 #else // !wxUSE_MIMETYPE
1756
1757 wxUnusedVar(mime);
1758 if (extension == wxT("exe"))
1759 return executable;
1760 else
1761 return file;
1762 #endif // wxUSE_MIMETYPE/!wxUSE_MIMETYPE
1763 }
1764
1765 #endif // wxUSE_DIRDLG || wxUSE_FILEDLG