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