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 if ( !node
.GetChildren() )
988 // In the typical, simple case, <object_ref> is used to link
989 // to another node and doesn't have any content of its own that
990 // would overwrite linked object's properties. In this case,
991 // we can simply create the resource from linked node.
993 return DoCreateResFromNode(*refNode
, parent
, instance
);
997 // In the more complicated (but rare) case, <object_ref> has
998 // subnodes that partially overwrite content of the referenced
999 // object. In this case, we need to merge both XML trees and
1000 // load the resource from result of the merge.
1002 wxXmlNode
copy(*refNode
);
1003 MergeNodesOver(copy
, node
, GetFileNameFromNode(&node
, Data()));
1005 // remember referenced object's file, see GetFileNameFromNode()
1006 copy
.AddAttribute(ATTR_INPUT_FILENAME
,
1007 GetFileNameFromNode(refNode
, Data()));
1009 return DoCreateResFromNode(copy
, parent
, instance
);
1015 if (handlerToUse
->CanHandle(&node
))
1017 return handlerToUse
->CreateResource(&node
, parent
, instance
);
1020 else if (node
.GetName() == wxT("object"))
1022 for ( wxVector
<wxXmlResourceHandler
*>::iterator h
= m_handlers
.begin();
1023 h
!= m_handlers
.end(); ++h
)
1025 wxXmlResourceHandler
*handler
= *h
;
1026 if (handler
->CanHandle(&node
))
1027 return handler
->CreateResource(&node
, parent
, instance
);
1036 "no handler found for XML node \"%s\" (class \"%s\")",
1038 node
.GetAttribute("class", wxEmptyString
)
1044 wxIdRange::wxIdRange(const wxXmlNode
* node
,
1045 const wxString
& rname
,
1046 const wxString
& startno
,
1047 const wxString
& rsize
)
1051 m_item_end_found(0),
1055 if ( startno
.ToLong(&l
) )
1063 wxXmlResource::Get()->ReportError
1066 "a negative id-range start parameter was given"
1072 wxXmlResource::Get()->ReportError
1075 "the id-range start parameter was malformed"
1080 if ( rsize
.ToULong(&ul
) )
1086 wxXmlResource::Get()->ReportError
1089 "the id-range size parameter was malformed"
1094 void wxIdRange::NoteItem(const wxXmlNode
* node
, const wxString
& item
)
1096 // Nothing gets added here, but the existence of each item is noted
1097 // thus getting an accurate count. 'item' will be either an integer e.g.
1098 // [0] [123]: will eventually create an XRCID as start+integer or [start]
1099 // or [end] which are synonyms for [0] or [range_size-1] respectively.
1100 wxString
content(item
.Mid(1, item
.length()-2));
1102 // Check that basename+item wasn't foo[]
1103 if (content
.empty())
1105 wxXmlResource::Get()->ReportError(node
, "an empty id-range item found");
1109 if (content
=="start")
1111 // "start" means [0], so store that in the set
1112 if (m_indices
.count(0) == 0)
1114 m_indices
.insert(0);
1118 wxXmlResource::Get()->ReportError
1121 "duplicate id-range item found"
1125 else if (content
=="end")
1127 // We can't yet be certain which XRCID this will be equivalent to, so
1128 // just note that there's an item with this name, in case we need to
1129 // inc the range size
1130 m_item_end_found
= true;
1134 // Anything else will be an integer, or rubbish
1136 if ( content
.ToULong(&l
) )
1138 if (m_indices
.count(l
) == 0)
1140 m_indices
.insert(l
);
1141 // Check that this item wouldn't fall outside the current range
1150 wxXmlResource::Get()->ReportError
1153 "duplicate id-range item found"
1160 wxXmlResource::Get()->ReportError
1163 "an id-range item had a malformed index"
1169 void wxIdRange::Finalise(const wxXmlNode
* node
)
1171 wxCHECK_RET( !IsFinalised(),
1172 "Trying to finalise an already-finalised range" );
1174 // Now we know about all the items, we can get an accurate range size
1175 // Expand any requested range-size if there were more items than would fit
1176 m_size
= wxMax(m_size
, m_indices
.size());
1178 // If an item is explicitly called foo[end], ensure it won't clash with
1180 if ( m_item_end_found
&& m_indices
.count(m_size
-1) )
1184 // This will happen if someone creates a range but no items in this xrc
1185 // file Report the error and abort, but don't finalise, in case items
1187 wxXmlResource::Get()->ReportError
1190 "trying to create an empty id-range"
1197 // This is the usual case, where the user didn't specify a start ID
1198 // So get the range using NewControlId().
1200 // NB: negative numbers, but NewControlId already returns the most
1202 m_start
= wxWindow::NewControlId(m_size
);
1203 wxCHECK_RET( m_start
!= wxID_NONE
,
1204 "insufficient IDs available to create range" );
1205 m_end
= m_start
+ m_size
- 1;
1209 // The user already specified a start value, which must be positive
1210 m_end
= m_start
+ m_size
- 1;
1213 // Create the XRCIDs
1214 for (int i
=m_start
; i
<= m_end
; ++i
)
1216 // First clear any pre-existing XRCID
1217 // Necessary for wxXmlResource::Unload() followed by Load()
1218 wxIdRangeManager::RemoveXRCIDEntry(
1219 m_name
+ wxString::Format("[%i]", i
-m_start
));
1221 // Use the second parameter of GetXRCID to force it to take the value i
1222 wxXmlResource::GetXRCID(m_name
+ wxString::Format("[%i]", i
-m_start
), i
);
1223 wxLogTrace("xrcrange",
1224 "integer = %i %s now returns %i",
1226 m_name
+ wxString::Format("[%i]", i
-m_start
),
1227 XRCID((m_name
+ wxString::Format("[%i]", i
-m_start
)).mb_str()));
1229 // and these special ones
1230 wxIdRangeManager::RemoveXRCIDEntry(m_name
+ "[start]");
1231 wxXmlResource::GetXRCID(m_name
+ "[start]", m_start
);
1232 wxIdRangeManager::RemoveXRCIDEntry(m_name
+ "[end]");
1233 wxXmlResource::GetXRCID(m_name
+ "[end]", m_end
);
1234 wxLogTrace("xrcrange","%s[start] = %i %s[end] = %i",
1235 m_name
.mb_str(),XRCID(wxString(m_name
+"[start]").mb_str()),
1236 m_name
.mb_str(),XRCID(wxString(m_name
+"[end]").mb_str()));
1241 wxIdRangeManager
*wxIdRangeManager::ms_instance
= NULL
;
1243 /*static*/ wxIdRangeManager
*wxIdRangeManager::Get()
1246 ms_instance
= new wxIdRangeManager
;
1250 /*static*/ wxIdRangeManager
*wxIdRangeManager::Set(wxIdRangeManager
*res
)
1252 wxIdRangeManager
*old
= ms_instance
;
1257 wxIdRangeManager::~wxIdRangeManager()
1259 for ( wxVector
<wxIdRange
*>::iterator i
= m_IdRanges
.begin();
1260 i
!= m_IdRanges
.end(); ++i
)
1269 void wxIdRangeManager::AddRange(const wxXmlNode
* node
)
1271 wxString name
= node
->GetAttribute("name");
1272 wxString start
= node
->GetAttribute("start", "0");
1273 wxString size
= node
->GetAttribute("size", "0");
1276 wxXmlResource::Get()->ReportError
1279 "xrc file contains an id-range without a name"
1284 int index
= Find(name
);
1285 if (index
== wxNOT_FOUND
)
1287 wxLogTrace("xrcrange",
1288 "Adding ID range, name=%s start=%s size=%s",
1291 m_IdRanges
.push_back(new wxIdRange(node
, name
, start
, size
));
1295 // There was already a range with this name. Let's hope this is
1296 // from an Unload()/(re)Load(), not an unintentional duplication
1297 wxLogTrace("xrcrange",
1298 "Replacing ID range, name=%s start=%s size=%s",
1301 wxIdRange
* oldrange
= m_IdRanges
.at(index
);
1302 m_IdRanges
.at(index
) = new wxIdRange(node
, name
, start
, size
);
1308 wxIdRangeManager::FindRangeForItem(const wxXmlNode
* node
,
1309 const wxString
& item
,
1310 wxString
& value
) const
1312 wxString basename
= item
.BeforeFirst('[');
1313 wxCHECK_MSG( !basename
.empty(), NULL
,
1314 "an id-range item without a range name" );
1316 int index
= Find(basename
);
1317 if (index
== wxNOT_FOUND
)
1319 // Don't assert just because we've found an unexpected foo[123]
1320 // Someone might just want such a name, nothing to do with ranges
1324 value
= item
.Mid(basename
.Len());
1325 if (value
.at(value
.length()-1)==']')
1327 return m_IdRanges
.at(index
);
1329 wxXmlResource::Get()->ReportError(node
, "a malformed id-range item");
1334 wxIdRangeManager::NotifyRangeOfItem(const wxXmlNode
* node
,
1335 const wxString
& item
) const
1338 wxIdRange
* range
= FindRangeForItem(node
, item
, value
);
1340 range
->NoteItem(node
, value
);
1343 int wxIdRangeManager::Find(const wxString
& rangename
) const
1345 for ( int i
=0; i
< (int)m_IdRanges
.size(); ++i
)
1347 if (m_IdRanges
.at(i
)->GetName() == rangename
)
1354 void wxIdRangeManager::FinaliseRanges(const wxXmlNode
* node
) const
1356 for ( wxVector
<wxIdRange
*>::const_iterator i
= m_IdRanges
.begin();
1357 i
!= m_IdRanges
.end(); ++i
)
1359 // Check if this range has already been finalised. Quite possible,
1360 // as FinaliseRanges() gets called for each .xrc file loaded
1361 if (!(*i
)->IsFinalised())
1363 wxLogTrace("xrcrange", "Finalising ID range %s", (*i
)->GetName());
1364 (*i
)->Finalise(node
);
1370 class wxXmlSubclassFactories
: public wxVector
<wxXmlSubclassFactory
*>
1372 // this is a class so that it can be forward-declared
1375 wxXmlSubclassFactories
*wxXmlResource::ms_subclassFactories
= NULL
;
1377 /*static*/ void wxXmlResource::AddSubclassFactory(wxXmlSubclassFactory
*factory
)
1379 if (!ms_subclassFactories
)
1381 ms_subclassFactories
= new wxXmlSubclassFactories
;
1383 ms_subclassFactories
->push_back(factory
);
1386 class wxXmlSubclassFactoryCXX
: public wxXmlSubclassFactory
1389 ~wxXmlSubclassFactoryCXX() {}
1391 wxObject
*Create(const wxString
& className
)
1393 wxClassInfo
* classInfo
= wxClassInfo::FindClass(className
);
1396 return classInfo
->CreateObject();
1405 wxXmlResourceHandler::wxXmlResourceHandler()
1406 : m_node(NULL
), m_parent(NULL
), m_instance(NULL
),
1407 m_parentAsWindow(NULL
)
1412 wxObject
*wxXmlResourceHandler::CreateResource(wxXmlNode
*node
, wxObject
*parent
, wxObject
*instance
)
1414 wxXmlNode
*myNode
= m_node
;
1415 wxString myClass
= m_class
;
1416 wxObject
*myParent
= m_parent
, *myInstance
= m_instance
;
1417 wxWindow
*myParentAW
= m_parentAsWindow
;
1419 m_instance
= instance
;
1420 if (!m_instance
&& node
->HasAttribute(wxT("subclass")) &&
1421 !(m_resource
->GetFlags() & wxXRC_NO_SUBCLASSING
))
1423 wxString subclass
= node
->GetAttribute(wxT("subclass"), wxEmptyString
);
1424 if (!subclass
.empty())
1426 for (wxXmlSubclassFactories::iterator i
= wxXmlResource::ms_subclassFactories
->begin();
1427 i
!= wxXmlResource::ms_subclassFactories
->end(); ++i
)
1429 m_instance
= (*i
)->Create(subclass
);
1436 wxString name
= node
->GetAttribute(wxT("name"), wxEmptyString
);
1442 "subclass \"%s\" not found for resource \"%s\", not subclassing",
1451 m_class
= node
->GetAttribute(wxT("class"), wxEmptyString
);
1453 m_parentAsWindow
= wxDynamicCast(m_parent
, wxWindow
);
1455 wxObject
*returned
= DoCreateResource();
1459 m_parent
= myParent
; m_parentAsWindow
= myParentAW
;
1460 m_instance
= myInstance
;
1466 void wxXmlResourceHandler::AddStyle(const wxString
& name
, int value
)
1468 m_styleNames
.Add(name
);
1469 m_styleValues
.Add(value
);
1474 void wxXmlResourceHandler::AddWindowStyles()
1476 XRC_ADD_STYLE(wxCLIP_CHILDREN
);
1478 // the border styles all have the old and new names, recognize both for now
1479 XRC_ADD_STYLE(wxSIMPLE_BORDER
); XRC_ADD_STYLE(wxBORDER_SIMPLE
);
1480 XRC_ADD_STYLE(wxSUNKEN_BORDER
); XRC_ADD_STYLE(wxBORDER_SUNKEN
);
1481 XRC_ADD_STYLE(wxDOUBLE_BORDER
); XRC_ADD_STYLE(wxBORDER_DOUBLE
); // deprecated
1482 XRC_ADD_STYLE(wxBORDER_THEME
);
1483 XRC_ADD_STYLE(wxRAISED_BORDER
); XRC_ADD_STYLE(wxBORDER_RAISED
);
1484 XRC_ADD_STYLE(wxSTATIC_BORDER
); XRC_ADD_STYLE(wxBORDER_STATIC
);
1485 XRC_ADD_STYLE(wxNO_BORDER
); XRC_ADD_STYLE(wxBORDER_NONE
);
1487 XRC_ADD_STYLE(wxTRANSPARENT_WINDOW
);
1488 XRC_ADD_STYLE(wxWANTS_CHARS
);
1489 XRC_ADD_STYLE(wxTAB_TRAVERSAL
);
1490 XRC_ADD_STYLE(wxNO_FULL_REPAINT_ON_RESIZE
);
1491 XRC_ADD_STYLE(wxFULL_REPAINT_ON_RESIZE
);
1492 XRC_ADD_STYLE(wxALWAYS_SHOW_SB
);
1493 XRC_ADD_STYLE(wxWS_EX_BLOCK_EVENTS
);
1494 XRC_ADD_STYLE(wxWS_EX_VALIDATE_RECURSIVELY
);
1499 bool wxXmlResourceHandler::HasParam(const wxString
& param
)
1501 return (GetParamNode(param
) != NULL
);
1505 int wxXmlResourceHandler::GetStyle(const wxString
& param
, int defaults
)
1507 wxString s
= GetParamValue(param
);
1509 if (!s
) return defaults
;
1511 wxStringTokenizer
tkn(s
, wxT("| \t\n"), wxTOKEN_STRTOK
);
1515 while (tkn
.HasMoreTokens())
1517 fl
= tkn
.GetNextToken();
1518 index
= m_styleNames
.Index(fl
);
1519 if (index
!= wxNOT_FOUND
)
1521 style
|= m_styleValues
[index
];
1528 wxString::Format("unknown style flag \"%s\"", fl
)
1537 wxString
wxXmlResourceHandler::GetText(const wxString
& param
, bool translate
)
1539 wxXmlNode
*parNode
= GetParamNode(param
);
1540 wxString
str1(GetNodeContent(parNode
));
1543 // "\\" wasn't translated to "\" prior to 2.5.3.0:
1544 const bool escapeBackslash
= (m_resource
->CompareVersion(2,5,3,0) >= 0);
1546 // VS: First version of XRC resources used $ instead of & (which is
1547 // illegal in XML), but later I realized that '_' fits this purpose
1548 // much better (because &File means "File with F underlined").
1549 const wxChar amp_char
= (m_resource
->CompareVersion(2,3,0,1) < 0)
1552 for ( wxString::const_iterator dt
= str1
.begin(); dt
!= str1
.end(); ++dt
)
1554 // Remap amp_char to &, map double amp_char to amp_char (for things
1555 // like "&File..." -- this is illegal in XML, so we use "_File..."):
1556 if ( *dt
== amp_char
)
1558 if ( *(++dt
) == amp_char
)
1561 str2
<< wxT('&') << *dt
;
1563 // Remap \n to CR, \r to LF, \t to TAB, \\ to \:
1564 else if ( *dt
== wxT('\\') )
1566 switch ( (*(++dt
)).GetValue() )
1581 // "\\" wasn't translated to "\" prior to 2.5.3.0:
1582 if ( escapeBackslash
)
1587 // else fall-through to default: branch below
1590 str2
<< wxT('\\') << *dt
;
1600 if (m_resource
->GetFlags() & wxXRC_USE_LOCALE
)
1602 if (translate
&& parNode
&&
1603 parNode
->GetAttribute(wxT("translate"), wxEmptyString
) != wxT("0"))
1605 return wxGetTranslation(str2
, m_resource
->GetDomain());
1612 // The string is internally stored as UTF-8, we have to convert
1613 // it into system's default encoding so that it can be displayed:
1614 return wxString(str2
.wc_str(wxConvUTF8
), wxConvLocal
);
1619 // If wxXRC_USE_LOCALE is not set, then the string is already in
1620 // system's default encoding in ANSI build, so we don't have to
1621 // do anything special here.
1627 long wxXmlResourceHandler::GetLong(const wxString
& param
, long defaultv
)
1630 wxString str1
= GetParamValue(param
);
1632 if (!str1
.ToLong(&value
))
1638 float wxXmlResourceHandler::GetFloat(const wxString
& param
, float defaultv
)
1640 wxString str
= GetParamValue(param
);
1642 // strings in XRC always use C locale so make sure to use the
1643 // locale-independent wxString::ToCDouble() and not ToDouble() which uses
1644 // the current locale with a potentially different decimal point character
1646 if (!str
.ToCDouble(&value
))
1649 return wx_truncate_cast(float, value
);
1653 int wxXmlResourceHandler::GetID()
1655 return wxXmlResource::GetXRCID(GetName());
1660 wxString
wxXmlResourceHandler::GetName()
1662 return m_node
->GetAttribute(wxT("name"), wxT("-1"));
1667 bool wxXmlResourceHandler::GetBoolAttr(const wxString
& attr
, bool defaultv
)
1670 return m_node
->GetAttribute(attr
, &v
) ? v
== '1' : defaultv
;
1673 bool wxXmlResourceHandler::GetBool(const wxString
& param
, bool defaultv
)
1675 const wxString v
= GetParamValue(param
);
1677 return v
.empty() ? defaultv
: (v
== '1');
1681 static wxColour
GetSystemColour(const wxString
& name
)
1685 #define SYSCLR(clr) \
1686 if (name == wxT(#clr)) return wxSystemSettings::GetColour(clr);
1687 SYSCLR(wxSYS_COLOUR_SCROLLBAR
)
1688 SYSCLR(wxSYS_COLOUR_BACKGROUND
)
1689 SYSCLR(wxSYS_COLOUR_DESKTOP
)
1690 SYSCLR(wxSYS_COLOUR_ACTIVECAPTION
)
1691 SYSCLR(wxSYS_COLOUR_INACTIVECAPTION
)
1692 SYSCLR(wxSYS_COLOUR_MENU
)
1693 SYSCLR(wxSYS_COLOUR_WINDOW
)
1694 SYSCLR(wxSYS_COLOUR_WINDOWFRAME
)
1695 SYSCLR(wxSYS_COLOUR_MENUTEXT
)
1696 SYSCLR(wxSYS_COLOUR_WINDOWTEXT
)
1697 SYSCLR(wxSYS_COLOUR_CAPTIONTEXT
)
1698 SYSCLR(wxSYS_COLOUR_ACTIVEBORDER
)
1699 SYSCLR(wxSYS_COLOUR_INACTIVEBORDER
)
1700 SYSCLR(wxSYS_COLOUR_APPWORKSPACE
)
1701 SYSCLR(wxSYS_COLOUR_HIGHLIGHT
)
1702 SYSCLR(wxSYS_COLOUR_HIGHLIGHTTEXT
)
1703 SYSCLR(wxSYS_COLOUR_BTNFACE
)
1704 SYSCLR(wxSYS_COLOUR_3DFACE
)
1705 SYSCLR(wxSYS_COLOUR_BTNSHADOW
)
1706 SYSCLR(wxSYS_COLOUR_3DSHADOW
)
1707 SYSCLR(wxSYS_COLOUR_GRAYTEXT
)
1708 SYSCLR(wxSYS_COLOUR_BTNTEXT
)
1709 SYSCLR(wxSYS_COLOUR_INACTIVECAPTIONTEXT
)
1710 SYSCLR(wxSYS_COLOUR_BTNHIGHLIGHT
)
1711 SYSCLR(wxSYS_COLOUR_BTNHILIGHT
)
1712 SYSCLR(wxSYS_COLOUR_3DHIGHLIGHT
)
1713 SYSCLR(wxSYS_COLOUR_3DHILIGHT
)
1714 SYSCLR(wxSYS_COLOUR_3DDKSHADOW
)
1715 SYSCLR(wxSYS_COLOUR_3DLIGHT
)
1716 SYSCLR(wxSYS_COLOUR_INFOTEXT
)
1717 SYSCLR(wxSYS_COLOUR_INFOBK
)
1718 SYSCLR(wxSYS_COLOUR_LISTBOX
)
1719 SYSCLR(wxSYS_COLOUR_HOTLIGHT
)
1720 SYSCLR(wxSYS_COLOUR_GRADIENTACTIVECAPTION
)
1721 SYSCLR(wxSYS_COLOUR_GRADIENTINACTIVECAPTION
)
1722 SYSCLR(wxSYS_COLOUR_MENUHILIGHT
)
1723 SYSCLR(wxSYS_COLOUR_MENUBAR
)
1727 return wxNullColour
;
1730 wxColour
wxXmlResourceHandler::GetColour(const wxString
& param
, const wxColour
& defaultv
)
1732 wxString v
= GetParamValue(param
);
1739 // wxString -> wxColour conversion
1742 // the colour doesn't use #RRGGBB format, check if it is symbolic
1744 clr
= GetSystemColour(v
);
1751 wxString::Format("incorrect colour specification \"%s\"", v
)
1753 return wxNullColour
;
1762 // if 'param' has stock_id/stock_client, extracts them and returns true
1763 bool GetStockArtAttrs(const wxXmlNode
*paramNode
,
1764 const wxString
& defaultArtClient
,
1765 wxString
& art_id
, wxString
& art_client
)
1769 art_id
= paramNode
->GetAttribute("stock_id", "");
1771 if ( !art_id
.empty() )
1773 art_id
= wxART_MAKE_ART_ID_FROM_STR(art_id
);
1775 art_client
= paramNode
->GetAttribute("stock_client", "");
1776 if ( art_client
.empty() )
1777 art_client
= defaultArtClient
;
1779 art_client
= wxART_MAKE_CLIENT_ID_FROM_STR(art_client
);
1788 } // anonymous namespace
1790 wxBitmap
wxXmlResourceHandler::GetBitmap(const wxString
& param
,
1791 const wxArtClient
& defaultArtClient
,
1794 // it used to be possible to pass an empty string here to indicate that the
1795 // bitmap name should be read from this node itself but this is not
1796 // supported any more because GetBitmap(m_node) can be used directly
1798 wxASSERT_MSG( !param
.empty(), "bitmap parameter name can't be empty" );
1800 const wxXmlNode
* const node
= GetParamNode(param
);
1804 // this is not an error as bitmap parameter could be optional
1805 return wxNullBitmap
;
1808 return GetBitmap(node
, defaultArtClient
, size
);
1811 wxBitmap
wxXmlResourceHandler::GetBitmap(const wxXmlNode
* node
,
1812 const wxArtClient
& defaultArtClient
,
1815 wxCHECK_MSG( node
, wxNullBitmap
, "bitmap node can't be NULL" );
1817 /* If the bitmap is specified as stock item, query wxArtProvider for it: */
1818 wxString art_id
, art_client
;
1819 if ( GetStockArtAttrs(node
, defaultArtClient
,
1820 art_id
, art_client
) )
1822 wxBitmap
stockArt(wxArtProvider::GetBitmap(art_id
, art_client
, size
));
1823 if ( stockArt
.Ok() )
1827 /* ...or load the bitmap from file: */
1828 wxString name
= GetParamValue(node
);
1829 if (name
.empty()) return wxNullBitmap
;
1830 #if wxUSE_FILESYSTEM
1831 wxFSFile
*fsfile
= GetCurFileSystem().OpenFile(name
, wxFS_READ
| wxFS_SEEKABLE
);
1837 wxString::Format("cannot open bitmap resource \"%s\"", name
)
1839 return wxNullBitmap
;
1841 wxImage
img(*(fsfile
->GetStream()));
1852 wxString::Format("cannot create bitmap from \"%s\"", name
)
1854 return wxNullBitmap
;
1856 if (!(size
== wxDefaultSize
)) img
.Rescale(size
.x
, size
.y
);
1857 return wxBitmap(img
);
1861 wxIcon
wxXmlResourceHandler::GetIcon(const wxString
& param
,
1862 const wxArtClient
& defaultArtClient
,
1865 // see comment in GetBitmap(wxString) overload
1866 wxASSERT_MSG( !param
.empty(), "icon parameter name can't be empty" );
1868 const wxXmlNode
* const node
= GetParamNode(param
);
1872 // this is not an error as icon parameter could be optional
1876 return GetIcon(node
, defaultArtClient
, size
);
1879 wxIcon
wxXmlResourceHandler::GetIcon(const wxXmlNode
* node
,
1880 const wxArtClient
& defaultArtClient
,
1884 icon
.CopyFromBitmap(GetBitmap(node
, defaultArtClient
, size
));
1889 wxIconBundle
wxXmlResourceHandler::GetIconBundle(const wxString
& param
,
1890 const wxArtClient
& defaultArtClient
)
1892 wxString art_id
, art_client
;
1893 if ( GetStockArtAttrs(GetParamNode(param
), defaultArtClient
,
1894 art_id
, art_client
) )
1896 wxIconBundle
stockArt(wxArtProvider::GetIconBundle(art_id
, art_client
));
1897 if ( stockArt
.IsOk() )
1901 const wxString name
= GetParamValue(param
);
1903 return wxNullIconBundle
;
1905 #if wxUSE_FILESYSTEM
1906 wxFSFile
*fsfile
= GetCurFileSystem().OpenFile(name
, wxFS_READ
| wxFS_SEEKABLE
);
1907 if ( fsfile
== NULL
)
1912 wxString::Format("cannot open icon resource \"%s\"", name
)
1914 return wxNullIconBundle
;
1917 wxIconBundle
bundle(*(fsfile
->GetStream()));
1920 wxIconBundle
bundle(name
);
1923 if ( !bundle
.IsOk() )
1928 wxString::Format("cannot create icon from \"%s\"", name
)
1930 return wxNullIconBundle
;
1937 wxImageList
*wxXmlResourceHandler::GetImageList(const wxString
& param
)
1939 wxXmlNode
* const imagelist_node
= GetParamNode(param
);
1940 if ( !imagelist_node
)
1943 wxXmlNode
* const oldnode
= m_node
;
1944 m_node
= imagelist_node
;
1946 // Get the size if we have it, otherwise we will use the size of the first
1948 wxSize size
= GetSize();
1950 // Start adding images, we'll create the image list when adding the first
1952 wxImageList
* imagelist
= NULL
;
1953 wxString parambitmap
= wxT("bitmap");
1954 if ( HasParam(parambitmap
) )
1956 wxXmlNode
*n
= m_node
->GetChildren();
1959 if (n
->GetType() == wxXML_ELEMENT_NODE
&& n
->GetName() == parambitmap
)
1961 wxIcon icon
= GetIcon(n
);
1964 // We need the real image list size to create it.
1965 if ( size
== wxDefaultSize
)
1966 size
= icon
.GetSize();
1968 // We use the mask by default.
1969 bool mask
= !HasParam(wxS("mask")) || GetBool(wxS("mask"));
1971 imagelist
= new wxImageList(size
.x
, size
.y
, mask
);
1974 // add icon instead of bitmap to keep the bitmap mask
1975 imagelist
->Add(icon
);
1985 wxXmlNode
*wxXmlResourceHandler::GetParamNode(const wxString
& param
)
1987 wxCHECK_MSG(m_node
, NULL
, wxT("You can't access handler data before it was initialized!"));
1989 wxXmlNode
*n
= m_node
->GetChildren();
1993 if (n
->GetType() == wxXML_ELEMENT_NODE
&& n
->GetName() == param
)
1995 // TODO: check that there are no other properties/parameters with
1996 // the same name and log an error if there are (can't do this
1997 // right now as I'm not sure if it's not going to break code
1998 // using this function in unintentional way (i.e. for
1999 // accessing other things than properties), for example
2000 // wxBitmapComboBoxXmlHandler almost surely does
2009 bool wxXmlResourceHandler::IsOfClass(wxXmlNode
*node
, const wxString
& classname
)
2011 return node
->GetAttribute(wxT("class")) == classname
;
2016 wxString
wxXmlResourceHandler::GetNodeContent(const wxXmlNode
*node
)
2018 const wxXmlNode
*n
= node
;
2019 if (n
== NULL
) return wxEmptyString
;
2020 n
= n
->GetChildren();
2024 if (n
->GetType() == wxXML_TEXT_NODE
||
2025 n
->GetType() == wxXML_CDATA_SECTION_NODE
)
2026 return n
->GetContent();
2029 return wxEmptyString
;
2034 wxString
wxXmlResourceHandler::GetParamValue(const wxString
& param
)
2037 return GetNodeContent(m_node
);
2039 return GetNodeContent(GetParamNode(param
));
2042 wxString
wxXmlResourceHandler::GetParamValue(const wxXmlNode
* node
)
2044 return GetNodeContent(node
);
2048 wxSize
wxXmlResourceHandler::GetSize(const wxString
& param
,
2049 wxWindow
*windowToUse
)
2051 wxString s
= GetParamValue(param
);
2052 if (s
.empty()) s
= wxT("-1,-1");
2056 is_dlg
= s
[s
.length()-1] == wxT('d');
2057 if (is_dlg
) s
.RemoveLast();
2059 if (!s
.BeforeFirst(wxT(',')).ToLong(&sx
) ||
2060 !s
.AfterLast(wxT(',')).ToLong(&sy
))
2065 wxString::Format("cannot parse coordinates value \"%s\"", s
)
2067 return wxDefaultSize
;
2074 return wxDLG_UNIT(windowToUse
, wxSize(sx
, sy
));
2076 else if (m_parentAsWindow
)
2078 return wxDLG_UNIT(m_parentAsWindow
, wxSize(sx
, sy
));
2085 "cannot convert dialog units: dialog unknown"
2087 return wxDefaultSize
;
2091 return wxSize(sx
, sy
);
2096 wxPoint
wxXmlResourceHandler::GetPosition(const wxString
& param
)
2098 wxSize sz
= GetSize(param
);
2099 return wxPoint(sz
.x
, sz
.y
);
2104 wxCoord
wxXmlResourceHandler::GetDimension(const wxString
& param
,
2106 wxWindow
*windowToUse
)
2108 wxString s
= GetParamValue(param
);
2109 if (s
.empty()) return defaultv
;
2113 is_dlg
= s
[s
.length()-1] == wxT('d');
2114 if (is_dlg
) s
.RemoveLast();
2121 wxString::Format("cannot parse dimension value \"%s\"", s
)
2130 return wxDLG_UNIT(windowToUse
, wxSize(sx
, 0)).x
;
2132 else if (m_parentAsWindow
)
2134 return wxDLG_UNIT(m_parentAsWindow
, wxSize(sx
, 0)).x
;
2141 "cannot convert dialog units: dialog unknown"
2151 // Get system font index using indexname
2152 static wxFont
GetSystemFont(const wxString
& name
)
2156 #define SYSFNT(fnt) \
2157 if (name == wxT(#fnt)) return wxSystemSettings::GetFont(fnt);
2158 SYSFNT(wxSYS_OEM_FIXED_FONT
)
2159 SYSFNT(wxSYS_ANSI_FIXED_FONT
)
2160 SYSFNT(wxSYS_ANSI_VAR_FONT
)
2161 SYSFNT(wxSYS_SYSTEM_FONT
)
2162 SYSFNT(wxSYS_DEVICE_DEFAULT_FONT
)
2163 SYSFNT(wxSYS_SYSTEM_FIXED_FONT
)
2164 SYSFNT(wxSYS_DEFAULT_GUI_FONT
)
2171 wxFont
wxXmlResourceHandler::GetFont(const wxString
& param
)
2173 wxXmlNode
*font_node
= GetParamNode(param
);
2174 if (font_node
== NULL
)
2177 wxString::Format("cannot find font node \"%s\"", param
));
2181 wxXmlNode
*oldnode
= m_node
;
2188 bool hasSize
= HasParam(wxT("size"));
2190 isize
= GetLong(wxT("size"), -1);
2193 int istyle
= wxNORMAL
;
2194 bool hasStyle
= HasParam(wxT("style"));
2197 wxString style
= GetParamValue(wxT("style"));
2198 if (style
== wxT("italic"))
2200 else if (style
== wxT("slant"))
2205 int iweight
= wxNORMAL
;
2206 bool hasWeight
= HasParam(wxT("weight"));
2209 wxString weight
= GetParamValue(wxT("weight"));
2210 if (weight
== wxT("bold"))
2212 else if (weight
== wxT("light"))
2217 bool hasUnderlined
= HasParam(wxT("underlined"));
2218 bool underlined
= hasUnderlined
? GetBool(wxT("underlined"), false) : false;
2220 // family and facename
2221 int ifamily
= wxDEFAULT
;
2222 bool hasFamily
= HasParam(wxT("family"));
2225 wxString family
= GetParamValue(wxT("family"));
2226 if (family
== wxT("decorative")) ifamily
= wxDECORATIVE
;
2227 else if (family
== wxT("roman")) ifamily
= wxROMAN
;
2228 else if (family
== wxT("script")) ifamily
= wxSCRIPT
;
2229 else if (family
== wxT("swiss")) ifamily
= wxSWISS
;
2230 else if (family
== wxT("modern")) ifamily
= wxMODERN
;
2231 else if (family
== wxT("teletype")) ifamily
= wxTELETYPE
;
2236 bool hasFacename
= HasParam(wxT("face"));
2239 wxString faces
= GetParamValue(wxT("face"));
2240 wxStringTokenizer
tk(faces
, wxT(","));
2242 wxArrayString
facenames(wxFontEnumerator::GetFacenames());
2243 while (tk
.HasMoreTokens())
2245 int index
= facenames
.Index(tk
.GetNextToken(), false);
2246 if (index
!= wxNOT_FOUND
)
2248 facename
= facenames
[index
];
2252 #else // !wxUSE_FONTENUM
2253 // just use the first face name if we can't check its availability:
2254 if (tk
.HasMoreTokens())
2255 facename
= tk
.GetNextToken();
2256 #endif // wxUSE_FONTENUM/!wxUSE_FONTENUM
2260 wxFontEncoding enc
= wxFONTENCODING_DEFAULT
;
2261 bool hasEncoding
= HasParam(wxT("encoding"));
2265 wxString encoding
= GetParamValue(wxT("encoding"));
2266 wxFontMapper mapper
;
2267 if (!encoding
.empty())
2268 enc
= mapper
.CharsetToEncoding(encoding
);
2269 if (enc
== wxFONTENCODING_SYSTEM
)
2270 enc
= wxFONTENCODING_DEFAULT
;
2272 #endif // wxUSE_FONTMAP
2274 // is this font based on a system font?
2275 wxFont font
= GetSystemFont(GetParamValue(wxT("sysfont")));
2279 if (hasSize
&& isize
!= -1)
2280 font
.SetPointSize(isize
);
2281 else if (HasParam(wxT("relativesize")))
2282 font
.SetPointSize(int(font
.GetPointSize() *
2283 GetFloat(wxT("relativesize"))));
2286 font
.SetStyle(istyle
);
2288 font
.SetWeight(iweight
);
2290 font
.SetUnderlined(underlined
);
2292 font
.SetFamily(ifamily
);
2294 font
.SetFaceName(facename
);
2296 font
.SetDefaultEncoding(enc
);
2298 else // not based on system font
2300 font
= wxFont(isize
== -1 ? wxNORMAL_FONT
->GetPointSize() : isize
,
2301 ifamily
, istyle
, iweight
,
2302 underlined
, facename
, enc
);
2310 void wxXmlResourceHandler::SetupWindow(wxWindow
*wnd
)
2312 //FIXME : add cursor
2314 if (HasParam(wxT("exstyle")))
2315 // Have to OR it with existing style, since
2316 // some implementations (e.g. wxGTK) use the extra style
2318 wnd
->SetExtraStyle(wnd
->GetExtraStyle() | GetStyle(wxT("exstyle")));
2319 if (HasParam(wxT("bg")))
2320 wnd
->SetBackgroundColour(GetColour(wxT("bg")));
2321 if (HasParam(wxT("ownbg")))
2322 wnd
->SetOwnBackgroundColour(GetColour(wxT("ownbg")));
2323 if (HasParam(wxT("fg")))
2324 wnd
->SetForegroundColour(GetColour(wxT("fg")));
2325 if (HasParam(wxT("ownfg")))
2326 wnd
->SetOwnForegroundColour(GetColour(wxT("ownfg")));
2327 if (GetBool(wxT("enabled"), 1) == 0)
2329 if (GetBool(wxT("focused"), 0) == 1)
2331 if (GetBool(wxT("hidden"), 0) == 1)
2334 if (HasParam(wxT("tooltip")))
2335 wnd
->SetToolTip(GetText(wxT("tooltip")));
2337 if (HasParam(wxT("font")))
2338 wnd
->SetFont(GetFont(wxT("font")));
2339 if (HasParam(wxT("ownfont")))
2340 wnd
->SetOwnFont(GetFont(wxT("ownfont")));
2341 if (HasParam(wxT("help")))
2342 wnd
->SetHelpText(GetText(wxT("help")));
2346 void wxXmlResourceHandler::CreateChildren(wxObject
*parent
, bool this_hnd_only
)
2348 for ( wxXmlNode
*n
= m_node
->GetChildren(); n
; n
= n
->GetNext() )
2350 if ( IsObjectNode(n
) )
2352 m_resource
->DoCreateResFromNode(*n
, parent
, NULL
,
2353 this_hnd_only
? this : NULL
);
2359 void wxXmlResourceHandler::CreateChildrenPrivately(wxObject
*parent
, wxXmlNode
*rootnode
)
2362 if (rootnode
== NULL
) root
= m_node
; else root
= rootnode
;
2363 wxXmlNode
*n
= root
->GetChildren();
2367 if (n
->GetType() == wxXML_ELEMENT_NODE
&& CanHandle(n
))
2369 CreateResource(n
, parent
, NULL
);
2376 //-----------------------------------------------------------------------------
2378 //-----------------------------------------------------------------------------
2380 void wxXmlResourceHandler::ReportError(const wxString
& message
)
2382 m_resource
->ReportError(m_node
, message
);
2385 void wxXmlResourceHandler::ReportError(wxXmlNode
*context
,
2386 const wxString
& message
)
2388 m_resource
->ReportError(context
? context
: m_node
, message
);
2391 void wxXmlResourceHandler::ReportParamError(const wxString
& param
,
2392 const wxString
& message
)
2394 m_resource
->ReportError(GetParamNode(param
), message
);
2397 void wxXmlResource::ReportError(const wxXmlNode
*context
, const wxString
& message
)
2401 DoReportError("", NULL
, message
);
2405 // We need to find out the file that 'context' is part of. Performance of
2406 // this code is not critical, so we simply find the root XML node and
2407 // compare it with all loaded XRC files.
2408 const wxString filename
= GetFileNameFromNode(context
, Data());
2410 DoReportError(filename
, context
, message
);
2413 void wxXmlResource::DoReportError(const wxString
& xrcFile
, const wxXmlNode
*position
,
2414 const wxString
& message
)
2416 const int line
= position
? position
->GetLineNumber() : -1;
2419 if ( !xrcFile
.empty() )
2420 loc
= xrcFile
+ ':';
2422 loc
+= wxString::Format("%d:", line
);
2426 wxLogError("XRC error: %s%s", loc
, message
);
2430 //-----------------------------------------------------------------------------
2431 // XRCID implementation
2432 //-----------------------------------------------------------------------------
2434 #define XRCID_TABLE_SIZE 1024
2439 /* Hold the id so that once an id is allocated for a name, it
2440 does not get created again by NewControlId at least
2441 until we are done with it */
2447 static XRCID_record
*XRCID_Records
[XRCID_TABLE_SIZE
] = {NULL
};
2449 // Extremely simplistic hash function which probably ought to be replaced with
2450 // wxStringHash::stringHash().
2451 static inline unsigned XRCIdHash(const char *str_id
)
2455 for (const char *c
= str_id
; *c
!= '\0'; c
++) index
+= (unsigned int)*c
;
2456 index
%= XRCID_TABLE_SIZE
;
2461 static int XRCID_Lookup(const char *str_id
, int value_if_not_found
= wxID_NONE
)
2463 const unsigned index
= XRCIdHash(str_id
);
2466 XRCID_record
*oldrec
= NULL
;
2467 for (XRCID_record
*rec
= XRCID_Records
[index
]; rec
; rec
= rec
->next
)
2469 if (wxStrcmp(rec
->key
, str_id
) == 0)
2476 XRCID_record
**rec_var
= (oldrec
== NULL
) ?
2477 &XRCID_Records
[index
] : &oldrec
->next
;
2478 *rec_var
= new XRCID_record
;
2479 (*rec_var
)->key
= wxStrdup(str_id
);
2480 (*rec_var
)->next
= NULL
;
2483 if (value_if_not_found
!= wxID_NONE
)
2484 (*rec_var
)->id
= value_if_not_found
;
2487 int asint
= wxStrtol(str_id
, &end
, 10);
2488 if (*str_id
&& *end
== 0)
2490 // if str_id was integer, keep it verbosely:
2491 (*rec_var
)->id
= asint
;
2495 (*rec_var
)->id
= wxWindowBase::NewControlId();
2499 return (*rec_var
)->id
;
2505 // flag indicating whether standard XRC ids were already initialized
2506 static bool gs_stdIDsAdded
= false;
2508 void AddStdXRCID_Records()
2510 #define stdID(id) XRCID_Lookup(#id, id)
2514 stdID(wxID_SEPARATOR
);
2527 stdID(wxID_PRINT_SETUP
);
2528 stdID(wxID_PAGE_SETUP
);
2529 stdID(wxID_PREVIEW
);
2531 stdID(wxID_HELP_CONTENTS
);
2532 stdID(wxID_HELP_COMMANDS
);
2533 stdID(wxID_HELP_PROCEDURES
);
2534 stdID(wxID_HELP_CONTEXT
);
2535 stdID(wxID_CLOSE_ALL
);
2536 stdID(wxID_PREFERENCES
);
2543 stdID(wxID_DUPLICATE
);
2544 stdID(wxID_SELECTALL
);
2546 stdID(wxID_REPLACE
);
2547 stdID(wxID_REPLACE_ALL
);
2548 stdID(wxID_PROPERTIES
);
2549 stdID(wxID_VIEW_DETAILS
);
2550 stdID(wxID_VIEW_LARGEICONS
);
2551 stdID(wxID_VIEW_SMALLICONS
);
2552 stdID(wxID_VIEW_LIST
);
2553 stdID(wxID_VIEW_SORTDATE
);
2554 stdID(wxID_VIEW_SORTNAME
);
2555 stdID(wxID_VIEW_SORTSIZE
);
2556 stdID(wxID_VIEW_SORTTYPE
);
2572 stdID(wxID_FORWARD
);
2573 stdID(wxID_BACKWARD
);
2574 stdID(wxID_DEFAULT
);
2578 stdID(wxID_CONTEXT_HELP
);
2579 stdID(wxID_YESTOALL
);
2580 stdID(wxID_NOTOALL
);
2589 stdID(wxID_REFRESH
);
2594 stdID(wxID_JUSTIFY_CENTER
);
2595 stdID(wxID_JUSTIFY_FILL
);
2596 stdID(wxID_JUSTIFY_RIGHT
);
2597 stdID(wxID_JUSTIFY_LEFT
);
2598 stdID(wxID_UNDERLINE
);
2600 stdID(wxID_UNINDENT
);
2601 stdID(wxID_ZOOM_100
);
2602 stdID(wxID_ZOOM_FIT
);
2603 stdID(wxID_ZOOM_IN
);
2604 stdID(wxID_ZOOM_OUT
);
2605 stdID(wxID_UNDELETE
);
2606 stdID(wxID_REVERT_TO_SAVED
);
2607 stdID(wxID_SYSTEM_MENU
);
2608 stdID(wxID_CLOSE_FRAME
);
2609 stdID(wxID_MOVE_FRAME
);
2610 stdID(wxID_RESIZE_FRAME
);
2611 stdID(wxID_MAXIMIZE_FRAME
);
2612 stdID(wxID_ICONIZE_FRAME
);
2613 stdID(wxID_RESTORE_FRAME
);
2615 stdID(wxID_CONVERT
);
2616 stdID(wxID_EXECUTE
);
2618 stdID(wxID_HARDDISK
);
2624 stdID(wxID_JUMP_TO
);
2625 stdID(wxID_NETWORK
);
2626 stdID(wxID_SELECT_COLOR
);
2627 stdID(wxID_SELECT_FONT
);
2628 stdID(wxID_SORT_ASCENDING
);
2629 stdID(wxID_SORT_DESCENDING
);
2630 stdID(wxID_SPELL_CHECK
);
2631 stdID(wxID_STRIKETHROUGH
);
2636 } // anonymous namespace
2640 int wxXmlResource::DoGetXRCID(const char *str_id
, int value_if_not_found
)
2642 if ( !gs_stdIDsAdded
)
2644 gs_stdIDsAdded
= true;
2645 AddStdXRCID_Records();
2648 return XRCID_Lookup(str_id
, value_if_not_found
);
2652 wxString
wxXmlResource::FindXRCIDById(int numId
)
2654 for ( int i
= 0; i
< XRCID_TABLE_SIZE
; i
++ )
2656 for ( XRCID_record
*rec
= XRCID_Records
[i
]; rec
; rec
= rec
->next
)
2658 if ( rec
->id
== numId
)
2659 return wxString(rec
->key
);
2667 void wxIdRangeManager::RemoveXRCIDEntry(const wxString
& idstr
)
2669 const char *str_id
= idstr
.mb_str();
2671 const unsigned index
= XRCIdHash(str_id
);
2673 XRCID_record
**p_previousrec
= &XRCID_Records
[index
];
2674 for (XRCID_record
*rec
= XRCID_Records
[index
]; rec
; rec
= rec
->next
)
2676 if (wxStrcmp(rec
->key
, str_id
) == 0)
2678 // Found the item to be removed so delete its record; but first
2679 // remove it from the linked list.
2680 *p_previousrec
= rec
->next
;
2686 p_previousrec
= &rec
->next
;
2690 static void CleanXRCID_Record(XRCID_record
*rec
)
2694 CleanXRCID_Record(rec
->next
);
2701 static void CleanXRCID_Records()
2703 for (int i
= 0; i
< XRCID_TABLE_SIZE
; i
++)
2705 CleanXRCID_Record(XRCID_Records
[i
]);
2706 XRCID_Records
[i
] = NULL
;
2709 gs_stdIDsAdded
= false;
2713 //-----------------------------------------------------------------------------
2714 // module and globals
2715 //-----------------------------------------------------------------------------
2717 // normally we would do the cleanup from wxXmlResourceModule::OnExit() but it
2718 // can happen that some XRC records have been created because of the use of
2719 // XRCID() in event tables, which happens during static objects initialization,
2720 // but then the application initialization failed and so the wx modules were
2721 // neither initialized nor cleaned up -- this static object does the cleanup in
2723 static struct wxXRCStaticCleanup
2725 ~wxXRCStaticCleanup() { CleanXRCID_Records(); }
2728 class wxXmlResourceModule
: public wxModule
2730 DECLARE_DYNAMIC_CLASS(wxXmlResourceModule
)
2732 wxXmlResourceModule() {}
2735 wxXmlResource::AddSubclassFactory(new wxXmlSubclassFactoryCXX
);
2740 delete wxXmlResource::Set(NULL
);
2741 delete wxIdRangeManager::Set(NULL
);
2742 if(wxXmlResource::ms_subclassFactories
)
2744 for ( wxXmlSubclassFactories::iterator i
= wxXmlResource::ms_subclassFactories
->begin();
2745 i
!= wxXmlResource::ms_subclassFactories
->end(); ++i
)
2749 wxDELETE(wxXmlResource::ms_subclassFactories
);
2751 CleanXRCID_Records();
2755 IMPLEMENT_DYNAMIC_CLASS(wxXmlResourceModule
, wxModule
)
2758 // When wxXml is loaded dynamically after the application is already running
2759 // then the built-in module system won't pick this one up. Add it manually.
2760 void wxXmlInitResourceModule()
2762 wxModule
* module = new wxXmlResourceModule
;
2764 wxModule::RegisterModule(module);