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