1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/xrc/xmlres.cpp
3 // Purpose: XRC resources
4 // Author: Vaclav Slavik
7 // Copyright: (c) 2000 Vaclav Slavik
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
11 // For compilers that support precompilation, includes "wx.h".
12 #include "wx/wxprec.h"
20 #include "wx/xrc/xmlres.h"
27 #include "wx/dialog.h"
28 #include "wx/settings.h"
29 #include "wx/bitmap.h"
31 #include "wx/module.h"
32 #include "wx/wxcrtvararg.h"
39 #include "wx/vector.h"
40 #include "wx/wfstream.h"
41 #include "wx/filesys.h"
42 #include "wx/filename.h"
43 #include "wx/tokenzr.h"
44 #include "wx/fontenum.h"
45 #include "wx/fontmap.h"
46 #include "wx/artprov.h"
47 #include "wx/imaglist.h"
49 #include "wx/xml/xml.h"
50 #include "wx/hashset.h"
51 #include "wx/scopedptr.h"
56 // Helper function to get modification time of either a wxFileSystem URI or
57 // just a normal file name, depending on the build.
60 wxDateTime
GetXRCFileModTime(const wxString
& filename
)
64 wxScopedPtr
<wxFSFile
> file(fsys
.OpenFile(filename
));
66 return file
? file
->GetModificationTime() : wxDateTime();
67 #else // wxUSE_FILESYSTEM
68 return wxDateTime(wxFileModificationTime(filename
));
69 #endif // wxUSE_FILESYSTEM
72 #endif // wxUSE_DATETIME
74 } // anonymous namespace
76 class wxXmlResourceDataRecord
79 // Ctor takes ownership of the document pointer.
80 wxXmlResourceDataRecord(const wxString
& File_
,
83 : File(File_
), Doc(Doc_
)
86 Time
= GetXRCFileModTime(File
);
90 ~wxXmlResourceDataRecord() {delete Doc
;}
98 wxDECLARE_NO_COPY_CLASS(wxXmlResourceDataRecord
);
101 class wxXmlResourceDataRecords
: public wxVector
<wxXmlResourceDataRecord
*>
103 // this is a class so that it can be forward-declared
106 WX_DECLARE_HASH_SET(int, wxIntegerHash
, wxIntegerEqual
, wxHashSetInt
);
108 class wxIdRange
// Holds data for a particular rangename
111 wxIdRange(const wxXmlNode
* node
,
112 const wxString
& rname
,
113 const wxString
& startno
,
114 const wxString
& rsize
);
116 // Note the existence of an item within the range
117 void NoteItem(const wxXmlNode
* node
, const wxString
& item
);
119 // The manager is telling us that it's finished adding items
120 void Finalise(const wxXmlNode
* node
);
122 wxString
GetName() const { return m_name
; }
123 bool IsFinalised() const { return m_finalised
; }
125 const wxString m_name
;
129 bool m_item_end_found
;
131 wxHashSetInt m_indices
;
133 friend class wxIdRangeManager
;
136 class wxIdRangeManager
140 // Gets the global resources object or creates one if none exists.
141 static wxIdRangeManager
*Get();
143 // Sets the global resources object and returns a pointer to the previous
144 // one (may be NULL).
145 static wxIdRangeManager
*Set(wxIdRangeManager
*res
);
147 // Create a new IDrange from this node
148 void AddRange(const wxXmlNode
* node
);
149 // Tell the IdRange that this item exists, and should be pre-allocated an ID
150 void NotifyRangeOfItem(const wxXmlNode
* node
, const wxString
& item
) const;
151 // Tells all IDranges that they're now complete, and can create their IDs
152 void FinaliseRanges(const wxXmlNode
* node
) const;
153 // Searches for a known IdRange matching 'name', returning its index or -1
154 int Find(const wxString
& rangename
) const;
155 // Removes, if it exists, an entry from the XRCID table. Used in id-ranges
156 // to replace defunct or statically-initialised entries with current values
157 static void RemoveXRCIDEntry(const wxString
& idstr
);
160 wxIdRange
* FindRangeForItem(const wxXmlNode
* node
,
161 const wxString
& item
,
162 wxString
& value
) const;
163 wxVector
<wxIdRange
*> m_IdRanges
;
166 static wxIdRangeManager
*ms_instance
;
172 // helper used by DoFindResource() and elsewhere: returns true if this is an
173 // object or object_ref node
175 // node must be non-NULL
176 inline bool IsObjectNode(wxXmlNode
*node
)
178 return node
->GetType() == wxXML_ELEMENT_NODE
&&
179 (node
->GetName() == wxS("object") ||
180 node
->GetName() == wxS("object_ref"));
183 // special XML attribute with name of input file, see GetFileNameFromNode()
184 const char *ATTR_INPUT_FILENAME
= "__wx:filename";
186 // helper to get filename corresponding to an XML node
188 GetFileNameFromNode(const wxXmlNode
*node
, const wxXmlResourceDataRecords
& files
)
190 // this loop does two things: it looks for ATTR_INPUT_FILENAME among
191 // parents and if it isn't used, it finds the root of the XML tree 'node'
195 // in some rare cases (specifically, when an <object_ref> is used, see
196 // wxXmlResource::CreateResFromNode() and MergeNodesOver()), we work
197 // with XML nodes that are not rooted in any document from 'files'
198 // (because a new node was created by CreateResFromNode() to merge the
199 // content of <object_ref> and the referenced <object>); in that case,
200 // we hack around the problem by putting the information about input
201 // file into a custom attribute
202 if ( node
->HasAttribute(ATTR_INPUT_FILENAME
) )
203 return node
->GetAttribute(ATTR_INPUT_FILENAME
);
205 if ( !node
->GetParent() )
206 break; // we found the root of this XML tree
208 node
= node
->GetParent();
211 // NB: 'node' now points to the root of XML document
213 for ( wxXmlResourceDataRecords::const_iterator i
= files
.begin();
214 i
!= files
.end(); ++i
)
216 if ( (*i
)->Doc
->GetRoot() == node
)
222 return wxEmptyString
; // not found
225 } // anonymous namespace
228 wxXmlResource
*wxXmlResource::ms_instance
= NULL
;
230 /*static*/ wxXmlResource
*wxXmlResource::Get()
233 ms_instance
= new wxXmlResource
;
237 /*static*/ wxXmlResource
*wxXmlResource::Set(wxXmlResource
*res
)
239 wxXmlResource
*old
= ms_instance
;
244 wxXmlResource::wxXmlResource(int flags
, const wxString
& domain
)
248 m_data
= new wxXmlResourceDataRecords
;
252 wxXmlResource::wxXmlResource(const wxString
& filemask
, int flags
, const wxString
& domain
)
256 m_data
= new wxXmlResourceDataRecords
;
261 wxXmlResource::~wxXmlResource()
265 for ( wxXmlResourceDataRecords::iterator i
= m_data
->begin();
266 i
!= m_data
->end(); ++i
)
273 void wxXmlResource::SetDomain(const wxString
& domain
)
280 wxString
wxXmlResource::ConvertFileNameToURL(const wxString
& filename
)
282 wxString
fnd(filename
);
284 // NB: as Load() and Unload() accept both filenames and URLs (should
285 // probably be changed to filenames only, but embedded resources
286 // currently rely on its ability to handle URLs - FIXME) we need to
287 // determine whether found name is filename and not URL and this is the
288 // fastest/simplest way to do it
289 if (wxFileName::FileExists(fnd
))
291 // Make the name absolute filename, because the app may
292 // change working directory later:
297 fnd
= fn
.GetFullPath();
300 fnd
= wxFileSystem::FileNameToURL(fnd
);
310 bool wxXmlResource::IsArchive(const wxString
& filename
)
312 const wxString fnd
= filename
.Lower();
314 return fnd
.Matches(wxT("*.zip")) || fnd
.Matches(wxT("*.xrs"));
317 #endif // wxUSE_FILESYSTEM
319 bool wxXmlResource::LoadFile(const wxFileName
& file
)
322 return Load(wxFileSystem::FileNameToURL(file
));
324 return Load(file
.GetFullPath());
328 bool wxXmlResource::LoadAllFiles(const wxString
& dirname
)
333 wxDir::GetAllFiles(dirname
, &files
, "*.xrc");
335 for ( wxArrayString::const_iterator i
= files
.begin(); i
!= files
.end(); ++i
)
344 bool wxXmlResource::Load(const wxString
& filemask_
)
346 wxString filemask
= ConvertFileNameToURL(filemask_
);
352 # define wxXmlFindFirst fsys.FindFirst(filemask, wxFILE)
353 # define wxXmlFindNext fsys.FindNext()
355 # define wxXmlFindFirst wxFindFirstFile(filemask, wxFILE)
356 # define wxXmlFindNext wxFindNextFile()
358 wxString fnd
= wxXmlFindFirst
;
361 wxLogError(_("Cannot load resources from '%s'."), filemask
);
368 if ( IsArchive(fnd
) )
370 if ( !Load(fnd
+ wxT("#zip:*.xrc")) )
373 else // a single resource URL
374 #endif // wxUSE_FILESYSTEM
376 wxXmlDocument
* const doc
= DoLoadFile(fnd
);
380 Data().push_back(new wxXmlResourceDataRecord(fnd
, doc
));
385 # undef wxXmlFindFirst
386 # undef wxXmlFindNext
391 bool wxXmlResource::Unload(const wxString
& filename
)
393 wxASSERT_MSG( !wxIsWild(filename
),
394 wxT("wildcards not supported by wxXmlResource::Unload()") );
396 wxString fnd
= ConvertFileNameToURL(filename
);
398 const bool isArchive
= IsArchive(fnd
);
401 #endif // wxUSE_FILESYSTEM
403 bool unloaded
= false;
404 for ( wxXmlResourceDataRecords::iterator i
= Data().begin();
405 i
!= Data().end(); ++i
)
410 if ( (*i
)->File
.StartsWith(fnd
) )
412 // don't break from the loop, we can have other matching files
414 else // a single resource URL
415 #endif // wxUSE_FILESYSTEM
417 if ( (*i
)->File
== fnd
)
423 // no sense in continuing, there is only one file with this URL
433 IMPLEMENT_ABSTRACT_CLASS(wxXmlResourceHandler
, wxObject
)
435 void wxXmlResource::AddHandler(wxXmlResourceHandler
*handler
)
437 m_handlers
.push_back(handler
);
438 handler
->SetParentResource(this);
441 void wxXmlResource::InsertHandler(wxXmlResourceHandler
*handler
)
443 m_handlers
.insert(m_handlers
.begin(), handler
);
444 handler
->SetParentResource(this);
449 void wxXmlResource::ClearHandlers()
451 for ( wxVector
<wxXmlResourceHandler
*>::iterator i
= m_handlers
.begin();
452 i
!= m_handlers
.end(); ++i
)
458 wxMenu
*wxXmlResource::LoadMenu(const wxString
& name
)
460 return (wxMenu
*)CreateResFromNode(FindResource(name
, wxT("wxMenu")), NULL
, NULL
);
465 wxMenuBar
*wxXmlResource::LoadMenuBar(wxWindow
*parent
, const wxString
& name
)
467 return (wxMenuBar
*)CreateResFromNode(FindResource(name
, wxT("wxMenuBar")), parent
, NULL
);
473 wxToolBar
*wxXmlResource::LoadToolBar(wxWindow
*parent
, const wxString
& name
)
475 return (wxToolBar
*)CreateResFromNode(FindResource(name
, wxT("wxToolBar")), parent
, NULL
);
480 wxDialog
*wxXmlResource::LoadDialog(wxWindow
*parent
, const wxString
& name
)
482 return (wxDialog
*)CreateResFromNode(FindResource(name
, wxT("wxDialog")), parent
, NULL
);
485 bool wxXmlResource::LoadDialog(wxDialog
*dlg
, wxWindow
*parent
, const wxString
& name
)
487 return CreateResFromNode(FindResource(name
, wxT("wxDialog")), parent
, dlg
) != NULL
;
492 wxPanel
*wxXmlResource::LoadPanel(wxWindow
*parent
, const wxString
& name
)
494 return (wxPanel
*)CreateResFromNode(FindResource(name
, wxT("wxPanel")), parent
, NULL
);
497 bool wxXmlResource::LoadPanel(wxPanel
*panel
, wxWindow
*parent
, const wxString
& name
)
499 return CreateResFromNode(FindResource(name
, wxT("wxPanel")), parent
, panel
) != NULL
;
502 wxFrame
*wxXmlResource::LoadFrame(wxWindow
* parent
, const wxString
& name
)
504 return (wxFrame
*)CreateResFromNode(FindResource(name
, wxT("wxFrame")), parent
, NULL
);
507 bool wxXmlResource::LoadFrame(wxFrame
* frame
, wxWindow
*parent
, const wxString
& name
)
509 return CreateResFromNode(FindResource(name
, wxT("wxFrame")), parent
, frame
) != NULL
;
512 wxBitmap
wxXmlResource::LoadBitmap(const wxString
& name
)
514 wxBitmap
*bmp
= (wxBitmap
*)CreateResFromNode(
515 FindResource(name
, wxT("wxBitmap")), NULL
, NULL
);
518 if (bmp
) { rt
= *bmp
; delete bmp
; }
522 wxIcon
wxXmlResource::LoadIcon(const wxString
& name
)
524 wxIcon
*icon
= (wxIcon
*)CreateResFromNode(
525 FindResource(name
, wxT("wxIcon")), NULL
, NULL
);
528 if (icon
) { rt
= *icon
; delete icon
; }
534 wxXmlResource::DoLoadObject(wxWindow
*parent
,
535 const wxString
& name
,
536 const wxString
& classname
,
539 wxXmlNode
* const node
= FindResource(name
, classname
, recursive
);
541 return node
? DoCreateResFromNode(*node
, parent
, NULL
) : NULL
;
545 wxXmlResource::DoLoadObject(wxObject
*instance
,
547 const wxString
& name
,
548 const wxString
& classname
,
551 wxXmlNode
* const node
= FindResource(name
, classname
, recursive
);
553 return node
&& DoCreateResFromNode(*node
, parent
, instance
) != NULL
;
557 bool wxXmlResource::AttachUnknownControl(const wxString
& name
,
558 wxWindow
*control
, wxWindow
*parent
)
561 parent
= control
->GetParent();
562 wxWindow
*container
= parent
->FindWindow(name
+ wxT("_container"));
565 wxLogError("Cannot find container for unknown control '%s'.", name
);
568 return control
->Reparent(container
);
572 static void ProcessPlatformProperty(wxXmlNode
*node
)
577 wxXmlNode
*c
= node
->GetChildren();
581 if (!c
->GetAttribute(wxT("platform"), &s
))
585 wxStringTokenizer
tkn(s
, wxT(" |"));
587 while (tkn
.HasMoreTokens())
589 s
= tkn
.GetNextToken();
591 if (s
== wxT("win")) isok
= true;
593 #if defined(__MAC__) || defined(__APPLE__)
594 if (s
== wxT("mac")) isok
= true;
595 #elif defined(__UNIX__)
596 if (s
== wxT("unix")) isok
= true;
599 if (s
== wxT("os2")) isok
= true;
609 ProcessPlatformProperty(c
);
614 wxXmlNode
*c2
= c
->GetNext();
615 node
->RemoveChild(c
);
622 static void PreprocessForIdRanges(wxXmlNode
*rootnode
)
624 // First go through the top level, looking for the names of ID ranges
625 // as processing items is a lot easier if names are already known
626 wxXmlNode
*c
= rootnode
->GetChildren();
629 if (c
->GetName() == wxT("ids-range"))
630 wxIdRangeManager::Get()->AddRange(c
);
634 // Next, examine every 'name' for the '[' that denotes an ID in a range
635 c
= rootnode
->GetChildren();
638 wxString name
= c
->GetAttribute(wxT("name"));
639 if (name
.find('[') != wxString::npos
)
640 wxIdRangeManager::Get()->NotifyRangeOfItem(rootnode
, name
);
642 // Do any children by recursion, then proceed to the next sibling
643 PreprocessForIdRanges(c
);
648 bool wxXmlResource::UpdateResources()
652 for ( wxXmlResourceDataRecords::iterator i
= Data().begin();
653 i
!= Data().end(); ++i
)
655 wxXmlResourceDataRecord
* const rec
= *i
;
657 // Check if we need to reload this one.
659 // We never do it if this flag is specified.
660 if ( m_flags
& wxXRC_NO_RELOADING
)
663 // Otherwise check its modification time if we can.
665 const wxDateTime lastModTime
= GetXRCFileModTime(rec
->File
);
667 if ( lastModTime
.IsValid() && lastModTime
<= rec
->Time
)
668 #else // !wxUSE_DATETIME
669 // Never reload the file contents: we can't know whether it changed or
670 // not in this build configuration and it would be unexpected and
671 // counter-productive to get a performance hit (due to constant
672 // reloading of XRC files) in a minimal wx build which is presumably
673 // used because of resource constraints of the current platform.
674 #endif // wxUSE_DATETIME/!wxUSE_DATETIME
676 // No need to reload, the file wasn't modified since we did it
681 wxXmlDocument
* const doc
= DoLoadFile(rec
->File
);
684 // Notice that we keep the old XML document: it seems better to
685 // preserve it instead of throwing it away if we have nothing to
691 // Replace the old resource contents with the new one.
695 // And, now that we loaded it successfully, update the last load time.
697 rec
->Time
= lastModTime
.IsValid() ? lastModTime
: wxDateTime::Now();
698 #endif // wxUSE_DATETIME
704 wxXmlDocument
*wxXmlResource::DoLoadFile(const wxString
& filename
)
706 wxLogTrace(wxT("xrc"), wxT("opening file '%s'"), filename
);
708 wxInputStream
*stream
= NULL
;
712 wxScopedPtr
<wxFSFile
> file(fsys
.OpenFile(filename
));
715 // Notice that we don't have ownership of the stream in this case, it
716 // remains owned by wxFSFile.
717 stream
= file
->GetStream();
719 #else // !wxUSE_FILESYSTEM
720 wxFileInputStream
fstream(filename
);
722 #endif // wxUSE_FILESYSTEM/!wxUSE_FILESYSTEM
724 if ( !stream
|| !stream
->IsOk() )
726 wxLogError(_("Cannot open resources file '%s'."), filename
);
730 wxString
encoding(wxT("UTF-8"));
731 #if !wxUSE_UNICODE && wxUSE_INTL
732 if ( (GetFlags() & wxXRC_USE_LOCALE
) == 0 )
734 // In case we are not using wxLocale to translate strings, convert the
735 // strings GUI's charset. This must not be done when wxXRC_USE_LOCALE
736 // is on, because it could break wxGetTranslation lookup.
737 encoding
= wxLocale::GetSystemEncodingName();
741 wxScopedPtr
<wxXmlDocument
> doc(new wxXmlDocument
);
742 if (!doc
->Load(*stream
, encoding
))
744 wxLogError(_("Cannot load resources from file '%s'."), filename
);
748 wxXmlNode
* const root
= doc
->GetRoot();
749 if (root
->GetName() != wxT("resource"))
754 "invalid XRC resource, doesn't have root node <resource>"
761 wxString verstr
= root
->GetAttribute(wxT("version"), wxT("0.0.0.0"));
762 if (wxSscanf(verstr
, wxT("%i.%i.%i.%i"), &v1
, &v2
, &v3
, &v4
) == 4)
763 version
= v1
*256*256*256+v2
*256*256+v3
*256+v4
;
768 if (m_version
!= version
)
770 wxLogWarning("Resource files must have same version number.");
773 ProcessPlatformProperty(root
);
774 PreprocessForIdRanges(root
);
775 wxIdRangeManager::Get()->FinaliseRanges(root
);
777 return doc
.release();
780 wxXmlNode
*wxXmlResource::DoFindResource(wxXmlNode
*parent
,
781 const wxString
& name
,
782 const wxString
& classname
,
783 bool recursive
) const
787 // first search for match at the top-level nodes (as this is
788 // where the resource is most commonly looked for):
789 for (node
= parent
->GetChildren(); node
; node
= node
->GetNext())
791 if ( IsObjectNode(node
) && node
->GetAttribute(wxS("name")) == name
)
793 // empty class name matches everything
794 if ( classname
.empty() )
797 wxString
cls(node
->GetAttribute(wxS("class")));
799 // object_ref may not have 'class' attribute:
800 if (cls
.empty() && node
->GetName() == wxS("object_ref"))
802 wxString refName
= node
->GetAttribute(wxS("ref"));
806 const wxXmlNode
* const refNode
= GetResourceNode(refName
);
808 cls
= refNode
->GetAttribute(wxS("class"));
811 if ( cls
== classname
)
816 // then recurse in child nodes
819 for (node
= parent
->GetChildren(); node
; node
= node
->GetNext())
821 if ( IsObjectNode(node
) )
823 wxXmlNode
* found
= DoFindResource(node
, name
, classname
, true);
833 wxXmlNode
*wxXmlResource::FindResource(const wxString
& name
,
834 const wxString
& classname
,
839 node
= GetResourceNodeAndLocation(name
, classname
, recursive
, &path
);
848 "XRC resource \"%s\" (class \"%s\") not found",
854 else // node was found
856 // ensure that relative paths work correctly when loading this node
857 // (which should happen as soon as we return as FindResource() result
858 // is always passed to CreateResFromNode())
859 m_curFileSystem
.ChangePathTo(path
);
861 #endif // wxUSE_FILESYSTEM
867 wxXmlResource::GetResourceNodeAndLocation(const wxString
& name
,
868 const wxString
& classname
,
870 wxString
*path
) const
872 // ensure everything is up-to-date: this is needed to support on-demand
873 // reloading of XRC files
874 const_cast<wxXmlResource
*>(this)->UpdateResources();
876 for ( wxXmlResourceDataRecords::const_iterator f
= Data().begin();
877 f
!= Data().end(); ++f
)
879 wxXmlResourceDataRecord
*const rec
= *f
;
880 wxXmlDocument
* const doc
= rec
->Doc
;
881 if ( !doc
|| !doc
->GetRoot() )
885 found
= DoFindResource(doc
->GetRoot(), name
, classname
, recursive
);
898 static void MergeNodesOver(wxXmlNode
& dest
, wxXmlNode
& overwriteWith
,
899 const wxString
& overwriteFilename
)
902 for ( wxXmlAttribute
*attr
= overwriteWith
.GetAttributes();
903 attr
; attr
= attr
->GetNext() )
905 wxXmlAttribute
*dattr
;
906 for (dattr
= dest
.GetAttributes(); dattr
; dattr
= dattr
->GetNext())
909 if ( dattr
->GetName() == attr
->GetName() )
911 dattr
->SetValue(attr
->GetValue());
917 dest
.AddAttribute(attr
->GetName(), attr
->GetValue());
920 // Merge child nodes:
921 for (wxXmlNode
* node
= overwriteWith
.GetChildren(); node
; node
= node
->GetNext())
923 wxString name
= node
->GetAttribute(wxT("name"), wxEmptyString
);
926 for (dnode
= dest
.GetChildren(); dnode
; dnode
= dnode
->GetNext() )
928 if ( dnode
->GetName() == node
->GetName() &&
929 dnode
->GetAttribute(wxT("name"), wxEmptyString
) == name
&&
930 dnode
->GetType() == node
->GetType() )
932 MergeNodesOver(*dnode
, *node
, overwriteFilename
);
939 wxXmlNode
*copyOfNode
= new wxXmlNode(*node
);
940 // remember referenced object's file, see GetFileNameFromNode()
941 copyOfNode
->AddAttribute(ATTR_INPUT_FILENAME
, overwriteFilename
);
943 static const wxChar
*AT_END
= wxT("end");
944 wxString insert_pos
= node
->GetAttribute(wxT("insert_at"), AT_END
);
945 if ( insert_pos
== AT_END
)
947 dest
.AddChild(copyOfNode
);
949 else if ( insert_pos
== wxT("begin") )
951 dest
.InsertChild(copyOfNode
, dest
.GetChildren());
956 if ( dest
.GetType() == wxXML_TEXT_NODE
&& overwriteWith
.GetContent().length() )
957 dest
.SetContent(overwriteWith
.GetContent());
961 wxXmlResource::DoCreateResFromNode(wxXmlNode
& node
,
964 wxXmlResourceHandler
*handlerToUse
)
966 // handling of referenced resource
967 if ( node
.GetName() == wxT("object_ref") )
969 wxString refName
= node
.GetAttribute(wxT("ref"), wxEmptyString
);
970 wxXmlNode
* refNode
= FindResource(refName
, wxEmptyString
, true);
979 "referenced object node with ref=\"%s\" not found",
986 const bool hasOnlyRefAttr
= node
.GetAttributes() != NULL
&&
987 node
.GetAttributes()->GetNext() == NULL
;
989 if ( hasOnlyRefAttr
&& !node
.GetChildren() )
991 // In the typical, simple case, <object_ref> is used to link
992 // to another node and doesn't have any content of its own that
993 // would overwrite linked object's properties. In this case,
994 // we can simply create the resource from linked node.
996 return DoCreateResFromNode(*refNode
, parent
, instance
);
1000 // In the more complicated (but rare) case, <object_ref> has
1001 // subnodes that partially overwrite content of the referenced
1002 // object. In this case, we need to merge both XML trees and
1003 // load the resource from result of the merge.
1005 wxXmlNode
copy(*refNode
);
1006 MergeNodesOver(copy
, node
, GetFileNameFromNode(&node
, Data()));
1008 // remember referenced object's file, see GetFileNameFromNode()
1009 copy
.AddAttribute(ATTR_INPUT_FILENAME
,
1010 GetFileNameFromNode(refNode
, Data()));
1012 return DoCreateResFromNode(copy
, parent
, instance
);
1018 if (handlerToUse
->CanHandle(&node
))
1020 return handlerToUse
->CreateResource(&node
, parent
, instance
);
1023 else if (node
.GetName() == wxT("object"))
1025 for ( wxVector
<wxXmlResourceHandler
*>::iterator h
= m_handlers
.begin();
1026 h
!= m_handlers
.end(); ++h
)
1028 wxXmlResourceHandler
*handler
= *h
;
1029 if (handler
->CanHandle(&node
))
1030 return handler
->CreateResource(&node
, parent
, instance
);
1039 "no handler found for XML node \"%s\" (class \"%s\")",
1041 node
.GetAttribute("class", wxEmptyString
)
1047 wxIdRange::wxIdRange(const wxXmlNode
* node
,
1048 const wxString
& rname
,
1049 const wxString
& startno
,
1050 const wxString
& rsize
)
1054 m_item_end_found(0),
1058 if ( startno
.ToLong(&l
) )
1066 wxXmlResource::Get()->ReportError
1069 "a negative id-range start parameter was given"
1075 wxXmlResource::Get()->ReportError
1078 "the id-range start parameter was malformed"
1083 if ( rsize
.ToULong(&ul
) )
1089 wxXmlResource::Get()->ReportError
1092 "the id-range size parameter was malformed"
1097 void wxIdRange::NoteItem(const wxXmlNode
* node
, const wxString
& item
)
1099 // Nothing gets added here, but the existence of each item is noted
1100 // thus getting an accurate count. 'item' will be either an integer e.g.
1101 // [0] [123]: will eventually create an XRCID as start+integer or [start]
1102 // or [end] which are synonyms for [0] or [range_size-1] respectively.
1103 wxString
content(item
.Mid(1, item
.length()-2));
1105 // Check that basename+item wasn't foo[]
1106 if (content
.empty())
1108 wxXmlResource::Get()->ReportError(node
, "an empty id-range item found");
1112 if (content
=="start")
1114 // "start" means [0], so store that in the set
1115 if (m_indices
.count(0) == 0)
1117 m_indices
.insert(0);
1121 wxXmlResource::Get()->ReportError
1124 "duplicate id-range item found"
1128 else if (content
=="end")
1130 // We can't yet be certain which XRCID this will be equivalent to, so
1131 // just note that there's an item with this name, in case we need to
1132 // inc the range size
1133 m_item_end_found
= true;
1137 // Anything else will be an integer, or rubbish
1139 if ( content
.ToULong(&l
) )
1141 if (m_indices
.count(l
) == 0)
1143 m_indices
.insert(l
);
1144 // Check that this item wouldn't fall outside the current range
1153 wxXmlResource::Get()->ReportError
1156 "duplicate id-range item found"
1163 wxXmlResource::Get()->ReportError
1166 "an id-range item had a malformed index"
1172 void wxIdRange::Finalise(const wxXmlNode
* node
)
1174 wxCHECK_RET( !IsFinalised(),
1175 "Trying to finalise an already-finalised range" );
1177 // Now we know about all the items, we can get an accurate range size
1178 // Expand any requested range-size if there were more items than would fit
1179 m_size
= wxMax(m_size
, m_indices
.size());
1181 // If an item is explicitly called foo[end], ensure it won't clash with
1183 if ( m_item_end_found
&& m_indices
.count(m_size
-1) )
1187 // This will happen if someone creates a range but no items in this xrc
1188 // file Report the error and abort, but don't finalise, in case items
1190 wxXmlResource::Get()->ReportError
1193 "trying to create an empty id-range"
1200 // This is the usual case, where the user didn't specify a start ID
1201 // So get the range using NewControlId().
1203 // NB: negative numbers, but NewControlId already returns the most
1205 m_start
= wxWindow::NewControlId(m_size
);
1206 wxCHECK_RET( m_start
!= wxID_NONE
,
1207 "insufficient IDs available to create range" );
1208 m_end
= m_start
+ m_size
- 1;
1212 // The user already specified a start value, which must be positive
1213 m_end
= m_start
+ m_size
- 1;
1216 // Create the XRCIDs
1217 for (int i
=m_start
; i
<= m_end
; ++i
)
1219 // First clear any pre-existing XRCID
1220 // Necessary for wxXmlResource::Unload() followed by Load()
1221 wxIdRangeManager::RemoveXRCIDEntry(
1222 m_name
+ wxString::Format("[%i]", i
-m_start
));
1224 // Use the second parameter of GetXRCID to force it to take the value i
1225 wxXmlResource::GetXRCID(m_name
+ wxString::Format("[%i]", i
-m_start
), i
);
1226 wxLogTrace("xrcrange",
1227 "integer = %i %s now returns %i",
1229 m_name
+ wxString::Format("[%i]", i
-m_start
),
1230 XRCID((m_name
+ wxString::Format("[%i]", i
-m_start
)).mb_str()));
1232 // and these special ones
1233 wxIdRangeManager::RemoveXRCIDEntry(m_name
+ "[start]");
1234 wxXmlResource::GetXRCID(m_name
+ "[start]", m_start
);
1235 wxIdRangeManager::RemoveXRCIDEntry(m_name
+ "[end]");
1236 wxXmlResource::GetXRCID(m_name
+ "[end]", m_end
);
1237 wxLogTrace("xrcrange","%s[start] = %i %s[end] = %i",
1238 m_name
.mb_str(),XRCID(wxString(m_name
+"[start]").mb_str()),
1239 m_name
.mb_str(),XRCID(wxString(m_name
+"[end]").mb_str()));
1244 wxIdRangeManager
*wxIdRangeManager::ms_instance
= NULL
;
1246 /*static*/ wxIdRangeManager
*wxIdRangeManager::Get()
1249 ms_instance
= new wxIdRangeManager
;
1253 /*static*/ wxIdRangeManager
*wxIdRangeManager::Set(wxIdRangeManager
*res
)
1255 wxIdRangeManager
*old
= ms_instance
;
1260 wxIdRangeManager::~wxIdRangeManager()
1262 for ( wxVector
<wxIdRange
*>::iterator i
= m_IdRanges
.begin();
1263 i
!= m_IdRanges
.end(); ++i
)
1272 void wxIdRangeManager::AddRange(const wxXmlNode
* node
)
1274 wxString name
= node
->GetAttribute("name");
1275 wxString start
= node
->GetAttribute("start", "0");
1276 wxString size
= node
->GetAttribute("size", "0");
1279 wxXmlResource::Get()->ReportError
1282 "xrc file contains an id-range without a name"
1287 int index
= Find(name
);
1288 if (index
== wxNOT_FOUND
)
1290 wxLogTrace("xrcrange",
1291 "Adding ID range, name=%s start=%s size=%s",
1294 m_IdRanges
.push_back(new wxIdRange(node
, name
, start
, size
));
1298 // There was already a range with this name. Let's hope this is
1299 // from an Unload()/(re)Load(), not an unintentional duplication
1300 wxLogTrace("xrcrange",
1301 "Replacing ID range, name=%s start=%s size=%s",
1304 wxIdRange
* oldrange
= m_IdRanges
.at(index
);
1305 m_IdRanges
.at(index
) = new wxIdRange(node
, name
, start
, size
);
1311 wxIdRangeManager::FindRangeForItem(const wxXmlNode
* node
,
1312 const wxString
& item
,
1313 wxString
& value
) const
1315 wxString basename
= item
.BeforeFirst('[');
1316 wxCHECK_MSG( !basename
.empty(), NULL
,
1317 "an id-range item without a range name" );
1319 int index
= Find(basename
);
1320 if (index
== wxNOT_FOUND
)
1322 // Don't assert just because we've found an unexpected foo[123]
1323 // Someone might just want such a name, nothing to do with ranges
1327 value
= item
.Mid(basename
.Len());
1328 if (value
.at(value
.length()-1)==']')
1330 return m_IdRanges
.at(index
);
1332 wxXmlResource::Get()->ReportError(node
, "a malformed id-range item");
1337 wxIdRangeManager::NotifyRangeOfItem(const wxXmlNode
* node
,
1338 const wxString
& item
) const
1341 wxIdRange
* range
= FindRangeForItem(node
, item
, value
);
1343 range
->NoteItem(node
, value
);
1346 int wxIdRangeManager::Find(const wxString
& rangename
) const
1348 for ( int i
=0; i
< (int)m_IdRanges
.size(); ++i
)
1350 if (m_IdRanges
.at(i
)->GetName() == rangename
)
1357 void wxIdRangeManager::FinaliseRanges(const wxXmlNode
* node
) const
1359 for ( wxVector
<wxIdRange
*>::const_iterator i
= m_IdRanges
.begin();
1360 i
!= m_IdRanges
.end(); ++i
)
1362 // Check if this range has already been finalised. Quite possible,
1363 // as FinaliseRanges() gets called for each .xrc file loaded
1364 if (!(*i
)->IsFinalised())
1366 wxLogTrace("xrcrange", "Finalising ID range %s", (*i
)->GetName());
1367 (*i
)->Finalise(node
);
1373 class wxXmlSubclassFactories
: public wxVector
<wxXmlSubclassFactory
*>
1375 // this is a class so that it can be forward-declared
1378 wxXmlSubclassFactories
*wxXmlResource::ms_subclassFactories
= NULL
;
1380 /*static*/ void wxXmlResource::AddSubclassFactory(wxXmlSubclassFactory
*factory
)
1382 if (!ms_subclassFactories
)
1384 ms_subclassFactories
= new wxXmlSubclassFactories
;
1386 ms_subclassFactories
->push_back(factory
);
1389 class wxXmlSubclassFactoryCXX
: public wxXmlSubclassFactory
1392 ~wxXmlSubclassFactoryCXX() {}
1394 wxObject
*Create(const wxString
& className
)
1396 wxClassInfo
* classInfo
= wxClassInfo::FindClass(className
);
1399 return classInfo
->CreateObject();
1408 wxXmlResourceHandler::wxXmlResourceHandler()
1409 : m_node(NULL
), m_parent(NULL
), m_instance(NULL
),
1410 m_parentAsWindow(NULL
)
1415 wxObject
*wxXmlResourceHandler::CreateResource(wxXmlNode
*node
, wxObject
*parent
, wxObject
*instance
)
1417 wxXmlNode
*myNode
= m_node
;
1418 wxString myClass
= m_class
;
1419 wxObject
*myParent
= m_parent
, *myInstance
= m_instance
;
1420 wxWindow
*myParentAW
= m_parentAsWindow
;
1422 m_instance
= instance
;
1423 if (!m_instance
&& node
->HasAttribute(wxT("subclass")) &&
1424 !(m_resource
->GetFlags() & wxXRC_NO_SUBCLASSING
))
1426 wxString subclass
= node
->GetAttribute(wxT("subclass"), wxEmptyString
);
1427 if (!subclass
.empty())
1429 for (wxXmlSubclassFactories::iterator i
= wxXmlResource::ms_subclassFactories
->begin();
1430 i
!= wxXmlResource::ms_subclassFactories
->end(); ++i
)
1432 m_instance
= (*i
)->Create(subclass
);
1439 wxString name
= node
->GetAttribute(wxT("name"), wxEmptyString
);
1445 "subclass \"%s\" not found for resource \"%s\", not subclassing",
1454 m_class
= node
->GetAttribute(wxT("class"), wxEmptyString
);
1456 m_parentAsWindow
= wxDynamicCast(m_parent
, wxWindow
);
1458 wxObject
*returned
= DoCreateResource();
1462 m_parent
= myParent
; m_parentAsWindow
= myParentAW
;
1463 m_instance
= myInstance
;
1469 void wxXmlResourceHandler::AddStyle(const wxString
& name
, int value
)
1471 m_styleNames
.Add(name
);
1472 m_styleValues
.Add(value
);
1477 void wxXmlResourceHandler::AddWindowStyles()
1479 XRC_ADD_STYLE(wxCLIP_CHILDREN
);
1481 // the border styles all have the old and new names, recognize both for now
1482 XRC_ADD_STYLE(wxSIMPLE_BORDER
); XRC_ADD_STYLE(wxBORDER_SIMPLE
);
1483 XRC_ADD_STYLE(wxSUNKEN_BORDER
); XRC_ADD_STYLE(wxBORDER_SUNKEN
);
1484 XRC_ADD_STYLE(wxDOUBLE_BORDER
); XRC_ADD_STYLE(wxBORDER_DOUBLE
); // deprecated
1485 XRC_ADD_STYLE(wxBORDER_THEME
);
1486 XRC_ADD_STYLE(wxRAISED_BORDER
); XRC_ADD_STYLE(wxBORDER_RAISED
);
1487 XRC_ADD_STYLE(wxSTATIC_BORDER
); XRC_ADD_STYLE(wxBORDER_STATIC
);
1488 XRC_ADD_STYLE(wxNO_BORDER
); XRC_ADD_STYLE(wxBORDER_NONE
);
1490 XRC_ADD_STYLE(wxTRANSPARENT_WINDOW
);
1491 XRC_ADD_STYLE(wxWANTS_CHARS
);
1492 XRC_ADD_STYLE(wxTAB_TRAVERSAL
);
1493 XRC_ADD_STYLE(wxNO_FULL_REPAINT_ON_RESIZE
);
1494 XRC_ADD_STYLE(wxFULL_REPAINT_ON_RESIZE
);
1495 XRC_ADD_STYLE(wxALWAYS_SHOW_SB
);
1496 XRC_ADD_STYLE(wxWS_EX_BLOCK_EVENTS
);
1497 XRC_ADD_STYLE(wxWS_EX_VALIDATE_RECURSIVELY
);
1502 bool wxXmlResourceHandler::HasParam(const wxString
& param
)
1504 return (GetParamNode(param
) != NULL
);
1508 int wxXmlResourceHandler::GetStyle(const wxString
& param
, int defaults
)
1510 wxString s
= GetParamValue(param
);
1512 if (!s
) return defaults
;
1514 wxStringTokenizer
tkn(s
, wxT("| \t\n"), wxTOKEN_STRTOK
);
1518 while (tkn
.HasMoreTokens())
1520 fl
= tkn
.GetNextToken();
1521 index
= m_styleNames
.Index(fl
);
1522 if (index
!= wxNOT_FOUND
)
1524 style
|= m_styleValues
[index
];
1531 wxString::Format("unknown style flag \"%s\"", fl
)
1540 wxString
wxXmlResourceHandler::GetText(const wxString
& param
, bool translate
)
1542 wxXmlNode
*parNode
= GetParamNode(param
);
1543 wxString
str1(GetNodeContent(parNode
));
1546 // "\\" wasn't translated to "\" prior to 2.5.3.0:
1547 const bool escapeBackslash
= (m_resource
->CompareVersion(2,5,3,0) >= 0);
1549 // VS: First version of XRC resources used $ instead of & (which is
1550 // illegal in XML), but later I realized that '_' fits this purpose
1551 // much better (because &File means "File with F underlined").
1552 const wxChar amp_char
= (m_resource
->CompareVersion(2,3,0,1) < 0)
1555 for ( wxString::const_iterator dt
= str1
.begin(); dt
!= str1
.end(); ++dt
)
1557 // Remap amp_char to &, map double amp_char to amp_char (for things
1558 // like "&File..." -- this is illegal in XML, so we use "_File..."):
1559 if ( *dt
== amp_char
)
1561 if ( *(++dt
) == amp_char
)
1564 str2
<< wxT('&') << *dt
;
1566 // Remap \n to CR, \r to LF, \t to TAB, \\ to \:
1567 else if ( *dt
== wxT('\\') )
1569 switch ( (*(++dt
)).GetValue() )
1584 // "\\" wasn't translated to "\" prior to 2.5.3.0:
1585 if ( escapeBackslash
)
1590 // else fall-through to default: branch below
1593 str2
<< wxT('\\') << *dt
;
1603 if (m_resource
->GetFlags() & wxXRC_USE_LOCALE
)
1605 if (translate
&& parNode
&&
1606 parNode
->GetAttribute(wxT("translate"), wxEmptyString
) != wxT("0"))
1608 return wxGetTranslation(str2
, m_resource
->GetDomain());
1615 // The string is internally stored as UTF-8, we have to convert
1616 // it into system's default encoding so that it can be displayed:
1617 return wxString(str2
.wc_str(wxConvUTF8
), wxConvLocal
);
1622 // If wxXRC_USE_LOCALE is not set, then the string is already in
1623 // system's default encoding in ANSI build, so we don't have to
1624 // do anything special here.
1630 long wxXmlResourceHandler::GetLong(const wxString
& param
, long defaultv
)
1633 wxString str1
= GetParamValue(param
);
1635 if (!str1
.ToLong(&value
))
1641 float wxXmlResourceHandler::GetFloat(const wxString
& param
, float defaultv
)
1643 wxString str
= GetParamValue(param
);
1645 // strings in XRC always use C locale so make sure to use the
1646 // locale-independent wxString::ToCDouble() and not ToDouble() which uses
1647 // the current locale with a potentially different decimal point character
1649 if (!str
.ToCDouble(&value
))
1652 return wx_truncate_cast(float, value
);
1656 int wxXmlResourceHandler::GetID()
1658 return wxXmlResource::GetXRCID(GetName());
1663 wxString
wxXmlResourceHandler::GetName()
1665 return m_node
->GetAttribute(wxT("name"), wxT("-1"));
1670 bool wxXmlResourceHandler::GetBoolAttr(const wxString
& attr
, bool defaultv
)
1673 return m_node
->GetAttribute(attr
, &v
) ? v
== '1' : defaultv
;
1676 bool wxXmlResourceHandler::GetBool(const wxString
& param
, bool defaultv
)
1678 const wxString v
= GetParamValue(param
);
1680 return v
.empty() ? defaultv
: (v
== '1');
1684 static wxColour
GetSystemColour(const wxString
& name
)
1688 #define SYSCLR(clr) \
1689 if (name == wxT(#clr)) return wxSystemSettings::GetColour(clr);
1690 SYSCLR(wxSYS_COLOUR_SCROLLBAR
)
1691 SYSCLR(wxSYS_COLOUR_BACKGROUND
)
1692 SYSCLR(wxSYS_COLOUR_DESKTOP
)
1693 SYSCLR(wxSYS_COLOUR_ACTIVECAPTION
)
1694 SYSCLR(wxSYS_COLOUR_INACTIVECAPTION
)
1695 SYSCLR(wxSYS_COLOUR_MENU
)
1696 SYSCLR(wxSYS_COLOUR_WINDOW
)
1697 SYSCLR(wxSYS_COLOUR_WINDOWFRAME
)
1698 SYSCLR(wxSYS_COLOUR_MENUTEXT
)
1699 SYSCLR(wxSYS_COLOUR_WINDOWTEXT
)
1700 SYSCLR(wxSYS_COLOUR_CAPTIONTEXT
)
1701 SYSCLR(wxSYS_COLOUR_ACTIVEBORDER
)
1702 SYSCLR(wxSYS_COLOUR_INACTIVEBORDER
)
1703 SYSCLR(wxSYS_COLOUR_APPWORKSPACE
)
1704 SYSCLR(wxSYS_COLOUR_HIGHLIGHT
)
1705 SYSCLR(wxSYS_COLOUR_HIGHLIGHTTEXT
)
1706 SYSCLR(wxSYS_COLOUR_BTNFACE
)
1707 SYSCLR(wxSYS_COLOUR_3DFACE
)
1708 SYSCLR(wxSYS_COLOUR_BTNSHADOW
)
1709 SYSCLR(wxSYS_COLOUR_3DSHADOW
)
1710 SYSCLR(wxSYS_COLOUR_GRAYTEXT
)
1711 SYSCLR(wxSYS_COLOUR_BTNTEXT
)
1712 SYSCLR(wxSYS_COLOUR_INACTIVECAPTIONTEXT
)
1713 SYSCLR(wxSYS_COLOUR_BTNHIGHLIGHT
)
1714 SYSCLR(wxSYS_COLOUR_BTNHILIGHT
)
1715 SYSCLR(wxSYS_COLOUR_3DHIGHLIGHT
)
1716 SYSCLR(wxSYS_COLOUR_3DHILIGHT
)
1717 SYSCLR(wxSYS_COLOUR_3DDKSHADOW
)
1718 SYSCLR(wxSYS_COLOUR_3DLIGHT
)
1719 SYSCLR(wxSYS_COLOUR_INFOTEXT
)
1720 SYSCLR(wxSYS_COLOUR_INFOBK
)
1721 SYSCLR(wxSYS_COLOUR_LISTBOX
)
1722 SYSCLR(wxSYS_COLOUR_HOTLIGHT
)
1723 SYSCLR(wxSYS_COLOUR_GRADIENTACTIVECAPTION
)
1724 SYSCLR(wxSYS_COLOUR_GRADIENTINACTIVECAPTION
)
1725 SYSCLR(wxSYS_COLOUR_MENUHILIGHT
)
1726 SYSCLR(wxSYS_COLOUR_MENUBAR
)
1730 return wxNullColour
;
1733 wxColour
wxXmlResourceHandler::GetColour(const wxString
& param
, const wxColour
& defaultv
)
1735 wxString v
= GetParamValue(param
);
1742 // wxString -> wxColour conversion
1745 // the colour doesn't use #RRGGBB format, check if it is symbolic
1747 clr
= GetSystemColour(v
);
1754 wxString::Format("incorrect colour specification \"%s\"", v
)
1756 return wxNullColour
;
1765 // if 'param' has stock_id/stock_client, extracts them and returns true
1766 bool GetStockArtAttrs(const wxXmlNode
*paramNode
,
1767 const wxString
& defaultArtClient
,
1768 wxString
& art_id
, wxString
& art_client
)
1772 art_id
= paramNode
->GetAttribute("stock_id", "");
1774 if ( !art_id
.empty() )
1776 art_id
= wxART_MAKE_ART_ID_FROM_STR(art_id
);
1778 art_client
= paramNode
->GetAttribute("stock_client", "");
1779 if ( art_client
.empty() )
1780 art_client
= defaultArtClient
;
1782 art_client
= wxART_MAKE_CLIENT_ID_FROM_STR(art_client
);
1791 } // anonymous namespace
1793 wxBitmap
wxXmlResourceHandler::GetBitmap(const wxString
& param
,
1794 const wxArtClient
& defaultArtClient
,
1797 // it used to be possible to pass an empty string here to indicate that the
1798 // bitmap name should be read from this node itself but this is not
1799 // supported any more because GetBitmap(m_node) can be used directly
1801 wxASSERT_MSG( !param
.empty(), "bitmap parameter name can't be empty" );
1803 const wxXmlNode
* const node
= GetParamNode(param
);
1807 // this is not an error as bitmap parameter could be optional
1808 return wxNullBitmap
;
1811 return GetBitmap(node
, defaultArtClient
, size
);
1814 wxBitmap
wxXmlResourceHandler::GetBitmap(const wxXmlNode
* node
,
1815 const wxArtClient
& defaultArtClient
,
1818 wxCHECK_MSG( node
, wxNullBitmap
, "bitmap node can't be NULL" );
1820 /* If the bitmap is specified as stock item, query wxArtProvider for it: */
1821 wxString art_id
, art_client
;
1822 if ( GetStockArtAttrs(node
, defaultArtClient
,
1823 art_id
, art_client
) )
1825 wxBitmap
stockArt(wxArtProvider::GetBitmap(art_id
, art_client
, size
));
1826 if ( stockArt
.IsOk() )
1830 /* ...or load the bitmap from file: */
1831 wxString name
= GetParamValue(node
);
1832 if (name
.empty()) return wxNullBitmap
;
1833 #if wxUSE_FILESYSTEM
1834 wxFSFile
*fsfile
= GetCurFileSystem().OpenFile(name
, wxFS_READ
| wxFS_SEEKABLE
);
1840 wxString::Format("cannot open bitmap resource \"%s\"", name
)
1842 return wxNullBitmap
;
1844 wxImage
img(*(fsfile
->GetStream()));
1855 wxString::Format("cannot create bitmap from \"%s\"", name
)
1857 return wxNullBitmap
;
1859 if (!(size
== wxDefaultSize
)) img
.Rescale(size
.x
, size
.y
);
1860 return wxBitmap(img
);
1864 wxIcon
wxXmlResourceHandler::GetIcon(const wxString
& param
,
1865 const wxArtClient
& defaultArtClient
,
1868 // see comment in GetBitmap(wxString) overload
1869 wxASSERT_MSG( !param
.empty(), "icon parameter name can't be empty" );
1871 const wxXmlNode
* const node
= GetParamNode(param
);
1875 // this is not an error as icon parameter could be optional
1879 return GetIcon(node
, defaultArtClient
, size
);
1882 wxIcon
wxXmlResourceHandler::GetIcon(const wxXmlNode
* node
,
1883 const wxArtClient
& defaultArtClient
,
1887 icon
.CopyFromBitmap(GetBitmap(node
, defaultArtClient
, size
));
1892 wxIconBundle
wxXmlResourceHandler::GetIconBundle(const wxString
& param
,
1893 const wxArtClient
& defaultArtClient
)
1895 wxString art_id
, art_client
;
1896 if ( GetStockArtAttrs(GetParamNode(param
), defaultArtClient
,
1897 art_id
, art_client
) )
1899 wxIconBundle
stockArt(wxArtProvider::GetIconBundle(art_id
, art_client
));
1900 if ( stockArt
.IsOk() )
1904 const wxString name
= GetParamValue(param
);
1906 return wxNullIconBundle
;
1908 #if wxUSE_FILESYSTEM
1909 wxFSFile
*fsfile
= GetCurFileSystem().OpenFile(name
, wxFS_READ
| wxFS_SEEKABLE
);
1910 if ( fsfile
== NULL
)
1915 wxString::Format("cannot open icon resource \"%s\"", name
)
1917 return wxNullIconBundle
;
1920 wxIconBundle
bundle(*(fsfile
->GetStream()));
1923 wxIconBundle
bundle(name
);
1926 if ( !bundle
.IsOk() )
1931 wxString::Format("cannot create icon from \"%s\"", name
)
1933 return wxNullIconBundle
;
1940 wxImageList
*wxXmlResourceHandler::GetImageList(const wxString
& param
)
1942 wxXmlNode
* const imagelist_node
= GetParamNode(param
);
1943 if ( !imagelist_node
)
1946 wxXmlNode
* const oldnode
= m_node
;
1947 m_node
= imagelist_node
;
1949 // Get the size if we have it, otherwise we will use the size of the first
1951 wxSize size
= GetSize();
1953 // Start adding images, we'll create the image list when adding the first
1955 wxImageList
* imagelist
= NULL
;
1956 wxString parambitmap
= wxT("bitmap");
1957 if ( HasParam(parambitmap
) )
1959 wxXmlNode
*n
= m_node
->GetChildren();
1962 if (n
->GetType() == wxXML_ELEMENT_NODE
&& n
->GetName() == parambitmap
)
1964 wxIcon icon
= GetIcon(n
, wxART_OTHER
, size
);
1967 // We need the real image list size to create it.
1968 if ( size
== wxDefaultSize
)
1969 size
= icon
.GetSize();
1971 // We use the mask by default.
1972 bool mask
= !HasParam(wxS("mask")) || GetBool(wxS("mask"));
1974 imagelist
= new wxImageList(size
.x
, size
.y
, mask
);
1977 // add icon instead of bitmap to keep the bitmap mask
1978 imagelist
->Add(icon
);
1988 wxXmlNode
*wxXmlResourceHandler::GetParamNode(const wxString
& param
)
1990 wxCHECK_MSG(m_node
, NULL
, wxT("You can't access handler data before it was initialized!"));
1992 wxXmlNode
*n
= m_node
->GetChildren();
1996 if (n
->GetType() == wxXML_ELEMENT_NODE
&& n
->GetName() == param
)
1998 // TODO: check that there are no other properties/parameters with
1999 // the same name and log an error if there are (can't do this
2000 // right now as I'm not sure if it's not going to break code
2001 // using this function in unintentional way (i.e. for
2002 // accessing other things than properties), for example
2003 // wxBitmapComboBoxXmlHandler almost surely does
2012 bool wxXmlResourceHandler::IsOfClass(wxXmlNode
*node
, const wxString
& classname
)
2014 return node
->GetAttribute(wxT("class")) == classname
;
2019 wxString
wxXmlResourceHandler::GetNodeContent(const wxXmlNode
*node
)
2021 const wxXmlNode
*n
= node
;
2022 if (n
== NULL
) return wxEmptyString
;
2023 n
= n
->GetChildren();
2027 if (n
->GetType() == wxXML_TEXT_NODE
||
2028 n
->GetType() == wxXML_CDATA_SECTION_NODE
)
2029 return n
->GetContent();
2032 return wxEmptyString
;
2037 wxString
wxXmlResourceHandler::GetParamValue(const wxString
& param
)
2040 return GetNodeContent(m_node
);
2042 return GetNodeContent(GetParamNode(param
));
2045 wxString
wxXmlResourceHandler::GetParamValue(const wxXmlNode
* node
)
2047 return GetNodeContent(node
);
2051 wxSize
wxXmlResourceHandler::GetSize(const wxString
& param
,
2052 wxWindow
*windowToUse
)
2054 wxString s
= GetParamValue(param
);
2055 if (s
.empty()) s
= wxT("-1,-1");
2059 is_dlg
= s
[s
.length()-1] == wxT('d');
2060 if (is_dlg
) s
.RemoveLast();
2062 if (!s
.BeforeFirst(wxT(',')).ToLong(&sx
) ||
2063 !s
.AfterLast(wxT(',')).ToLong(&sy
))
2068 wxString::Format("cannot parse coordinates value \"%s\"", s
)
2070 return wxDefaultSize
;
2077 return wxDLG_UNIT(windowToUse
, wxSize(sx
, sy
));
2079 else if (m_parentAsWindow
)
2081 return wxDLG_UNIT(m_parentAsWindow
, wxSize(sx
, sy
));
2088 "cannot convert dialog units: dialog unknown"
2090 return wxDefaultSize
;
2094 return wxSize(sx
, sy
);
2099 wxPoint
wxXmlResourceHandler::GetPosition(const wxString
& param
)
2101 wxSize sz
= GetSize(param
);
2102 return wxPoint(sz
.x
, sz
.y
);
2107 wxCoord
wxXmlResourceHandler::GetDimension(const wxString
& param
,
2109 wxWindow
*windowToUse
)
2111 wxString s
= GetParamValue(param
);
2112 if (s
.empty()) return defaultv
;
2116 is_dlg
= s
[s
.length()-1] == wxT('d');
2117 if (is_dlg
) s
.RemoveLast();
2124 wxString::Format("cannot parse dimension value \"%s\"", s
)
2133 return wxDLG_UNIT(windowToUse
, wxSize(sx
, 0)).x
;
2135 else if (m_parentAsWindow
)
2137 return wxDLG_UNIT(m_parentAsWindow
, wxSize(sx
, 0)).x
;
2144 "cannot convert dialog units: dialog unknown"
2154 // Get system font index using indexname
2155 static wxFont
GetSystemFont(const wxString
& name
)
2159 #define SYSFNT(fnt) \
2160 if (name == wxT(#fnt)) return wxSystemSettings::GetFont(fnt);
2161 SYSFNT(wxSYS_OEM_FIXED_FONT
)
2162 SYSFNT(wxSYS_ANSI_FIXED_FONT
)
2163 SYSFNT(wxSYS_ANSI_VAR_FONT
)
2164 SYSFNT(wxSYS_SYSTEM_FONT
)
2165 SYSFNT(wxSYS_DEVICE_DEFAULT_FONT
)
2166 SYSFNT(wxSYS_SYSTEM_FIXED_FONT
)
2167 SYSFNT(wxSYS_DEFAULT_GUI_FONT
)
2174 wxFont
wxXmlResourceHandler::GetFont(const wxString
& param
)
2176 wxXmlNode
*font_node
= GetParamNode(param
);
2177 if (font_node
== NULL
)
2180 wxString::Format("cannot find font node \"%s\"", param
));
2184 wxXmlNode
*oldnode
= m_node
;
2191 bool hasSize
= HasParam(wxT("size"));
2193 isize
= GetLong(wxT("size"), -1);
2196 int istyle
= wxNORMAL
;
2197 bool hasStyle
= HasParam(wxT("style"));
2200 wxString style
= GetParamValue(wxT("style"));
2201 if (style
== wxT("italic"))
2203 else if (style
== wxT("slant"))
2208 int iweight
= wxNORMAL
;
2209 bool hasWeight
= HasParam(wxT("weight"));
2212 wxString weight
= GetParamValue(wxT("weight"));
2213 if (weight
== wxT("bold"))
2215 else if (weight
== wxT("light"))
2220 bool hasUnderlined
= HasParam(wxT("underlined"));
2221 bool underlined
= hasUnderlined
? GetBool(wxT("underlined"), false) : false;
2223 // family and facename
2224 int ifamily
= wxDEFAULT
;
2225 bool hasFamily
= HasParam(wxT("family"));
2228 wxString family
= GetParamValue(wxT("family"));
2229 if (family
== wxT("decorative")) ifamily
= wxDECORATIVE
;
2230 else if (family
== wxT("roman")) ifamily
= wxROMAN
;
2231 else if (family
== wxT("script")) ifamily
= wxSCRIPT
;
2232 else if (family
== wxT("swiss")) ifamily
= wxSWISS
;
2233 else if (family
== wxT("modern")) ifamily
= wxMODERN
;
2234 else if (family
== wxT("teletype")) ifamily
= wxTELETYPE
;
2239 bool hasFacename
= HasParam(wxT("face"));
2242 wxString faces
= GetParamValue(wxT("face"));
2243 wxStringTokenizer
tk(faces
, wxT(","));
2245 wxArrayString
facenames(wxFontEnumerator::GetFacenames());
2246 while (tk
.HasMoreTokens())
2248 int index
= facenames
.Index(tk
.GetNextToken(), false);
2249 if (index
!= wxNOT_FOUND
)
2251 facename
= facenames
[index
];
2255 #else // !wxUSE_FONTENUM
2256 // just use the first face name if we can't check its availability:
2257 if (tk
.HasMoreTokens())
2258 facename
= tk
.GetNextToken();
2259 #endif // wxUSE_FONTENUM/!wxUSE_FONTENUM
2263 wxFontEncoding enc
= wxFONTENCODING_DEFAULT
;
2264 bool hasEncoding
= HasParam(wxT("encoding"));
2268 wxString encoding
= GetParamValue(wxT("encoding"));
2269 wxFontMapper mapper
;
2270 if (!encoding
.empty())
2271 enc
= mapper
.CharsetToEncoding(encoding
);
2272 if (enc
== wxFONTENCODING_SYSTEM
)
2273 enc
= wxFONTENCODING_DEFAULT
;
2275 #endif // wxUSE_FONTMAP
2277 // is this font based on a system font?
2278 wxFont font
= GetSystemFont(GetParamValue(wxT("sysfont")));
2282 if (hasSize
&& isize
!= -1)
2283 font
.SetPointSize(isize
);
2284 else if (HasParam(wxT("relativesize")))
2285 font
.SetPointSize(int(font
.GetPointSize() *
2286 GetFloat(wxT("relativesize"))));
2289 font
.SetStyle(istyle
);
2291 font
.SetWeight(iweight
);
2293 font
.SetUnderlined(underlined
);
2295 font
.SetFamily(ifamily
);
2297 font
.SetFaceName(facename
);
2299 font
.SetDefaultEncoding(enc
);
2301 else // not based on system font
2303 font
= wxFont(isize
== -1 ? wxNORMAL_FONT
->GetPointSize() : isize
,
2304 ifamily
, istyle
, iweight
,
2305 underlined
, facename
, enc
);
2313 void wxXmlResourceHandler::SetupWindow(wxWindow
*wnd
)
2315 //FIXME : add cursor
2317 if (HasParam(wxT("exstyle")))
2318 // Have to OR it with existing style, since
2319 // some implementations (e.g. wxGTK) use the extra style
2321 wnd
->SetExtraStyle(wnd
->GetExtraStyle() | GetStyle(wxT("exstyle")));
2322 if (HasParam(wxT("bg")))
2323 wnd
->SetBackgroundColour(GetColour(wxT("bg")));
2324 if (HasParam(wxT("ownbg")))
2325 wnd
->SetOwnBackgroundColour(GetColour(wxT("ownbg")));
2326 if (HasParam(wxT("fg")))
2327 wnd
->SetForegroundColour(GetColour(wxT("fg")));
2328 if (HasParam(wxT("ownfg")))
2329 wnd
->SetOwnForegroundColour(GetColour(wxT("ownfg")));
2330 if (GetBool(wxT("enabled"), 1) == 0)
2332 if (GetBool(wxT("focused"), 0) == 1)
2334 if (GetBool(wxT("hidden"), 0) == 1)
2337 if (HasParam(wxT("tooltip")))
2338 wnd
->SetToolTip(GetText(wxT("tooltip")));
2340 if (HasParam(wxT("font")))
2341 wnd
->SetFont(GetFont(wxT("font")));
2342 if (HasParam(wxT("ownfont")))
2343 wnd
->SetOwnFont(GetFont(wxT("ownfont")));
2344 if (HasParam(wxT("help")))
2345 wnd
->SetHelpText(GetText(wxT("help")));
2349 void wxXmlResourceHandler::CreateChildren(wxObject
*parent
, bool this_hnd_only
)
2351 for ( wxXmlNode
*n
= m_node
->GetChildren(); n
; n
= n
->GetNext() )
2353 if ( IsObjectNode(n
) )
2355 m_resource
->DoCreateResFromNode(*n
, parent
, NULL
,
2356 this_hnd_only
? this : NULL
);
2362 void wxXmlResourceHandler::CreateChildrenPrivately(wxObject
*parent
, wxXmlNode
*rootnode
)
2365 if (rootnode
== NULL
) root
= m_node
; else root
= rootnode
;
2366 wxXmlNode
*n
= root
->GetChildren();
2370 if (n
->GetType() == wxXML_ELEMENT_NODE
&& CanHandle(n
))
2372 CreateResource(n
, parent
, NULL
);
2379 //-----------------------------------------------------------------------------
2381 //-----------------------------------------------------------------------------
2383 void wxXmlResourceHandler::ReportError(const wxString
& message
)
2385 m_resource
->ReportError(m_node
, message
);
2388 void wxXmlResourceHandler::ReportError(wxXmlNode
*context
,
2389 const wxString
& message
)
2391 m_resource
->ReportError(context
? context
: m_node
, message
);
2394 void wxXmlResourceHandler::ReportParamError(const wxString
& param
,
2395 const wxString
& message
)
2397 m_resource
->ReportError(GetParamNode(param
), message
);
2400 void wxXmlResource::ReportError(const wxXmlNode
*context
, const wxString
& message
)
2404 DoReportError("", NULL
, message
);
2408 // We need to find out the file that 'context' is part of. Performance of
2409 // this code is not critical, so we simply find the root XML node and
2410 // compare it with all loaded XRC files.
2411 const wxString filename
= GetFileNameFromNode(context
, Data());
2413 DoReportError(filename
, context
, message
);
2416 void wxXmlResource::DoReportError(const wxString
& xrcFile
, const wxXmlNode
*position
,
2417 const wxString
& message
)
2419 const int line
= position
? position
->GetLineNumber() : -1;
2422 if ( !xrcFile
.empty() )
2423 loc
= xrcFile
+ ':';
2425 loc
+= wxString::Format("%d:", line
);
2429 wxLogError("XRC error: %s%s", loc
, message
);
2433 //-----------------------------------------------------------------------------
2434 // XRCID implementation
2435 //-----------------------------------------------------------------------------
2437 #define XRCID_TABLE_SIZE 1024
2442 /* Hold the id so that once an id is allocated for a name, it
2443 does not get created again by NewControlId at least
2444 until we are done with it */
2450 static XRCID_record
*XRCID_Records
[XRCID_TABLE_SIZE
] = {NULL
};
2452 // Extremely simplistic hash function which probably ought to be replaced with
2453 // wxStringHash::stringHash().
2454 static inline unsigned XRCIdHash(const char *str_id
)
2458 for (const char *c
= str_id
; *c
!= '\0'; c
++) index
+= (unsigned int)*c
;
2459 index
%= XRCID_TABLE_SIZE
;
2464 static int XRCID_Lookup(const char *str_id
, int value_if_not_found
= wxID_NONE
)
2466 const unsigned index
= XRCIdHash(str_id
);
2469 XRCID_record
*oldrec
= NULL
;
2470 for (XRCID_record
*rec
= XRCID_Records
[index
]; rec
; rec
= rec
->next
)
2472 if (wxStrcmp(rec
->key
, str_id
) == 0)
2479 XRCID_record
**rec_var
= (oldrec
== NULL
) ?
2480 &XRCID_Records
[index
] : &oldrec
->next
;
2481 *rec_var
= new XRCID_record
;
2482 (*rec_var
)->key
= wxStrdup(str_id
);
2483 (*rec_var
)->next
= NULL
;
2486 if (value_if_not_found
!= wxID_NONE
)
2487 (*rec_var
)->id
= value_if_not_found
;
2490 int asint
= wxStrtol(str_id
, &end
, 10);
2491 if (*str_id
&& *end
== 0)
2493 // if str_id was integer, keep it verbosely:
2494 (*rec_var
)->id
= asint
;
2498 (*rec_var
)->id
= wxWindowBase::NewControlId();
2502 return (*rec_var
)->id
;
2508 // flag indicating whether standard XRC ids were already initialized
2509 static bool gs_stdIDsAdded
= false;
2511 void AddStdXRCID_Records()
2513 #define stdID(id) XRCID_Lookup(#id, id)
2517 stdID(wxID_SEPARATOR
);
2530 stdID(wxID_PRINT_SETUP
);
2531 stdID(wxID_PAGE_SETUP
);
2532 stdID(wxID_PREVIEW
);
2534 stdID(wxID_HELP_CONTENTS
);
2535 stdID(wxID_HELP_COMMANDS
);
2536 stdID(wxID_HELP_PROCEDURES
);
2537 stdID(wxID_HELP_CONTEXT
);
2538 stdID(wxID_CLOSE_ALL
);
2539 stdID(wxID_PREFERENCES
);
2546 stdID(wxID_DUPLICATE
);
2547 stdID(wxID_SELECTALL
);
2549 stdID(wxID_REPLACE
);
2550 stdID(wxID_REPLACE_ALL
);
2551 stdID(wxID_PROPERTIES
);
2552 stdID(wxID_VIEW_DETAILS
);
2553 stdID(wxID_VIEW_LARGEICONS
);
2554 stdID(wxID_VIEW_SMALLICONS
);
2555 stdID(wxID_VIEW_LIST
);
2556 stdID(wxID_VIEW_SORTDATE
);
2557 stdID(wxID_VIEW_SORTNAME
);
2558 stdID(wxID_VIEW_SORTSIZE
);
2559 stdID(wxID_VIEW_SORTTYPE
);
2575 stdID(wxID_FORWARD
);
2576 stdID(wxID_BACKWARD
);
2577 stdID(wxID_DEFAULT
);
2581 stdID(wxID_CONTEXT_HELP
);
2582 stdID(wxID_YESTOALL
);
2583 stdID(wxID_NOTOALL
);
2592 stdID(wxID_REFRESH
);
2597 stdID(wxID_JUSTIFY_CENTER
);
2598 stdID(wxID_JUSTIFY_FILL
);
2599 stdID(wxID_JUSTIFY_RIGHT
);
2600 stdID(wxID_JUSTIFY_LEFT
);
2601 stdID(wxID_UNDERLINE
);
2603 stdID(wxID_UNINDENT
);
2604 stdID(wxID_ZOOM_100
);
2605 stdID(wxID_ZOOM_FIT
);
2606 stdID(wxID_ZOOM_IN
);
2607 stdID(wxID_ZOOM_OUT
);
2608 stdID(wxID_UNDELETE
);
2609 stdID(wxID_REVERT_TO_SAVED
);
2610 stdID(wxID_SYSTEM_MENU
);
2611 stdID(wxID_CLOSE_FRAME
);
2612 stdID(wxID_MOVE_FRAME
);
2613 stdID(wxID_RESIZE_FRAME
);
2614 stdID(wxID_MAXIMIZE_FRAME
);
2615 stdID(wxID_ICONIZE_FRAME
);
2616 stdID(wxID_RESTORE_FRAME
);
2618 stdID(wxID_CONVERT
);
2619 stdID(wxID_EXECUTE
);
2621 stdID(wxID_HARDDISK
);
2627 stdID(wxID_JUMP_TO
);
2628 stdID(wxID_NETWORK
);
2629 stdID(wxID_SELECT_COLOR
);
2630 stdID(wxID_SELECT_FONT
);
2631 stdID(wxID_SORT_ASCENDING
);
2632 stdID(wxID_SORT_DESCENDING
);
2633 stdID(wxID_SPELL_CHECK
);
2634 stdID(wxID_STRIKETHROUGH
);
2639 } // anonymous namespace
2643 int wxXmlResource::DoGetXRCID(const char *str_id
, int value_if_not_found
)
2645 if ( !gs_stdIDsAdded
)
2647 gs_stdIDsAdded
= true;
2648 AddStdXRCID_Records();
2651 return XRCID_Lookup(str_id
, value_if_not_found
);
2655 wxString
wxXmlResource::FindXRCIDById(int numId
)
2657 for ( int i
= 0; i
< XRCID_TABLE_SIZE
; i
++ )
2659 for ( XRCID_record
*rec
= XRCID_Records
[i
]; rec
; rec
= rec
->next
)
2661 if ( rec
->id
== numId
)
2662 return wxString(rec
->key
);
2670 void wxIdRangeManager::RemoveXRCIDEntry(const wxString
& idstr
)
2672 const char *str_id
= idstr
.mb_str();
2674 const unsigned index
= XRCIdHash(str_id
);
2676 XRCID_record
**p_previousrec
= &XRCID_Records
[index
];
2677 for (XRCID_record
*rec
= XRCID_Records
[index
]; rec
; rec
= rec
->next
)
2679 if (wxStrcmp(rec
->key
, str_id
) == 0)
2681 // Found the item to be removed so delete its record; but first
2682 // remove it from the linked list.
2683 *p_previousrec
= rec
->next
;
2689 p_previousrec
= &rec
->next
;
2693 static void CleanXRCID_Record(XRCID_record
*rec
)
2697 CleanXRCID_Record(rec
->next
);
2704 static void CleanXRCID_Records()
2706 for (int i
= 0; i
< XRCID_TABLE_SIZE
; i
++)
2708 CleanXRCID_Record(XRCID_Records
[i
]);
2709 XRCID_Records
[i
] = NULL
;
2712 gs_stdIDsAdded
= false;
2716 //-----------------------------------------------------------------------------
2717 // module and globals
2718 //-----------------------------------------------------------------------------
2720 // normally we would do the cleanup from wxXmlResourceModule::OnExit() but it
2721 // can happen that some XRC records have been created because of the use of
2722 // XRCID() in event tables, which happens during static objects initialization,
2723 // but then the application initialization failed and so the wx modules were
2724 // neither initialized nor cleaned up -- this static object does the cleanup in
2726 static struct wxXRCStaticCleanup
2728 ~wxXRCStaticCleanup() { CleanXRCID_Records(); }
2731 class wxXmlResourceModule
: public wxModule
2733 DECLARE_DYNAMIC_CLASS(wxXmlResourceModule
)
2735 wxXmlResourceModule() {}
2738 wxXmlResource::AddSubclassFactory(new wxXmlSubclassFactoryCXX
);
2743 delete wxXmlResource::Set(NULL
);
2744 delete wxIdRangeManager::Set(NULL
);
2745 if(wxXmlResource::ms_subclassFactories
)
2747 for ( wxXmlSubclassFactories::iterator i
= wxXmlResource::ms_subclassFactories
->begin();
2748 i
!= wxXmlResource::ms_subclassFactories
->end(); ++i
)
2752 wxDELETE(wxXmlResource::ms_subclassFactories
);
2754 CleanXRCID_Records();
2758 IMPLEMENT_DYNAMIC_CLASS(wxXmlResourceModule
, wxModule
)
2761 // When wxXml is loaded dynamically after the application is already running
2762 // then the built-in module system won't pick this one up. Add it manually.
2763 void wxXmlInitResourceModule()
2765 wxModule
* module = new wxXmlResourceModule
;
2767 wxModule::RegisterModule(module);