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