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