]> git.saurik.com Git - wxWidgets.git/blame - src/xrc/xmlres.cpp
Set C++ global locale too in wxAppTraitsBase::SetLocale().
[wxWidgets.git] / src / xrc / xmlres.cpp
CommitLineData
78d14f80 1/////////////////////////////////////////////////////////////////////////////
88a7a4e1 2// Name: src/xrc/xmlres.cpp
b5d6954b 3// Purpose: XRC resources
78d14f80
VS
4// Author: Vaclav Slavik
5// Created: 2000/03/05
6// RCS-ID: $Id$
7// Copyright: (c) 2000 Vaclav Slavik
8// Licence: wxWindows licence
9/////////////////////////////////////////////////////////////////////////////
10
78d14f80
VS
11// For compilers that support precompilation, includes "wx.h".
12#include "wx/wxprec.h"
13
14#ifdef __BORLANDC__
15 #pragma hdrstop
16#endif
17
621be1ec 18#if wxUSE_XRC
a1e4ec87 19
88a7a4e1
WS
20#include "wx/xrc/xmlres.h"
21
22#ifndef WX_PRECOMP
23 #include "wx/intl.h"
e4db172a 24 #include "wx/log.h"
8e609c82 25 #include "wx/panel.h"
76b49cf4 26 #include "wx/frame.h"
fdf565fe 27 #include "wx/dialog.h"
9eddec69 28 #include "wx/settings.h"
0bca0373 29 #include "wx/bitmap.h"
155ecd4c 30 #include "wx/image.h"
02761f6c 31 #include "wx/module.h"
193d0c93 32 #include "wx/wxcrtvararg.h"
88a7a4e1
WS
33#endif
34
e7a3a5a5 35#ifndef __WXWINCE__
88a7a4e1 36 #include <locale.h>
e7a3a5a5 37#endif
1df61962 38
eb2d0d23 39#include "wx/vector.h"
78d14f80
VS
40#include "wx/wfstream.h"
41#include "wx/filesys.h"
317a0d73 42#include "wx/filename.h"
78d14f80
VS
43#include "wx/tokenzr.h"
44#include "wx/fontenum.h"
78d14f80 45#include "wx/fontmap.h"
af1337b0 46#include "wx/artprov.h"
326462ae 47#include "wx/imaglist.h"
2bb9a404 48#include "wx/dir.h"
34c6bbee 49#include "wx/xml/xml.h"
0526c8cc 50#include "wx/hashset.h"
9fc5a47c 51#include "wx/scopedptr.h"
78d14f80 52
9fc5a47c
VZ
53namespace
54{
55
56// Helper function to get modification time of either a wxFileSystem URI or
57// just a normal file name, depending on the build.
58#if wxUSE_DATETIME
59
60wxDateTime GetXRCFileModTime(const wxString& filename)
61{
62#if wxUSE_FILESYSTEM
63 wxFileSystem fsys;
64 wxScopedPtr<wxFSFile> file(fsys.OpenFile(filename));
65
66 return file ? file->GetModificationTime() : wxDateTime();
67#else // wxUSE_FILESYSTEM
68 return wxDateTime(wxFileModificationTime(filename));
69#endif // wxUSE_FILESYSTEM
70}
71
72#endif // wxUSE_DATETIME
73
74} // anonymous namespace
f35fdf7e 75
d265ec6b
VZ
76// Assign the given value to the specified entry or add a new value with this
77// name.
3cf2fe54 78static void XRCID_Assign(const wxString& str_id, int value);
d265ec6b 79
eb2d0d23
VS
80class wxXmlResourceDataRecord
81{
82public:
9fc5a47c
VZ
83 // Ctor takes ownership of the document pointer.
84 wxXmlResourceDataRecord(const wxString& File_,
85 wxXmlDocument *Doc_
86 )
87 : File(File_), Doc(Doc_)
88 {
eb2d0d23 89#if wxUSE_DATETIME
9fc5a47c 90 Time = GetXRCFileModTime(File);
eb2d0d23
VS
91#endif
92 }
9fc5a47c 93
eb2d0d23
VS
94 ~wxXmlResourceDataRecord() {delete Doc;}
95
96 wxString File;
97 wxXmlDocument *Doc;
98#if wxUSE_DATETIME
99 wxDateTime Time;
100#endif
9fc5a47c
VZ
101
102 wxDECLARE_NO_COPY_CLASS(wxXmlResourceDataRecord);
eb2d0d23
VS
103};
104
f396e5a7 105class wxXmlResourceDataRecords : public wxVector<wxXmlResourceDataRecord*>
eb2d0d23
VS
106{
107 // this is a class so that it can be forward-declared
108};
78d14f80 109
7a7fa93b 110WX_DECLARE_HASH_SET_PTR(int, wxIntegerHash, wxIntegerEqual, wxHashSetInt);
0526c8cc
VZ
111
112class wxIdRange // Holds data for a particular rangename
113{
114protected:
115 wxIdRange(const wxXmlNode* node,
116 const wxString& rname,
117 const wxString& startno,
118 const wxString& rsize);
119
120 // Note the existence of an item within the range
121 void NoteItem(const wxXmlNode* node, const wxString& item);
122
123 // The manager is telling us that it's finished adding items
124 void Finalise(const wxXmlNode* node);
125
126 wxString GetName() const { return m_name; }
127 bool IsFinalised() const { return m_finalised; }
128
129 const wxString m_name;
130 int m_start;
131 int m_end;
132 unsigned int m_size;
133 bool m_item_end_found;
134 bool m_finalised;
135 wxHashSetInt m_indices;
136
137 friend class wxIdRangeManager;
138};
139
140class wxIdRangeManager
141{
142public:
143 ~wxIdRangeManager();
144 // Gets the global resources object or creates one if none exists.
145 static wxIdRangeManager *Get();
146
147 // Sets the global resources object and returns a pointer to the previous
148 // one (may be NULL).
149 static wxIdRangeManager *Set(wxIdRangeManager *res);
150
151 // Create a new IDrange from this node
152 void AddRange(const wxXmlNode* node);
153 // Tell the IdRange that this item exists, and should be pre-allocated an ID
154 void NotifyRangeOfItem(const wxXmlNode* node, const wxString& item) const;
155 // Tells all IDranges that they're now complete, and can create their IDs
156 void FinaliseRanges(const wxXmlNode* node) const;
157 // Searches for a known IdRange matching 'name', returning its index or -1
158 int Find(const wxString& rangename) const;
0526c8cc
VZ
159
160protected:
161 wxIdRange* FindRangeForItem(const wxXmlNode* node,
162 const wxString& item,
163 wxString& value) const;
164 wxVector<wxIdRange*> m_IdRanges;
165
166private:
167 static wxIdRangeManager *ms_instance;
168};
169
23239d94
VZ
170namespace
171{
172
173// helper used by DoFindResource() and elsewhere: returns true if this is an
174// object or object_ref node
175//
176// node must be non-NULL
177inline bool IsObjectNode(wxXmlNode *node)
178{
179 return node->GetType() == wxXML_ELEMENT_NODE &&
180 (node->GetName() == wxS("object") ||
181 node->GetName() == wxS("object_ref"));
182}
183
a1eeda0b
VS
184// special XML attribute with name of input file, see GetFileNameFromNode()
185const char *ATTR_INPUT_FILENAME = "__wx:filename";
186
187// helper to get filename corresponding to an XML node
188wxString
1f6ea935 189GetFileNameFromNode(const wxXmlNode *node, const wxXmlResourceDataRecords& files)
a1eeda0b
VS
190{
191 // this loop does two things: it looks for ATTR_INPUT_FILENAME among
192 // parents and if it isn't used, it finds the root of the XML tree 'node'
193 // is in
194 for ( ;; )
195 {
196 // in some rare cases (specifically, when an <object_ref> is used, see
197 // wxXmlResource::CreateResFromNode() and MergeNodesOver()), we work
198 // with XML nodes that are not rooted in any document from 'files'
199 // (because a new node was created by CreateResFromNode() to merge the
200 // content of <object_ref> and the referenced <object>); in that case,
201 // we hack around the problem by putting the information about input
202 // file into a custom attribute
203 if ( node->HasAttribute(ATTR_INPUT_FILENAME) )
204 return node->GetAttribute(ATTR_INPUT_FILENAME);
205
206 if ( !node->GetParent() )
207 break; // we found the root of this XML tree
208
209 node = node->GetParent();
210 }
211
212 // NB: 'node' now points to the root of XML document
213
214 for ( wxXmlResourceDataRecords::const_iterator i = files.begin();
215 i != files.end(); ++i )
216 {
217 if ( (*i)->Doc->GetRoot() == node )
218 {
219 return (*i)->File;
220 }
221 }
222
223 return wxEmptyString; // not found
224}
225
23239d94
VZ
226} // anonymous namespace
227
78d14f80 228
824e8eaa
VS
229wxXmlResource *wxXmlResource::ms_instance = NULL;
230
231/*static*/ wxXmlResource *wxXmlResource::Get()
232{
233 if ( !ms_instance )
234 ms_instance = new wxXmlResource;
235 return ms_instance;
236}
237
238/*static*/ wxXmlResource *wxXmlResource::Set(wxXmlResource *res)
239{
240 wxXmlResource *old = ms_instance;
241 ms_instance = res;
242 return old;
243}
244
d4a724d4 245wxXmlResource::wxXmlResource(int flags, const wxString& domain)
78d14f80 246{
daa85ee3 247 m_flags = flags;
78d14f80 248 m_version = -1;
eb2d0d23 249 m_data = new wxXmlResourceDataRecords;
d7a80cf5 250 SetDomain(domain);
78d14f80
VS
251}
252
d4a724d4 253wxXmlResource::wxXmlResource(const wxString& filemask, int flags, const wxString& domain)
78d14f80 254{
daa85ee3 255 m_flags = flags;
78d14f80 256 m_version = -1;
eb2d0d23 257 m_data = new wxXmlResourceDataRecords;
d7a80cf5 258 SetDomain(domain);
78d14f80
VS
259 Load(filemask);
260}
261
262wxXmlResource::~wxXmlResource()
263{
264 ClearHandlers();
eb2d0d23 265
f396e5a7
VS
266 for ( wxXmlResourceDataRecords::iterator i = m_data->begin();
267 i != m_data->end(); ++i )
268 {
269 delete *i;
270 }
eb2d0d23 271 delete m_data;
78d14f80
VS
272}
273
d7a80cf5 274void wxXmlResource::SetDomain(const wxString& domain)
d4a724d4 275{
d7a80cf5 276 m_domain = domain;
d4a724d4
RD
277}
278
78d14f80 279
60fd818a
VZ
280/* static */
281wxString wxXmlResource::ConvertFileNameToURL(const wxString& filename)
282{
283 wxString fnd(filename);
284
285 // NB: as Load() and Unload() accept both filenames and URLs (should
286 // probably be changed to filenames only, but embedded resources
287 // currently rely on its ability to handle URLs - FIXME) we need to
288 // determine whether found name is filename and not URL and this is the
289 // fastest/simplest way to do it
290 if (wxFileName::FileExists(fnd))
291 {
292 // Make the name absolute filename, because the app may
293 // change working directory later:
294 wxFileName fn(fnd);
295 if (fn.IsRelative())
296 {
297 fn.MakeAbsolute();
298 fnd = fn.GetFullPath();
299 }
300#if wxUSE_FILESYSTEM
301 fnd = wxFileSystem::FileNameToURL(fnd);
302#endif
303 }
304
305 return fnd;
306}
307
308#if wxUSE_FILESYSTEM
309
310/* static */
311bool wxXmlResource::IsArchive(const wxString& filename)
312{
313 const wxString fnd = filename.Lower();
314
315 return fnd.Matches(wxT("*.zip")) || fnd.Matches(wxT("*.xrs"));
316}
317
318#endif // wxUSE_FILESYSTEM
319
04ae32cd
VS
320bool wxXmlResource::LoadFile(const wxFileName& file)
321{
159852ae 322#if wxUSE_FILESYSTEM
04ae32cd 323 return Load(wxFileSystem::FileNameToURL(file));
159852ae
VS
324#else
325 return Load(file.GetFullPath());
326#endif
04ae32cd
VS
327}
328
2bb9a404
VS
329bool wxXmlResource::LoadAllFiles(const wxString& dirname)
330{
331 bool ok = true;
332 wxArrayString files;
333
334 wxDir::GetAllFiles(dirname, &files, "*.xrc");
335
336 for ( wxArrayString::const_iterator i = files.begin(); i != files.end(); ++i )
337 {
338 if ( !LoadFile(*i) )
339 ok = false;
340 }
341
342 return ok;
343}
344
acd32ffc 345bool wxXmlResource::Load(const wxString& filemask_)
78d14f80 346{
acd32ffc
VS
347 wxString filemask = ConvertFileNameToURL(filemask_);
348
9fc5a47c
VZ
349 bool allOK = true;
350
78d14f80
VS
351#if wxUSE_FILESYSTEM
352 wxFileSystem fsys;
353# define wxXmlFindFirst fsys.FindFirst(filemask, wxFILE)
354# define wxXmlFindNext fsys.FindNext()
355#else
356# define wxXmlFindFirst wxFindFirstFile(filemask, wxFILE)
357# define wxXmlFindNext wxFindNextFile()
358#endif
e5bb501b
VZ
359 wxString fnd = wxXmlFindFirst;
360 if ( fnd.empty() )
361 {
362 wxLogError(_("Cannot load resources from '%s'."), filemask);
363 return false;
364 }
365
ec157c8f 366 while (!fnd.empty())
78d14f80
VS
367 {
368#if wxUSE_FILESYSTEM
60fd818a 369 if ( IsArchive(fnd) )
78d14f80 370 {
e5bb501b 371 if ( !Load(fnd + wxT("#zip:*.xrc")) )
9fc5a47c 372 allOK = false;
78d14f80 373 }
60fd818a
VZ
374 else // a single resource URL
375#endif // wxUSE_FILESYSTEM
78d14f80 376 {
9fc5a47c
VZ
377 wxXmlDocument * const doc = DoLoadFile(fnd);
378 if ( !doc )
379 allOK = false;
380 else
381 Data().push_back(new wxXmlResourceDataRecord(fnd, doc));
78d14f80
VS
382 }
383
e5bb501b 384 fnd = wxXmlFindNext;
78d14f80
VS
385 }
386# undef wxXmlFindFirst
387# undef wxXmlFindNext
e5bb501b 388
9fc5a47c 389 return allOK;
78d14f80
VS
390}
391
60fd818a
VZ
392bool wxXmlResource::Unload(const wxString& filename)
393{
394 wxASSERT_MSG( !wxIsWild(filename),
9a83f860 395 wxT("wildcards not supported by wxXmlResource::Unload()") );
60fd818a
VZ
396
397 wxString fnd = ConvertFileNameToURL(filename);
398#if wxUSE_FILESYSTEM
399 const bool isArchive = IsArchive(fnd);
400 if ( isArchive )
9a83f860 401 fnd += wxT("#zip:");
60fd818a
VZ
402#endif // wxUSE_FILESYSTEM
403
404 bool unloaded = false;
eb2d0d23
VS
405 for ( wxXmlResourceDataRecords::iterator i = Data().begin();
406 i != Data().end(); ++i )
60fd818a
VZ
407 {
408#if wxUSE_FILESYSTEM
409 if ( isArchive )
410 {
f396e5a7 411 if ( (*i)->File.StartsWith(fnd) )
60fd818a
VZ
412 unloaded = true;
413 // don't break from the loop, we can have other matching files
414 }
415 else // a single resource URL
416#endif // wxUSE_FILESYSTEM
417 {
f396e5a7 418 if ( (*i)->File == fnd )
60fd818a 419 {
f8b1df0b 420 delete *i;
eb2d0d23 421 Data().erase(i);
60fd818a
VZ
422 unloaded = true;
423
424 // no sense in continuing, there is only one file with this URL
425 break;
426 }
427 }
428 }
429
430 return unloaded;
431}
432
78d14f80 433
854e189f 434IMPLEMENT_ABSTRACT_CLASS(wxXmlResourceHandler, wxObject)
78d14f80
VS
435
436void wxXmlResource::AddHandler(wxXmlResourceHandler *handler)
437{
eb2d0d23 438 m_handlers.push_back(handler);
78d14f80
VS
439 handler->SetParentResource(this);
440}
441
92e898b0
RD
442void wxXmlResource::InsertHandler(wxXmlResourceHandler *handler)
443{
eb2d0d23 444 m_handlers.insert(m_handlers.begin(), handler);
92e898b0
RD
445 handler->SetParentResource(this);
446}
447
78d14f80
VS
448
449
450void wxXmlResource::ClearHandlers()
451{
eb2d0d23
VS
452 for ( wxVector<wxXmlResourceHandler*>::iterator i = m_handlers.begin();
453 i != m_handlers.end(); ++i )
454 delete *i;
455 m_handlers.clear();
78d14f80
VS
456}
457
458
78d14f80
VS
459wxMenu *wxXmlResource::LoadMenu(const wxString& name)
460{
461 return (wxMenu*)CreateResFromNode(FindResource(name, wxT("wxMenu")), NULL, NULL);
462}
463
464
465
4a1b9596 466wxMenuBar *wxXmlResource::LoadMenuBar(wxWindow *parent, const wxString& name)
78d14f80 467{
4a1b9596 468 return (wxMenuBar*)CreateResFromNode(FindResource(name, wxT("wxMenuBar")), parent, NULL);
78d14f80
VS
469}
470
471
472
4a1b9596 473#if wxUSE_TOOLBAR
78d14f80
VS
474wxToolBar *wxXmlResource::LoadToolBar(wxWindow *parent, const wxString& name)
475{
476 return (wxToolBar*)CreateResFromNode(FindResource(name, wxT("wxToolBar")), parent, NULL);
477}
4a1b9596 478#endif
78d14f80
VS
479
480
481wxDialog *wxXmlResource::LoadDialog(wxWindow *parent, const wxString& name)
482{
4dd75a6a 483 return (wxDialog*)CreateResFromNode(FindResource(name, wxT("wxDialog")), parent, NULL);
78d14f80
VS
484}
485
486bool wxXmlResource::LoadDialog(wxDialog *dlg, wxWindow *parent, const wxString& name)
487{
488 return CreateResFromNode(FindResource(name, wxT("wxDialog")), parent, dlg) != NULL;
489}
490
491
492
493wxPanel *wxXmlResource::LoadPanel(wxWindow *parent, const wxString& name)
494{
495 return (wxPanel*)CreateResFromNode(FindResource(name, wxT("wxPanel")), parent, NULL);
496}
497
498bool wxXmlResource::LoadPanel(wxPanel *panel, wxWindow *parent, const wxString& name)
499{
500 return CreateResFromNode(FindResource(name, wxT("wxPanel")), parent, panel) != NULL;
501}
502
92e898b0
RD
503wxFrame *wxXmlResource::LoadFrame(wxWindow* parent, const wxString& name)
504{
505 return (wxFrame*)CreateResFromNode(FindResource(name, wxT("wxFrame")), parent, NULL);
506}
507
78d14f80
VS
508bool wxXmlResource::LoadFrame(wxFrame* frame, wxWindow *parent, const wxString& name)
509{
510 return CreateResFromNode(FindResource(name, wxT("wxFrame")), parent, frame) != NULL;
511}
512
513wxBitmap wxXmlResource::LoadBitmap(const wxString& name)
514{
515 wxBitmap *bmp = (wxBitmap*)CreateResFromNode(
516 FindResource(name, wxT("wxBitmap")), NULL, NULL);
517 wxBitmap rt;
518
519 if (bmp) { rt = *bmp; delete bmp; }
520 return rt;
521}
522
523wxIcon wxXmlResource::LoadIcon(const wxString& name)
524{
525 wxIcon *icon = (wxIcon*)CreateResFromNode(
526 FindResource(name, wxT("wxIcon")), NULL, NULL);
527 wxIcon rt;
528
529 if (icon) { rt = *icon; delete icon; }
530 return rt;
531}
532
92e898b0 533
af0ac990
VZ
534wxObject *
535wxXmlResource::DoLoadObject(wxWindow *parent,
536 const wxString& name,
537 const wxString& classname,
538 bool recursive)
92e898b0 539{
af0ac990
VZ
540 wxXmlNode * const node = FindResource(name, classname, recursive);
541
542 return node ? DoCreateResFromNode(*node, parent, NULL) : NULL;
92e898b0
RD
543}
544
af0ac990
VZ
545bool
546wxXmlResource::DoLoadObject(wxObject *instance,
547 wxWindow *parent,
548 const wxString& name,
549 const wxString& classname,
550 bool recursive)
92e898b0 551{
af0ac990
VZ
552 wxXmlNode * const node = FindResource(name, classname, recursive);
553
554 return node && DoCreateResFromNode(*node, parent, instance) != NULL;
92e898b0
RD
555}
556
557
78d14f80
VS
558bool wxXmlResource::AttachUnknownControl(const wxString& name,
559 wxWindow *control, wxWindow *parent)
560{
561 if (parent == NULL)
562 parent = control->GetParent();
563 wxWindow *container = parent->FindWindow(name + wxT("_container"));
564 if (!container)
565 {
819559b2 566 wxLogError("Cannot find container for unknown control '%s'.", name);
f80ea77b 567 return false;
78d14f80
VS
568 }
569 return control->Reparent(container);
570}
571
572
77b2f9b1 573static void ProcessPlatformProperty(wxXmlNode *node)
78d14f80
VS
574{
575 wxString s;
576 bool isok;
577
578 wxXmlNode *c = node->GetChildren();
579 while (c)
580 {
f80ea77b 581 isok = false;
288b6107 582 if (!c->GetAttribute(wxT("platform"), &s))
f80ea77b 583 isok = true;
78d14f80
VS
584 else
585 {
2b5f62a0 586 wxStringTokenizer tkn(s, wxT(" |"));
78d14f80
VS
587
588 while (tkn.HasMoreTokens())
589 {
590 s = tkn.GetNextToken();
84389518 591#ifdef __WINDOWS__
d003330c
VS
592 if (s == wxT("win")) isok = true;
593#endif
b380439d 594#if defined(__MAC__) || defined(__APPLE__)
d003330c 595 if (s == wxT("mac")) isok = true;
b380439d
RD
596#elif defined(__UNIX__)
597 if (s == wxT("unix")) isok = true;
78d14f80 598#endif
d003330c
VS
599#ifdef __OS2__
600 if (s == wxT("os2")) isok = true;
601#endif
602
603 if (isok)
604 break;
78d14f80
VS
605 }
606 }
607
608 if (isok)
d7b1d73c 609 {
78d14f80 610 ProcessPlatformProperty(c);
d7b1d73c
VS
611 c = c->GetNext();
612 }
78d14f80
VS
613 else
614 {
d7b1d73c 615 wxXmlNode *c2 = c->GetNext();
db59a97c 616 node->RemoveChild(c);
78d14f80 617 delete c;
d7b1d73c 618 c = c2;
78d14f80 619 }
78d14f80
VS
620 }
621}
622
0526c8cc
VZ
623static void PreprocessForIdRanges(wxXmlNode *rootnode)
624{
625 // First go through the top level, looking for the names of ID ranges
626 // as processing items is a lot easier if names are already known
627 wxXmlNode *c = rootnode->GetChildren();
628 while (c)
629 {
630 if (c->GetName() == wxT("ids-range"))
631 wxIdRangeManager::Get()->AddRange(c);
632 c = c->GetNext();
633 }
634
635 // Next, examine every 'name' for the '[' that denotes an ID in a range
636 c = rootnode->GetChildren();
637 while (c)
638 {
639 wxString name = c->GetAttribute(wxT("name"));
640 if (name.find('[') != wxString::npos)
641 wxIdRangeManager::Get()->NotifyRangeOfItem(rootnode, name);
78d14f80 642
0526c8cc
VZ
643 // Do any children by recursion, then proceed to the next sibling
644 PreprocessForIdRanges(c);
645 c = c->GetNext();
646 }
647}
78d14f80 648
d614f51b 649bool wxXmlResource::UpdateResources()
78d14f80 650{
d614f51b 651 bool rt = true;
480505bc 652
eb2d0d23
VS
653 for ( wxXmlResourceDataRecords::iterator i = Data().begin();
654 i != Data().end(); ++i )
78d14f80 655 {
f396e5a7
VS
656 wxXmlResourceDataRecord* const rec = *i;
657
9fc5a47c 658 // Check if we need to reload this one.
78d14f80 659
9fc5a47c
VZ
660 // We never do it if this flag is specified.
661 if ( m_flags & wxXRC_NO_RELOADING )
662 continue;
663
664 // Otherwise check its modification time if we can.
665#if wxUSE_DATETIME
666 const wxDateTime lastModTime = GetXRCFileModTime(rec->File);
667
668 if ( lastModTime.IsValid() && lastModTime <= rec->Time )
669#else // !wxUSE_DATETIME
670 // Never reload the file contents: we can't know whether it changed or
671 // not in this build configuration and it would be unexpected and
672 // counter-productive to get a performance hit (due to constant
673 // reloading of XRC files) in a minimal wx build which is presumably
674 // used because of resource constraints of the current platform.
675#endif // wxUSE_DATETIME/!wxUSE_DATETIME
78d14f80 676 {
9fc5a47c
VZ
677 // No need to reload, the file wasn't modified since we did it
678 // last.
679 continue;
78d14f80
VS
680 }
681
9fc5a47c
VZ
682 wxXmlDocument * const doc = DoLoadFile(rec->File);
683 if ( !doc )
78d14f80 684 {
9fc5a47c
VZ
685 // Notice that we keep the old XML document: it seems better to
686 // preserve it instead of throwing it away if we have nothing to
687 // replace it with.
688 rt = false;
689 continue;
690 }
78d14f80 691
9fc5a47c
VZ
692 // Replace the old resource contents with the new one.
693 delete rec->Doc;
694 rec->Doc = doc;
78d14f80 695
9fc5a47c 696 // And, now that we loaded it successfully, update the last load time.
34af0de4 697#if wxUSE_DATETIME
9fc5a47c 698 rec->Time = lastModTime.IsValid() ? lastModTime : wxDateTime::Now();
34af0de4 699#endif // wxUSE_DATETIME
78d14f80 700 }
d614f51b
VS
701
702 return rt;
78d14f80
VS
703}
704
9fc5a47c
VZ
705wxXmlDocument *wxXmlResource::DoLoadFile(const wxString& filename)
706{
707 wxLogTrace(wxT("xrc"), wxT("opening file '%s'"), filename);
708
709 wxInputStream *stream = NULL;
710
711#if wxUSE_FILESYSTEM
712 wxFileSystem fsys;
713 wxScopedPtr<wxFSFile> file(fsys.OpenFile(filename));
714 if (file)
715 {
716 // Notice that we don't have ownership of the stream in this case, it
717 // remains owned by wxFSFile.
718 stream = file->GetStream();
719 }
720#else // !wxUSE_FILESYSTEM
721 wxFileInputStream fstream(filename);
722 stream = &fstream;
723#endif // wxUSE_FILESYSTEM/!wxUSE_FILESYSTEM
724
725 if ( !stream || !stream->IsOk() )
726 {
727 wxLogError(_("Cannot open resources file '%s'."), filename);
728 return NULL;
729 }
730
731 wxString encoding(wxT("UTF-8"));
732#if !wxUSE_UNICODE && wxUSE_INTL
733 if ( (GetFlags() & wxXRC_USE_LOCALE) == 0 )
734 {
735 // In case we are not using wxLocale to translate strings, convert the
736 // strings GUI's charset. This must not be done when wxXRC_USE_LOCALE
737 // is on, because it could break wxGetTranslation lookup.
738 encoding = wxLocale::GetSystemEncodingName();
739 }
740#endif
741
742 wxScopedPtr<wxXmlDocument> doc(new wxXmlDocument);
743 if (!doc->Load(*stream, encoding))
744 {
745 wxLogError(_("Cannot load resources from file '%s'."), filename);
746 return NULL;
747 }
748
749 wxXmlNode * const root = doc->GetRoot();
750 if (root->GetName() != wxT("resource"))
751 {
752 ReportError
753 (
754 root,
755 "invalid XRC resource, doesn't have root node <resource>"
756 );
757 return NULL;
758 }
759
760 long version;
761 int v1, v2, v3, v4;
762 wxString verstr = root->GetAttribute(wxT("version"), wxT("0.0.0.0"));
763 if (wxSscanf(verstr, wxT("%i.%i.%i.%i"), &v1, &v2, &v3, &v4) == 4)
764 version = v1*256*256*256+v2*256*256+v3*256+v4;
765 else
766 version = 0;
767 if (m_version == -1)
768 m_version = version;
769 if (m_version != version)
770 {
771 wxLogWarning("Resource files must have same version number.");
772 }
773
774 ProcessPlatformProperty(root);
775 PreprocessForIdRanges(root);
776 wxIdRangeManager::Get()->FinaliseRanges(root);
777
778 return doc.release();
779}
780
b272b6dc
RD
781wxXmlNode *wxXmlResource::DoFindResource(wxXmlNode *parent,
782 const wxString& name,
783 const wxString& classname,
23239d94 784 bool recursive) const
47793ab8 785{
47793ab8
VS
786 wxXmlNode *node;
787
788 // first search for match at the top-level nodes (as this is
789 // where the resource is most commonly looked for):
790 for (node = parent->GetChildren(); node; node = node->GetNext())
791 {
23239d94 792 if ( IsObjectNode(node) && node->GetAttribute(wxS("name")) == name )
2b5f62a0 793 {
23239d94
VZ
794 // empty class name matches everything
795 if ( classname.empty() )
2b5f62a0 796 return node;
23239d94
VZ
797
798 wxString cls(node->GetAttribute(wxS("class")));
799
288b6107 800 // object_ref may not have 'class' attribute:
23239d94 801 if (cls.empty() && node->GetName() == wxS("object_ref"))
2b5f62a0 802 {
23239d94 803 wxString refName = node->GetAttribute(wxS("ref"));
2b5f62a0
VZ
804 if (refName.empty())
805 continue;
23239d94
VZ
806
807 const wxXmlNode * const refNode = GetResourceNode(refName);
808 if ( refNode )
809 cls = refNode->GetAttribute(wxS("class"));
2b5f62a0 810 }
23239d94
VZ
811
812 if ( cls == classname )
813 return node;
2b5f62a0 814 }
47793ab8
VS
815 }
816
23239d94 817 // then recurse in child nodes
47793ab8 818 if ( recursive )
23239d94 819 {
47793ab8
VS
820 for (node = parent->GetChildren(); node; node = node->GetNext())
821 {
23239d94 822 if ( IsObjectNode(node) )
47793ab8 823 {
f80ea77b 824 wxXmlNode* found = DoFindResource(node, name, classname, true);
47793ab8
VS
825 if ( found )
826 return found;
827 }
828 }
23239d94 829 }
47793ab8 830
23239d94 831 return NULL;
47793ab8 832}
78d14f80 833
b272b6dc 834wxXmlNode *wxXmlResource::FindResource(const wxString& name,
47793ab8
VS
835 const wxString& classname,
836 bool recursive)
78d14f80 837{
23239d94
VZ
838 wxString path;
839 wxXmlNode * const
840 node = GetResourceNodeAndLocation(name, classname, recursive, &path);
841
842 if ( !node )
843 {
819559b2
VS
844 ReportError
845 (
846 NULL,
847 wxString::Format
848 (
849 "XRC resource \"%s\" (class \"%s\") not found",
850 name, classname
851 )
852 );
23239d94
VZ
853 }
854#if wxUSE_FILESYSTEM
855 else // node was found
856 {
857 // ensure that relative paths work correctly when loading this node
858 // (which should happen as soon as we return as FindResource() result
859 // is always passed to CreateResFromNode())
860 m_curFileSystem.ChangePathTo(path);
861 }
862#endif // wxUSE_FILESYSTEM
863
864 return node;
865}
866
867wxXmlNode *
868wxXmlResource::GetResourceNodeAndLocation(const wxString& name,
869 const wxString& classname,
870 bool recursive,
871 wxString *path) const
872{
0526c8cc 873 // ensure everything is up-to-date: this is needed to support on-demand
23239d94
VZ
874 // reloading of XRC files
875 const_cast<wxXmlResource *>(this)->UpdateResources();
78d14f80 876
eb2d0d23
VS
877 for ( wxXmlResourceDataRecords::const_iterator f = Data().begin();
878 f != Data().end(); ++f )
78d14f80 879 {
23239d94
VZ
880 wxXmlResourceDataRecord *const rec = *f;
881 wxXmlDocument * const doc = rec->Doc;
882 if ( !doc || !doc->GetRoot() )
47793ab8
VS
883 continue;
884
23239d94
VZ
885 wxXmlNode * const
886 found = DoFindResource(doc->GetRoot(), name, classname, recursive);
47793ab8
VS
887 if ( found )
888 {
23239d94
VZ
889 if ( path )
890 *path = rec->File;
891
47793ab8
VS
892 return found;
893 }
78d14f80
VS
894 }
895
78d14f80
VS
896 return NULL;
897}
898
a1eeda0b
VS
899static void MergeNodesOver(wxXmlNode& dest, wxXmlNode& overwriteWith,
900 const wxString& overwriteFilename)
47793ab8 901{
288b6107 902 // Merge attributes:
a1eeda0b 903 for ( wxXmlAttribute *attr = overwriteWith.GetAttributes();
288b6107 904 attr; attr = attr->GetNext() )
47793ab8 905 {
288b6107
VS
906 wxXmlAttribute *dattr;
907 for (dattr = dest.GetAttributes(); dattr; dattr = dattr->GetNext())
47793ab8 908 {
b272b6dc 909
288b6107 910 if ( dattr->GetName() == attr->GetName() )
47793ab8 911 {
288b6107 912 dattr->SetValue(attr->GetValue());
47793ab8
VS
913 break;
914 }
915 }
78d14f80 916
288b6107
VS
917 if ( !dattr )
918 dest.AddAttribute(attr->GetName(), attr->GetValue());
47793ab8
VS
919 }
920
921 // Merge child nodes:
a1eeda0b 922 for (wxXmlNode* node = overwriteWith.GetChildren(); node; node = node->GetNext())
47793ab8 923 {
288b6107 924 wxString name = node->GetAttribute(wxT("name"), wxEmptyString);
47793ab8
VS
925 wxXmlNode *dnode;
926
927 for (dnode = dest.GetChildren(); dnode; dnode = dnode->GetNext() )
928 {
929 if ( dnode->GetName() == node->GetName() &&
288b6107 930 dnode->GetAttribute(wxT("name"), wxEmptyString) == name &&
47793ab8
VS
931 dnode->GetType() == node->GetType() )
932 {
a1eeda0b 933 MergeNodesOver(*dnode, *node, overwriteFilename);
47793ab8
VS
934 break;
935 }
936 }
937
938 if ( !dnode )
b26a650c 939 {
a1eeda0b
VS
940 wxXmlNode *copyOfNode = new wxXmlNode(*node);
941 // remember referenced object's file, see GetFileNameFromNode()
942 copyOfNode->AddAttribute(ATTR_INPUT_FILENAME, overwriteFilename);
943
b26a650c 944 static const wxChar *AT_END = wxT("end");
288b6107 945 wxString insert_pos = node->GetAttribute(wxT("insert_at"), AT_END);
b26a650c
VZ
946 if ( insert_pos == AT_END )
947 {
a1eeda0b 948 dest.AddChild(copyOfNode);
b26a650c
VZ
949 }
950 else if ( insert_pos == wxT("begin") )
951 {
a1eeda0b 952 dest.InsertChild(copyOfNode, dest.GetChildren());
b26a650c
VZ
953 }
954 }
47793ab8
VS
955 }
956
a1eeda0b
VS
957 if ( dest.GetType() == wxXML_TEXT_NODE && overwriteWith.GetContent().length() )
958 dest.SetContent(overwriteWith.GetContent());
47793ab8 959}
78d14f80 960
af0ac990
VZ
961wxObject *
962wxXmlResource::DoCreateResFromNode(wxXmlNode& node,
963 wxObject *parent,
964 wxObject *instance,
965 wxXmlResourceHandler *handlerToUse)
78d14f80 966{
47793ab8 967 // handling of referenced resource
af0ac990 968 if ( node.GetName() == wxT("object_ref") )
47793ab8 969 {
af0ac990 970 wxString refName = node.GetAttribute(wxT("ref"), wxEmptyString);
f80ea77b 971 wxXmlNode* refNode = FindResource(refName, wxEmptyString, true);
47793ab8
VS
972
973 if ( !refNode )
974 {
819559b2
VS
975 ReportError
976 (
af0ac990 977 &node,
819559b2
VS
978 wxString::Format
979 (
980 "referenced object node with ref=\"%s\" not found",
981 refName
982 )
983 );
47793ab8
VS
984 return NULL;
985 }
986
9445e542
VS
987 const bool hasOnlyRefAttr = node.GetAttributes() != NULL &&
988 node.GetAttributes()->GetNext() == NULL;
989
990 if ( hasOnlyRefAttr && !node.GetChildren() )
44108a07
VS
991 {
992 // In the typical, simple case, <object_ref> is used to link
993 // to another node and doesn't have any content of its own that
994 // would overwrite linked object's properties. In this case,
995 // we can simply create the resource from linked node.
996
af0ac990 997 return DoCreateResFromNode(*refNode, parent, instance);
44108a07
VS
998 }
999 else
1000 {
1001 // In the more complicated (but rare) case, <object_ref> has
1002 // subnodes that partially overwrite content of the referenced
1003 // object. In this case, we need to merge both XML trees and
1004 // load the resource from result of the merge.
1005
1006 wxXmlNode copy(*refNode);
af0ac990 1007 MergeNodesOver(copy, node, GetFileNameFromNode(&node, Data()));
a1eeda0b 1008
44108a07
VS
1009 // remember referenced object's file, see GetFileNameFromNode()
1010 copy.AddAttribute(ATTR_INPUT_FILENAME,
1011 GetFileNameFromNode(refNode, Data()));
47793ab8 1012
af0ac990 1013 return DoCreateResFromNode(copy, parent, instance);
44108a07 1014 }
47793ab8
VS
1015 }
1016
317a0d73 1017 if (handlerToUse)
b380439d 1018 {
af0ac990 1019 if (handlerToUse->CanHandle(&node))
8e8a4e85 1020 {
af0ac990 1021 return handlerToUse->CreateResource(&node, parent, instance);
8e8a4e85 1022 }
317a0d73 1023 }
af0ac990 1024 else if (node.GetName() == wxT("object"))
b380439d 1025 {
eb2d0d23
VS
1026 for ( wxVector<wxXmlResourceHandler*>::iterator h = m_handlers.begin();
1027 h != m_handlers.end(); ++h )
317a0d73 1028 {
eb2d0d23 1029 wxXmlResourceHandler *handler = *h;
af0ac990
VZ
1030 if (handler->CanHandle(&node))
1031 return handler->CreateResource(&node, parent, instance);
78d14f80 1032 }
78d14f80
VS
1033 }
1034
819559b2
VS
1035 ReportError
1036 (
af0ac990 1037 &node,
819559b2
VS
1038 wxString::Format
1039 (
1040 "no handler found for XML node \"%s\" (class \"%s\")",
af0ac990
VZ
1041 node.GetName(),
1042 node.GetAttribute("class", wxEmptyString)
819559b2
VS
1043 )
1044 );
78d14f80
VS
1045 return NULL;
1046}
1047
0526c8cc
VZ
1048wxIdRange::wxIdRange(const wxXmlNode* node,
1049 const wxString& rname,
1050 const wxString& startno,
1051 const wxString& rsize)
1052 : m_name(rname),
1053 m_start(0),
1054 m_size(0),
1055 m_item_end_found(0),
1056 m_finalised(0)
1057{
1058 long l;
1059 if ( startno.ToLong(&l) )
1060 {
1061 if ( l >= 0 )
1062 {
1063 m_start = l;
1064 }
1065 else
1066 {
1067 wxXmlResource::Get()->ReportError
1068 (
1069 node,
1070 "a negative id-range start parameter was given"
1071 );
1072 }
1073 }
1074 else
1075 {
1076 wxXmlResource::Get()->ReportError
1077 (
1078 node,
1079 "the id-range start parameter was malformed"
1080 );
1081 }
1082
1083 unsigned long ul;
1084 if ( rsize.ToULong(&ul) )
1085 {
1086 m_size = ul;
1087 }
1088 else
1089 {
1090 wxXmlResource::Get()->ReportError
1091 (
1092 node,
1093 "the id-range size parameter was malformed"
1094 );
1095 }
1096}
1097
1098void wxIdRange::NoteItem(const wxXmlNode* node, const wxString& item)
1099{
1100 // Nothing gets added here, but the existence of each item is noted
1101 // thus getting an accurate count. 'item' will be either an integer e.g.
1102 // [0] [123]: will eventually create an XRCID as start+integer or [start]
1103 // or [end] which are synonyms for [0] or [range_size-1] respectively.
1104 wxString content(item.Mid(1, item.length()-2));
1105
1106 // Check that basename+item wasn't foo[]
1107 if (content.empty())
1108 {
1109 wxXmlResource::Get()->ReportError(node, "an empty id-range item found");
1110 return;
1111 }
1112
1113 if (content=="start")
1114 {
1115 // "start" means [0], so store that in the set
1116 if (m_indices.count(0) == 0)
1117 {
1118 m_indices.insert(0);
1119 }
1120 else
1121 {
1122 wxXmlResource::Get()->ReportError
1123 (
1124 node,
1125 "duplicate id-range item found"
1126 );
1127 }
1128 }
1129 else if (content=="end")
1130 {
1131 // We can't yet be certain which XRCID this will be equivalent to, so
1132 // just note that there's an item with this name, in case we need to
1133 // inc the range size
1134 m_item_end_found = true;
1135 }
1136 else
1137 {
1138 // Anything else will be an integer, or rubbish
1139 unsigned long l;
1140 if ( content.ToULong(&l) )
1141 {
1142 if (m_indices.count(l) == 0)
1143 {
1144 m_indices.insert(l);
1145 // Check that this item wouldn't fall outside the current range
1146 // extent
1147 if (l >= m_size)
1148 {
1149 m_size = l + 1;
1150 }
1151 }
1152 else
1153 {
1154 wxXmlResource::Get()->ReportError
1155 (
1156 node,
1157 "duplicate id-range item found"
1158 );
1159 }
1160
1161 }
1162 else
1163 {
1164 wxXmlResource::Get()->ReportError
1165 (
1166 node,
1167 "an id-range item had a malformed index"
1168 );
1169 }
1170 }
1171}
1172
1173void wxIdRange::Finalise(const wxXmlNode* node)
1174{
1175 wxCHECK_RET( !IsFinalised(),
1176 "Trying to finalise an already-finalised range" );
1177
1178 // Now we know about all the items, we can get an accurate range size
1179 // Expand any requested range-size if there were more items than would fit
1180 m_size = wxMax(m_size, m_indices.size());
1181
1182 // If an item is explicitly called foo[end], ensure it won't clash with
1183 // another item
1184 if ( m_item_end_found && m_indices.count(m_size-1) )
1185 ++m_size;
1186 if (m_size == 0)
1187 {
1188 // This will happen if someone creates a range but no items in this xrc
1189 // file Report the error and abort, but don't finalise, in case items
1190 // appear later
1191 wxXmlResource::Get()->ReportError
1192 (
1193 node,
1194 "trying to create an empty id-range"
1195 );
1196 return;
1197 }
1198
1199 if (m_start==0)
1200 {
1201 // This is the usual case, where the user didn't specify a start ID
1202 // So get the range using NewControlId().
1203 //
1204 // NB: negative numbers, but NewControlId already returns the most
1205 // negative
1206 m_start = wxWindow::NewControlId(m_size);
1207 wxCHECK_RET( m_start != wxID_NONE,
1208 "insufficient IDs available to create range" );
1209 m_end = m_start + m_size - 1;
1210 }
1211 else
1212 {
1213 // The user already specified a start value, which must be positive
1214 m_end = m_start + m_size - 1;
1215 }
1216
1217 // Create the XRCIDs
1218 for (int i=m_start; i <= m_end; ++i)
1219 {
d265ec6b
VZ
1220 // Ensure that we overwrite any existing value as otherwise
1221 // wxXmlResource::Unload() followed by Load() wouldn't work correctly.
1222 XRCID_Assign(m_name + wxString::Format("[%i]", i-m_start), i);
0526c8cc 1223
e7cad4b7
VZ
1224 wxLogTrace("xrcrange",
1225 "integer = %i %s now returns %i",
1226 i,
1227 m_name + wxString::Format("[%i]", i-m_start),
1228 XRCID((m_name + wxString::Format("[%i]", i-m_start)).mb_str()));
0526c8cc
VZ
1229 }
1230 // and these special ones
d265ec6b
VZ
1231 XRCID_Assign(m_name + "[start]", m_start);
1232 XRCID_Assign(m_name + "[end]", m_end);
0526c8cc
VZ
1233 wxLogTrace("xrcrange","%s[start] = %i %s[end] = %i",
1234 m_name.mb_str(),XRCID(wxString(m_name+"[start]").mb_str()),
1235 m_name.mb_str(),XRCID(wxString(m_name+"[end]").mb_str()));
1236
1237 m_finalised = true;
1238}
1239
1240wxIdRangeManager *wxIdRangeManager::ms_instance = NULL;
1241
1242/*static*/ wxIdRangeManager *wxIdRangeManager::Get()
1243{
1244 if ( !ms_instance )
1245 ms_instance = new wxIdRangeManager;
1246 return ms_instance;
1247}
1248
1249/*static*/ wxIdRangeManager *wxIdRangeManager::Set(wxIdRangeManager *res)
1250{
1251 wxIdRangeManager *old = ms_instance;
1252 ms_instance = res;
1253 return old;
1254}
1255
1256wxIdRangeManager::~wxIdRangeManager()
1257{
1258 for ( wxVector<wxIdRange*>::iterator i = m_IdRanges.begin();
1259 i != m_IdRanges.end(); ++i )
1260 {
1261 delete *i;
1262 }
1263 m_IdRanges.clear();
1264
1265 delete ms_instance;
1266}
1267
1268void wxIdRangeManager::AddRange(const wxXmlNode* node)
1269{
1270 wxString name = node->GetAttribute("name");
1271 wxString start = node->GetAttribute("start", "0");
1272 wxString size = node->GetAttribute("size", "0");
1273 if (name.empty())
1274 {
1275 wxXmlResource::Get()->ReportError
1276 (
1277 node,
1278 "xrc file contains an id-range without a name"
1279 );
1280 return;
1281 }
1282
1283 int index = Find(name);
1284 if (index == wxNOT_FOUND)
1285 {
1286 wxLogTrace("xrcrange",
1287 "Adding ID range, name=%s start=%s size=%s",
1288 name, start, size);
1289
1290 m_IdRanges.push_back(new wxIdRange(node, name, start, size));
1291 }
1292 else
1293 {
1294 // There was already a range with this name. Let's hope this is
1295 // from an Unload()/(re)Load(), not an unintentional duplication
1296 wxLogTrace("xrcrange",
1297 "Replacing ID range, name=%s start=%s size=%s",
1298 name, start, size);
1299
1300 wxIdRange* oldrange = m_IdRanges.at(index);
1301 m_IdRanges.at(index) = new wxIdRange(node, name, start, size);
1302 delete oldrange;
1303 }
1304}
1305
1306wxIdRange *
1307wxIdRangeManager::FindRangeForItem(const wxXmlNode* node,
1308 const wxString& item,
1309 wxString& value) const
1310{
1311 wxString basename = item.BeforeFirst('[');
1312 wxCHECK_MSG( !basename.empty(), NULL,
1313 "an id-range item without a range name" );
1314
1315 int index = Find(basename);
1316 if (index == wxNOT_FOUND)
1317 {
1318 // Don't assert just because we've found an unexpected foo[123]
1319 // Someone might just want such a name, nothing to do with ranges
1320 return NULL;
1321 }
1322
1323 value = item.Mid(basename.Len());
1324 if (value.at(value.length()-1)==']')
1325 {
1326 return m_IdRanges.at(index);
1327 }
1328 wxXmlResource::Get()->ReportError(node, "a malformed id-range item");
1329 return NULL;
1330}
1331
1332void
1333wxIdRangeManager::NotifyRangeOfItem(const wxXmlNode* node,
1334 const wxString& item) const
1335{
1336 wxString value;
1337 wxIdRange* range = FindRangeForItem(node, item, value);
1338 if (range)
1339 range->NoteItem(node, value);
1340}
1341
1342int wxIdRangeManager::Find(const wxString& rangename) const
1343{
1344 for ( int i=0; i < (int)m_IdRanges.size(); ++i )
1345 {
1346 if (m_IdRanges.at(i)->GetName() == rangename)
1347 return i;
1348 }
1349
1350 return wxNOT_FOUND;
1351}
1352
1353void wxIdRangeManager::FinaliseRanges(const wxXmlNode* node) const
1354{
1355 for ( wxVector<wxIdRange*>::const_iterator i = m_IdRanges.begin();
1356 i != m_IdRanges.end(); ++i )
1357 {
1358 // Check if this range has already been finalised. Quite possible,
1359 // as FinaliseRanges() gets called for each .xrc file loaded
1360 if (!(*i)->IsFinalised())
1361 {
1362 wxLogTrace("xrcrange", "Finalising ID range %s", (*i)->GetName());
1363 (*i)->Finalise(node);
1364 }
1365 }
1366}
1367
78d14f80 1368
eb2d0d23
VS
1369class wxXmlSubclassFactories : public wxVector<wxXmlSubclassFactory*>
1370{
1371 // this is a class so that it can be forward-declared
1372};
2b5f62a0 1373
eb2d0d23 1374wxXmlSubclassFactories *wxXmlResource::ms_subclassFactories = NULL;
2b5f62a0
VZ
1375
1376/*static*/ void wxXmlResource::AddSubclassFactory(wxXmlSubclassFactory *factory)
1377{
1378 if (!ms_subclassFactories)
1379 {
eb2d0d23 1380 ms_subclassFactories = new wxXmlSubclassFactories;
2b5f62a0 1381 }
eb2d0d23 1382 ms_subclassFactories->push_back(factory);
2b5f62a0
VZ
1383}
1384
1385class wxXmlSubclassFactoryCXX : public wxXmlSubclassFactory
1386{
1387public:
1388 ~wxXmlSubclassFactoryCXX() {}
1389
1390 wxObject *Create(const wxString& className)
1391 {
1392 wxClassInfo* classInfo = wxClassInfo::FindClass(className);
1393
1394 if (classInfo)
1395 return classInfo->CreateObject();
1396 else
1397 return NULL;
1398 }
1399};
1400
1401
1402
78d14f80 1403
78d14f80
VS
1404wxXmlResourceHandler::wxXmlResourceHandler()
1405 : m_node(NULL), m_parent(NULL), m_instance(NULL),
9a8d8c5a 1406 m_parentAsWindow(NULL)
78d14f80
VS
1407{}
1408
1409
1410
1411wxObject *wxXmlResourceHandler::CreateResource(wxXmlNode *node, wxObject *parent, wxObject *instance)
1412{
1413 wxXmlNode *myNode = m_node;
1414 wxString myClass = m_class;
1415 wxObject *myParent = m_parent, *myInstance = m_instance;
9a8d8c5a 1416 wxWindow *myParentAW = m_parentAsWindow;
78d14f80 1417
daa85ee3 1418 m_instance = instance;
288b6107 1419 if (!m_instance && node->HasAttribute(wxT("subclass")) &&
daa85ee3
VS
1420 !(m_resource->GetFlags() & wxXRC_NO_SUBCLASSING))
1421 {
288b6107 1422 wxString subclass = node->GetAttribute(wxT("subclass"), wxEmptyString);
2b5f62a0 1423 if (!subclass.empty())
daa85ee3 1424 {
eb2d0d23
VS
1425 for (wxXmlSubclassFactories::iterator i = wxXmlResource::ms_subclassFactories->begin();
1426 i != wxXmlResource::ms_subclassFactories->end(); ++i)
2b5f62a0 1427 {
eb2d0d23 1428 m_instance = (*i)->Create(subclass);
2b5f62a0
VZ
1429 if (m_instance)
1430 break;
1431 }
daa85ee3 1432
2b5f62a0
VZ
1433 if (!m_instance)
1434 {
288b6107 1435 wxString name = node->GetAttribute(wxT("name"), wxEmptyString);
819559b2
VS
1436 ReportError
1437 (
1438 node,
1439 wxString::Format
1440 (
1441 "subclass \"%s\" not found for resource \"%s\", not subclassing",
1442 subclass, name
1443 )
1444 );
2b5f62a0
VZ
1445 }
1446 }
daa85ee3
VS
1447 }
1448
78d14f80 1449 m_node = node;
288b6107 1450 m_class = node->GetAttribute(wxT("class"), wxEmptyString);
78d14f80 1451 m_parent = parent;
78d14f80 1452 m_parentAsWindow = wxDynamicCast(m_parent, wxWindow);
78d14f80
VS
1453
1454 wxObject *returned = DoCreateResource();
1455
1456 m_node = myNode;
1457 m_class = myClass;
1458 m_parent = myParent; m_parentAsWindow = myParentAW;
9a8d8c5a 1459 m_instance = myInstance;
78d14f80
VS
1460
1461 return returned;
1462}
1463
1464
1465void wxXmlResourceHandler::AddStyle(const wxString& name, int value)
1466{
1467 m_styleNames.Add(name);
1468 m_styleValues.Add(value);
1469}
1470
1471
1472
1473void wxXmlResourceHandler::AddWindowStyles()
1474{
9dc579b3 1475 XRC_ADD_STYLE(wxCLIP_CHILDREN);
d54a3e73
VZ
1476
1477 // the border styles all have the old and new names, recognize both for now
1478 XRC_ADD_STYLE(wxSIMPLE_BORDER); XRC_ADD_STYLE(wxBORDER_SIMPLE);
1479 XRC_ADD_STYLE(wxSUNKEN_BORDER); XRC_ADD_STYLE(wxBORDER_SUNKEN);
b37e592b
JS
1480 XRC_ADD_STYLE(wxDOUBLE_BORDER); XRC_ADD_STYLE(wxBORDER_DOUBLE); // deprecated
1481 XRC_ADD_STYLE(wxBORDER_THEME);
d54a3e73
VZ
1482 XRC_ADD_STYLE(wxRAISED_BORDER); XRC_ADD_STYLE(wxBORDER_RAISED);
1483 XRC_ADD_STYLE(wxSTATIC_BORDER); XRC_ADD_STYLE(wxBORDER_STATIC);
1484 XRC_ADD_STYLE(wxNO_BORDER); XRC_ADD_STYLE(wxBORDER_NONE);
15b467a5 1485 XRC_ADD_STYLE(wxBORDER_DEFAULT);
d54a3e73 1486
daa85ee3
VS
1487 XRC_ADD_STYLE(wxTRANSPARENT_WINDOW);
1488 XRC_ADD_STYLE(wxWANTS_CHARS);
43840d8b 1489 XRC_ADD_STYLE(wxTAB_TRAVERSAL);
daa85ee3 1490 XRC_ADD_STYLE(wxNO_FULL_REPAINT_ON_RESIZE);
7539ba56 1491 XRC_ADD_STYLE(wxFULL_REPAINT_ON_RESIZE);
15b467a5
VZ
1492 XRC_ADD_STYLE(wxVSCROLL);
1493 XRC_ADD_STYLE(wxHSCROLL);
162a4f93 1494 XRC_ADD_STYLE(wxALWAYS_SHOW_SB);
15b467a5 1495
9f4ed861 1496 XRC_ADD_STYLE(wxWS_EX_BLOCK_EVENTS);
b0802e64 1497 XRC_ADD_STYLE(wxWS_EX_VALIDATE_RECURSIVELY);
15b467a5
VZ
1498 XRC_ADD_STYLE(wxWS_EX_TRANSIENT);
1499 XRC_ADD_STYLE(wxWS_EX_CONTEXTHELP);
1500 XRC_ADD_STYLE(wxWS_EX_PROCESS_IDLE);
1501 XRC_ADD_STYLE(wxWS_EX_PROCESS_UI_UPDATES);
78d14f80
VS
1502}
1503
1504
1505
1506bool wxXmlResourceHandler::HasParam(const wxString& param)
1507{
1508 return (GetParamNode(param) != NULL);
1509}
1510
1511
1512int wxXmlResourceHandler::GetStyle(const wxString& param, int defaults)
1513{
1514 wxString s = GetParamValue(param);
1515
1516 if (!s) return defaults;
1517
2b5f62a0 1518 wxStringTokenizer tkn(s, wxT("| \t\n"), wxTOKEN_STRTOK);
78d14f80
VS
1519 int style = 0;
1520 int index;
1521 wxString fl;
1522 while (tkn.HasMoreTokens())
1523 {
1524 fl = tkn.GetNextToken();
1525 index = m_styleNames.Index(fl);
1526 if (index != wxNOT_FOUND)
819559b2 1527 {
78d14f80 1528 style |= m_styleValues[index];
819559b2 1529 }
78d14f80 1530 else
819559b2
VS
1531 {
1532 ReportParamError
1533 (
1534 param,
1535 wxString::Format("unknown style flag \"%s\"", fl)
1536 );
1537 }
78d14f80
VS
1538 }
1539 return style;
1540}
1541
1542
1543
ee1046d1 1544wxString wxXmlResourceHandler::GetText(const wxString& param, bool translate)
78d14f80 1545{
7b56015f
VS
1546 wxXmlNode *parNode = GetParamNode(param);
1547 wxString str1(GetNodeContent(parNode));
78d14f80 1548 wxString str2;
424af7aa
VS
1549
1550 // "\\" wasn't translated to "\" prior to 2.5.3.0:
1551 const bool escapeBackslash = (m_resource->CompareVersion(2,5,3,0) >= 0);
78d14f80 1552
b272b6dc
RD
1553 // VS: First version of XRC resources used $ instead of & (which is
1554 // illegal in XML), but later I realized that '_' fits this purpose
718cf160 1555 // much better (because &File means "File with F underlined").
424af7aa
VS
1556 const wxChar amp_char = (m_resource->CompareVersion(2,3,0,1) < 0)
1557 ? '$' : '_';
78d14f80 1558
424af7aa 1559 for ( wxString::const_iterator dt = str1.begin(); dt != str1.end(); ++dt )
78d14f80
VS
1560 {
1561 // Remap amp_char to &, map double amp_char to amp_char (for things
1562 // like "&File..." -- this is illegal in XML, so we use "_File..."):
424af7aa 1563 if ( *dt == amp_char )
78d14f80 1564 {
2148394a 1565 if ( dt+1 == str1.end() || *(++dt) == amp_char )
78d14f80
VS
1566 str2 << amp_char;
1567 else
1568 str2 << wxT('&') << *dt;
1569 }
984c33c9 1570 // Remap \n to CR, \r to LF, \t to TAB, \\ to \:
424af7aa
VS
1571 else if ( *dt == wxT('\\') )
1572 {
1573 switch ( (*(++dt)).GetValue() )
78d14f80 1574 {
984c33c9
VS
1575 case wxT('n'):
1576 str2 << wxT('\n');
1577 break;
e7a3a5a5 1578
984c33c9
VS
1579 case wxT('t'):
1580 str2 << wxT('\t');
1581 break;
e7a3a5a5 1582
984c33c9
VS
1583 case wxT('r'):
1584 str2 << wxT('\r');
1585 break;
1586
1587 case wxT('\\') :
1588 // "\\" wasn't translated to "\" prior to 2.5.3.0:
424af7aa 1589 if ( escapeBackslash )
984c33c9
VS
1590 {
1591 str2 << wxT('\\');
1592 break;
1593 }
1594 // else fall-through to default: branch below
e7a3a5a5 1595
984c33c9
VS
1596 default:
1597 str2 << wxT('\\') << *dt;
1598 break;
78d14f80 1599 }
424af7aa
VS
1600 }
1601 else
1602 {
1603 str2 << *dt;
1604 }
78d14f80 1605 }
b272b6dc 1606
7b56015f
VS
1607 if (m_resource->GetFlags() & wxXRC_USE_LOCALE)
1608 {
1609 if (translate && parNode &&
288b6107 1610 parNode->GetAttribute(wxT("translate"), wxEmptyString) != wxT("0"))
7b56015f 1611 {
d4a724d4 1612 return wxGetTranslation(str2, m_resource->GetDomain());
7b56015f
VS
1613 }
1614 else
1615 {
1616#if wxUSE_UNICODE
1617 return str2;
1618#else
1619 // The string is internally stored as UTF-8, we have to convert
1620 // it into system's default encoding so that it can be displayed:
6251e0ea 1621 return wxString(str2.wc_str(wxConvUTF8), wxConvLocal);
7b56015f
VS
1622#endif
1623 }
1624 }
8516a98b
DS
1625
1626 // If wxXRC_USE_LOCALE is not set, then the string is already in
1627 // system's default encoding in ANSI build, so we don't have to
1628 // do anything special here.
1629 return str2;
78d14f80
VS
1630}
1631
1632
1633
1634long wxXmlResourceHandler::GetLong(const wxString& param, long defaultv)
1635{
9f5103f1 1636 long value = defaultv;
78d14f80
VS
1637 wxString str1 = GetParamValue(param);
1638
9f5103f1
VZ
1639 if (!str1.empty())
1640 {
1641 if (!str1.ToLong(&value))
1642 {
1643 ReportParamError
1644 (
1645 param,
1646 wxString::Format("invalid long specification \"%s\"", str1)
1647 );
1648 }
1649 }
78d14f80
VS
1650
1651 return value;
1652}
e7a3a5a5 1653
1df61962
VS
1654float wxXmlResourceHandler::GetFloat(const wxString& param, float defaultv)
1655{
1d9473d3 1656 wxString str = GetParamValue(param);
1df61962 1657
9edb8fa0
VZ
1658 // strings in XRC always use C locale so make sure to use the
1659 // locale-independent wxString::ToCDouble() and not ToDouble() which uses
1660 // the current locale with a potentially different decimal point character
9f5103f1
VZ
1661 double value = defaultv;
1662 if (!str.empty())
1663 {
1664 if (!str.ToCDouble(&value))
1665 {
1666 ReportParamError
1667 (
1668 param,
1669 wxString::Format("invalid float specification \"%s\"", str)
1670 );
1671 }
1672 }
1df61962 1673
17a1ebd1 1674 return wx_truncate_cast(float, value);
1df61962 1675}
78d14f80 1676
af1337b0 1677
78d14f80
VS
1678int wxXmlResourceHandler::GetID()
1679{
13de23f6 1680 return wxXmlResource::GetXRCID(GetName());
78d14f80
VS
1681}
1682
1683
af1337b0 1684
78d14f80
VS
1685wxString wxXmlResourceHandler::GetName()
1686{
288b6107 1687 return m_node->GetAttribute(wxT("name"), wxT("-1"));
78d14f80
VS
1688}
1689
1690
1691
8758875e
VZ
1692bool wxXmlResourceHandler::GetBoolAttr(const wxString& attr, bool defaultv)
1693{
1694 wxString v;
1695 return m_node->GetAttribute(attr, &v) ? v == '1' : defaultv;
1696}
1697
78d14f80
VS
1698bool wxXmlResourceHandler::GetBool(const wxString& param, bool defaultv)
1699{
8758875e 1700 const wxString v = GetParamValue(param);
8516a98b 1701
8758875e 1702 return v.empty() ? defaultv : (v == '1');
78d14f80
VS
1703}
1704
1705
1df61962
VS
1706static wxColour GetSystemColour(const wxString& name)
1707{
1708 if (!name.empty())
1709 {
1710 #define SYSCLR(clr) \
9a83f860 1711 if (name == wxT(#clr)) return wxSystemSettings::GetColour(clr);
1df61962
VS
1712 SYSCLR(wxSYS_COLOUR_SCROLLBAR)
1713 SYSCLR(wxSYS_COLOUR_BACKGROUND)
1714 SYSCLR(wxSYS_COLOUR_DESKTOP)
1715 SYSCLR(wxSYS_COLOUR_ACTIVECAPTION)
1716 SYSCLR(wxSYS_COLOUR_INACTIVECAPTION)
1717 SYSCLR(wxSYS_COLOUR_MENU)
1718 SYSCLR(wxSYS_COLOUR_WINDOW)
1719 SYSCLR(wxSYS_COLOUR_WINDOWFRAME)
1720 SYSCLR(wxSYS_COLOUR_MENUTEXT)
1721 SYSCLR(wxSYS_COLOUR_WINDOWTEXT)
1722 SYSCLR(wxSYS_COLOUR_CAPTIONTEXT)
1723 SYSCLR(wxSYS_COLOUR_ACTIVEBORDER)
1724 SYSCLR(wxSYS_COLOUR_INACTIVEBORDER)
1725 SYSCLR(wxSYS_COLOUR_APPWORKSPACE)
1726 SYSCLR(wxSYS_COLOUR_HIGHLIGHT)
1727 SYSCLR(wxSYS_COLOUR_HIGHLIGHTTEXT)
1728 SYSCLR(wxSYS_COLOUR_BTNFACE)
1729 SYSCLR(wxSYS_COLOUR_3DFACE)
1730 SYSCLR(wxSYS_COLOUR_BTNSHADOW)
1731 SYSCLR(wxSYS_COLOUR_3DSHADOW)
1732 SYSCLR(wxSYS_COLOUR_GRAYTEXT)
1733 SYSCLR(wxSYS_COLOUR_BTNTEXT)
1734 SYSCLR(wxSYS_COLOUR_INACTIVECAPTIONTEXT)
1735 SYSCLR(wxSYS_COLOUR_BTNHIGHLIGHT)
1736 SYSCLR(wxSYS_COLOUR_BTNHILIGHT)
1737 SYSCLR(wxSYS_COLOUR_3DHIGHLIGHT)
1738 SYSCLR(wxSYS_COLOUR_3DHILIGHT)
1739 SYSCLR(wxSYS_COLOUR_3DDKSHADOW)
1740 SYSCLR(wxSYS_COLOUR_3DLIGHT)
1741 SYSCLR(wxSYS_COLOUR_INFOTEXT)
1742 SYSCLR(wxSYS_COLOUR_INFOBK)
1743 SYSCLR(wxSYS_COLOUR_LISTBOX)
1744 SYSCLR(wxSYS_COLOUR_HOTLIGHT)
1745 SYSCLR(wxSYS_COLOUR_GRADIENTACTIVECAPTION)
1746 SYSCLR(wxSYS_COLOUR_GRADIENTINACTIVECAPTION)
1747 SYSCLR(wxSYS_COLOUR_MENUHILIGHT)
1748 SYSCLR(wxSYS_COLOUR_MENUBAR)
1749 #undef SYSCLR
1750 }
1751
1752 return wxNullColour;
1753}
78d14f80 1754
984f1d84 1755wxColour wxXmlResourceHandler::GetColour(const wxString& param, const wxColour& defaultv)
78d14f80
VS
1756{
1757 wxString v = GetParamValue(param);
984f1d84
VS
1758
1759 if ( v.empty() )
1760 return defaultv;
1761
68b4e4cf 1762 wxColour clr;
1df61962 1763
68b4e4cf
WS
1764 // wxString -> wxColour conversion
1765 if (!clr.Set(v))
78d14f80 1766 {
1df61962
VS
1767 // the colour doesn't use #RRGGBB format, check if it is symbolic
1768 // colour name:
68b4e4cf 1769 clr = GetSystemColour(v);
a1b806b9 1770 if (clr.IsOk())
1df61962 1771 return clr;
e7a3a5a5 1772
819559b2
VS
1773 ReportParamError
1774 (
1775 param,
1776 wxString::Format("incorrect colour specification \"%s\"", v)
1777 );
78d14f80
VS
1778 return wxNullColour;
1779 }
1780
68b4e4cf 1781 return clr;
78d14f80
VS
1782}
1783
1c60f644
VS
1784namespace
1785{
1786
1787// if 'param' has stock_id/stock_client, extracts them and returns true
1788bool GetStockArtAttrs(const wxXmlNode *paramNode,
1789 const wxString& defaultArtClient,
1790 wxString& art_id, wxString& art_client)
1791{
1792 if ( paramNode )
1793 {
1794 art_id = paramNode->GetAttribute("stock_id", "");
1795
1796 if ( !art_id.empty() )
1797 {
1798 art_id = wxART_MAKE_ART_ID_FROM_STR(art_id);
1799
1800 art_client = paramNode->GetAttribute("stock_client", "");
1801 if ( art_client.empty() )
1802 art_client = defaultArtClient;
1803 else
1804 art_client = wxART_MAKE_CLIENT_ID_FROM_STR(art_client);
78d14f80 1805
1c60f644
VS
1806 return true;
1807 }
1808 }
1809
1810 return false;
1811}
1812
1813} // anonymous namespace
78d14f80 1814
92e898b0 1815wxBitmap wxXmlResourceHandler::GetBitmap(const wxString& param,
db59a97c
VS
1816 const wxArtClient& defaultArtClient,
1817 wxSize size)
326462ae 1818{
9c1d2aa2
VZ
1819 // it used to be possible to pass an empty string here to indicate that the
1820 // bitmap name should be read from this node itself but this is not
1821 // supported any more because GetBitmap(m_node) can be used directly
1822 // instead
1823 wxASSERT_MSG( !param.empty(), "bitmap parameter name can't be empty" );
1824
1825 const wxXmlNode* const node = GetParamNode(param);
1826
1827 if ( !node )
1828 {
1829 // this is not an error as bitmap parameter could be optional
1830 return wxNullBitmap;
1831 }
1832
1833 return GetBitmap(node, defaultArtClient, size);
326462ae
VZ
1834}
1835
1836wxBitmap wxXmlResourceHandler::GetBitmap(const wxXmlNode* node,
1837 const wxArtClient& defaultArtClient,
1838 wxSize size)
78d14f80 1839{
9c1d2aa2
VZ
1840 wxCHECK_MSG( node, wxNullBitmap, "bitmap node can't be NULL" );
1841
db59a97c 1842 /* If the bitmap is specified as stock item, query wxArtProvider for it: */
1c60f644 1843 wxString art_id, art_client;
326462ae 1844 if ( GetStockArtAttrs(node, defaultArtClient,
1c60f644 1845 art_id, art_client) )
af1337b0 1846 {
1c60f644 1847 wxBitmap stockArt(wxArtProvider::GetBitmap(art_id, art_client, size));
a1b806b9 1848 if ( stockArt.IsOk() )
1c60f644 1849 return stockArt;
af1337b0
JS
1850 }
1851
92e898b0 1852 /* ...or load the bitmap from file: */
326462ae 1853 wxString name = GetParamValue(node);
e7a3a5a5 1854 if (name.empty()) return wxNullBitmap;
78d14f80 1855#if wxUSE_FILESYSTEM
4532786e 1856 wxFSFile *fsfile = GetCurFileSystem().OpenFile(name, wxFS_READ | wxFS_SEEKABLE);
78d14f80
VS
1857 if (fsfile == NULL)
1858 {
819559b2
VS
1859 ReportParamError
1860 (
326462ae 1861 node->GetName(),
819559b2
VS
1862 wxString::Format("cannot open bitmap resource \"%s\"", name)
1863 );
78d14f80
VS
1864 return wxNullBitmap;
1865 }
1866 wxImage img(*(fsfile->GetStream()));
1867 delete fsfile;
1868#else
45f3249b 1869 wxImage img(name);
78d14f80 1870#endif
af1337b0 1871
a1b806b9 1872 if (!img.IsOk())
78d14f80 1873 {
819559b2
VS
1874 ReportParamError
1875 (
326462ae 1876 node->GetName(),
819559b2
VS
1877 wxString::Format("cannot create bitmap from \"%s\"", name)
1878 );
78d14f80
VS
1879 return wxNullBitmap;
1880 }
1881 if (!(size == wxDefaultSize)) img.Rescale(size.x, size.y);
b272b6dc 1882 return wxBitmap(img);
78d14f80
VS
1883}
1884
78d14f80 1885
92e898b0 1886wxIcon wxXmlResourceHandler::GetIcon(const wxString& param,
db59a97c
VS
1887 const wxArtClient& defaultArtClient,
1888 wxSize size)
326462ae 1889{
9c1d2aa2
VZ
1890 // see comment in GetBitmap(wxString) overload
1891 wxASSERT_MSG( !param.empty(), "icon parameter name can't be empty" );
1892
1893 const wxXmlNode* const node = GetParamNode(param);
1894
1895 if ( !node )
1896 {
1897 // this is not an error as icon parameter could be optional
1898 return wxIcon();
1899 }
1900
1901 return GetIcon(node, defaultArtClient, size);
326462ae
VZ
1902}
1903
1904wxIcon wxXmlResourceHandler::GetIcon(const wxXmlNode* node,
1905 const wxArtClient& defaultArtClient,
1906 wxSize size)
78d14f80 1907{
78d14f80 1908 wxIcon icon;
326462ae 1909 icon.CopyFromBitmap(GetBitmap(node, defaultArtClient, size));
78d14f80
VS
1910 return icon;
1911}
1912
326462ae 1913
1c60f644
VS
1914wxIconBundle wxXmlResourceHandler::GetIconBundle(const wxString& param,
1915 const wxArtClient& defaultArtClient)
1916{
1917 wxString art_id, art_client;
1918 if ( GetStockArtAttrs(GetParamNode(param), defaultArtClient,
1919 art_id, art_client) )
1920 {
1921 wxIconBundle stockArt(wxArtProvider::GetIconBundle(art_id, art_client));
1922 if ( stockArt.IsOk() )
1923 return stockArt;
1924 }
1925
1926 const wxString name = GetParamValue(param);
1927 if ( name.empty() )
1928 return wxNullIconBundle;
1929
1930#if wxUSE_FILESYSTEM
1931 wxFSFile *fsfile = GetCurFileSystem().OpenFile(name, wxFS_READ | wxFS_SEEKABLE);
1932 if ( fsfile == NULL )
1933 {
1934 ReportParamError
1935 (
1936 param,
1937 wxString::Format("cannot open icon resource \"%s\"", name)
1938 );
1939 return wxNullIconBundle;
1940 }
1941
1942 wxIconBundle bundle(*(fsfile->GetStream()));
1943 delete fsfile;
1944#else
1945 wxIconBundle bundle(name);
1946#endif
1947
1948 if ( !bundle.IsOk() )
1949 {
1950 ReportParamError
1951 (
1952 param,
1953 wxString::Format("cannot create icon from \"%s\"", name)
1954 );
1955 return wxNullIconBundle;
1956 }
1957
1958 return bundle;
1959}
78d14f80
VS
1960
1961
326462ae
VZ
1962wxImageList *wxXmlResourceHandler::GetImageList(const wxString& param)
1963{
1964 wxXmlNode * const imagelist_node = GetParamNode(param);
1965 if ( !imagelist_node )
1966 return NULL;
1967
1968 wxXmlNode * const oldnode = m_node;
1969 m_node = imagelist_node;
1970
fe97acf0
VZ
1971 // Get the size if we have it, otherwise we will use the size of the first
1972 // list element.
326462ae 1973 wxSize size = GetSize();
326462ae 1974
fe97acf0
VZ
1975 // Start adding images, we'll create the image list when adding the first
1976 // one.
1977 wxImageList * imagelist = NULL;
326462ae
VZ
1978 wxString parambitmap = wxT("bitmap");
1979 if ( HasParam(parambitmap) )
1980 {
1981 wxXmlNode *n = m_node->GetChildren();
1982 while (n)
1983 {
1984 if (n->GetType() == wxXML_ELEMENT_NODE && n->GetName() == parambitmap)
1985 {
0915bc4d 1986 wxIcon icon = GetIcon(n, wxART_OTHER, size);
fe97acf0
VZ
1987 if ( !imagelist )
1988 {
1989 // We need the real image list size to create it.
1990 if ( size == wxDefaultSize )
1991 size = icon.GetSize();
1992
1993 // We use the mask by default.
1994 bool mask = !HasParam(wxS("mask")) || GetBool(wxS("mask"));
1995
1996 imagelist = new wxImageList(size.x, size.y, mask);
1997 }
1998
326462ae 1999 // add icon instead of bitmap to keep the bitmap mask
fe97acf0 2000 imagelist->Add(icon);
326462ae
VZ
2001 }
2002 n = n->GetNext();
2003 }
2004 }
2005
2006 m_node = oldnode;
2007 return imagelist;
2008}
2009
78d14f80
VS
2010wxXmlNode *wxXmlResourceHandler::GetParamNode(const wxString& param)
2011{
2b5f62a0
VZ
2012 wxCHECK_MSG(m_node, NULL, wxT("You can't access handler data before it was initialized!"));
2013
78d14f80
VS
2014 wxXmlNode *n = m_node->GetChildren();
2015
2016 while (n)
2017 {
2018 if (n->GetType() == wxXML_ELEMENT_NODE && n->GetName() == param)
cffff062
VZ
2019 {
2020 // TODO: check that there are no other properties/parameters with
2021 // the same name and log an error if there are (can't do this
2022 // right now as I'm not sure if it's not going to break code
2023 // using this function in unintentional way (i.e. for
2024 // accessing other things than properties), for example
2025 // wxBitmapComboBoxXmlHandler almost surely does
78d14f80 2026 return n;
cffff062 2027 }
78d14f80
VS
2028 n = n->GetNext();
2029 }
2030 return NULL;
2031}
2032
8ec22772 2033/* static */
2d672c46
MW
2034bool wxXmlResourceHandler::IsOfClass(wxXmlNode *node, const wxString& classname)
2035{
8ec22772 2036 return node->GetAttribute(wxT("class")) == classname;
2d672c46
MW
2037}
2038
2039
2040
326462ae 2041wxString wxXmlResourceHandler::GetNodeContent(const wxXmlNode *node)
78d14f80 2042{
326462ae 2043 const wxXmlNode *n = node;
78d14f80
VS
2044 if (n == NULL) return wxEmptyString;
2045 n = n->GetChildren();
2046
2047 while (n)
2048 {
2049 if (n->GetType() == wxXML_TEXT_NODE ||
2050 n->GetType() == wxXML_CDATA_SECTION_NODE)
2051 return n->GetContent();
2052 n = n->GetNext();
2053 }
2054 return wxEmptyString;
2055}
2056
2057
2058
2059wxString wxXmlResourceHandler::GetParamValue(const wxString& param)
2060{
e7a3a5a5 2061 if (param.empty())
78d14f80
VS
2062 return GetNodeContent(m_node);
2063 else
2064 return GetNodeContent(GetParamNode(param));
2065}
2066
326462ae
VZ
2067wxString wxXmlResourceHandler::GetParamValue(const wxXmlNode* node)
2068{
2069 return GetNodeContent(node);
2070}
78d14f80
VS
2071
2072
0c00c86f
VS
2073wxSize wxXmlResourceHandler::GetSize(const wxString& param,
2074 wxWindow *windowToUse)
78d14f80
VS
2075{
2076 wxString s = GetParamValue(param);
e7a3a5a5 2077 if (s.empty()) s = wxT("-1,-1");
78d14f80 2078 bool is_dlg;
d1f47235 2079 long sx, sy = 0;
78d14f80 2080
88a7a4e1 2081 is_dlg = s[s.length()-1] == wxT('d');
78d14f80
VS
2082 if (is_dlg) s.RemoveLast();
2083
2084 if (!s.BeforeFirst(wxT(',')).ToLong(&sx) ||
2085 !s.AfterLast(wxT(',')).ToLong(&sy))
2086 {
819559b2
VS
2087 ReportParamError
2088 (
2089 param,
2090 wxString::Format("cannot parse coordinates value \"%s\"", s)
2091 );
78d14f80
VS
2092 return wxDefaultSize;
2093 }
2094
2095 if (is_dlg)
2096 {
0c00c86f
VS
2097 if (windowToUse)
2098 {
2099 return wxDLG_UNIT(windowToUse, wxSize(sx, sy));
2100 }
2101 else if (m_parentAsWindow)
2102 {
78d14f80 2103 return wxDLG_UNIT(m_parentAsWindow, wxSize(sx, sy));
0c00c86f 2104 }
78d14f80
VS
2105 else
2106 {
819559b2
VS
2107 ReportParamError
2108 (
2109 param,
2110 "cannot convert dialog units: dialog unknown"
2111 );
78d14f80
VS
2112 return wxDefaultSize;
2113 }
2114 }
8516a98b
DS
2115
2116 return wxSize(sx, sy);
78d14f80
VS
2117}
2118
2119
2120
2121wxPoint wxXmlResourceHandler::GetPosition(const wxString& param)
2122{
2123 wxSize sz = GetSize(param);
2124 return wxPoint(sz.x, sz.y);
2125}
2126
2127
2128
0c00c86f
VS
2129wxCoord wxXmlResourceHandler::GetDimension(const wxString& param,
2130 wxCoord defaultv,
2131 wxWindow *windowToUse)
78d14f80
VS
2132{
2133 wxString s = GetParamValue(param);
e7a3a5a5 2134 if (s.empty()) return defaultv;
78d14f80
VS
2135 bool is_dlg;
2136 long sx;
2137
88a7a4e1 2138 is_dlg = s[s.length()-1] == wxT('d');
78d14f80
VS
2139 if (is_dlg) s.RemoveLast();
2140
2141 if (!s.ToLong(&sx))
2142 {
819559b2
VS
2143 ReportParamError
2144 (
2145 param,
2146 wxString::Format("cannot parse dimension value \"%s\"", s)
2147 );
78d14f80
VS
2148 return defaultv;
2149 }
2150
2151 if (is_dlg)
2152 {
0c00c86f
VS
2153 if (windowToUse)
2154 {
2155 return wxDLG_UNIT(windowToUse, wxSize(sx, 0)).x;
2156 }
2157 else if (m_parentAsWindow)
2158 {
78d14f80 2159 return wxDLG_UNIT(m_parentAsWindow, wxSize(sx, 0)).x;
0c00c86f 2160 }
78d14f80
VS
2161 else
2162 {
819559b2
VS
2163 ReportParamError
2164 (
2165 param,
2166 "cannot convert dialog units: dialog unknown"
2167 );
78d14f80
VS
2168 return defaultv;
2169 }
2170 }
8516a98b
DS
2171
2172 return sx;
78d14f80
VS
2173}
2174
50c20291
VZ
2175wxDirection
2176wxXmlResourceHandler::GetDirection(const wxString& param, wxDirection dirDefault)
2177{
2178 wxDirection dir;
2179
2180 const wxString dirstr = GetParamValue(param);
2181 if ( dirstr.empty() )
2182 dir = dirDefault;
2183 else if ( dirstr == "wxLEFT" )
2184 dir = wxLEFT;
2185 else if ( dirstr == "wxRIGHT" )
2186 dir = wxRIGHT;
2187 else if ( dirstr == "wxTOP" )
2188 dir = wxTOP;
2189 else if ( dirstr == "wxBOTTOM" )
2190 dir = wxBOTTOM;
2191 else
2192 {
2193 ReportError
2194 (
2195 GetParamNode(param),
2196 wxString::Format
2197 (
2198 "Invalid direction \"%s\": must be one of "
2199 "wxLEFT|wxRIGHT|wxTOP|wxBOTTOM.",
2200 dirstr
2201 )
2202 );
2203
2204 dir = dirDefault;
2205 }
2206
2207 return dir;
2208}
78d14f80 2209
1df61962
VS
2210// Get system font index using indexname
2211static wxFont GetSystemFont(const wxString& name)
2212{
2213 if (!name.empty())
2214 {
2215 #define SYSFNT(fnt) \
9a83f860 2216 if (name == wxT(#fnt)) return wxSystemSettings::GetFont(fnt);
1df61962
VS
2217 SYSFNT(wxSYS_OEM_FIXED_FONT)
2218 SYSFNT(wxSYS_ANSI_FIXED_FONT)
2219 SYSFNT(wxSYS_ANSI_VAR_FONT)
2220 SYSFNT(wxSYS_SYSTEM_FONT)
2221 SYSFNT(wxSYS_DEVICE_DEFAULT_FONT)
1df61962
VS
2222 SYSFNT(wxSYS_SYSTEM_FIXED_FONT)
2223 SYSFNT(wxSYS_DEFAULT_GUI_FONT)
2224 #undef SYSFNT
2225 }
2226
2227 return wxNullFont;
2228}
78d14f80 2229
45df4bb6 2230wxFont wxXmlResourceHandler::GetFont(const wxString& param, wxWindow* parent)
78d14f80
VS
2231{
2232 wxXmlNode *font_node = GetParamNode(param);
2233 if (font_node == NULL)
2234 {
819559b2
VS
2235 ReportError(
2236 wxString::Format("cannot find font node \"%s\"", param));
78d14f80
VS
2237 return wxNullFont;
2238 }
2239
2240 wxXmlNode *oldnode = m_node;
2241 m_node = font_node;
2242
1df61962 2243 // font attributes:
78d14f80 2244
1df61962 2245 // size
94245f6d 2246 int isize = -1;
1df61962 2247 bool hasSize = HasParam(wxT("size"));
e7a3a5a5 2248 if (hasSize)
94245f6d 2249 isize = GetLong(wxT("size"), -1);
78d14f80 2250
1df61962
VS
2251 // style
2252 int istyle = wxNORMAL;
2253 bool hasStyle = HasParam(wxT("style"));
2254 if (hasStyle)
2255 {
2256 wxString style = GetParamValue(wxT("style"));
e7a3a5a5 2257 if (style == wxT("italic"))
1df61962 2258 istyle = wxITALIC;
e7a3a5a5 2259 else if (style == wxT("slant"))
1df61962 2260 istyle = wxSLANT;
9f5103f1
VZ
2261 else if (style != wxT("normal"))
2262 {
2263 ReportParamError
2264 (
2265 param,
2266 wxString::Format("unknown font style \"%s\"", style)
2267 );
2268 }
1df61962 2269 }
78d14f80 2270
1df61962
VS
2271 // weight
2272 int iweight = wxNORMAL;
2273 bool hasWeight = HasParam(wxT("weight"));
2274 if (hasWeight)
2275 {
2276 wxString weight = GetParamValue(wxT("weight"));
e7a3a5a5 2277 if (weight == wxT("bold"))
1df61962 2278 iweight = wxBOLD;
e7a3a5a5 2279 else if (weight == wxT("light"))
1df61962 2280 iweight = wxLIGHT;
9f5103f1
VZ
2281 else if (weight != wxT("normal"))
2282 {
2283 ReportParamError
2284 (
2285 param,
2286 wxString::Format("unknown font weight \"%s\"", weight)
2287 );
2288 }
1df61962 2289 }
e7a3a5a5 2290
1df61962
VS
2291 // underline
2292 bool hasUnderlined = HasParam(wxT("underlined"));
2293 bool underlined = hasUnderlined ? GetBool(wxT("underlined"), false) : false;
78d14f80 2294
1df61962
VS
2295 // family and facename
2296 int ifamily = wxDEFAULT;
2297 bool hasFamily = HasParam(wxT("family"));
2298 if (hasFamily)
78d14f80 2299 {
1df61962
VS
2300 wxString family = GetParamValue(wxT("family"));
2301 if (family == wxT("decorative")) ifamily = wxDECORATIVE;
2302 else if (family == wxT("roman")) ifamily = wxROMAN;
2303 else if (family == wxT("script")) ifamily = wxSCRIPT;
2304 else if (family == wxT("swiss")) ifamily = wxSWISS;
2305 else if (family == wxT("modern")) ifamily = wxMODERN;
2306 else if (family == wxT("teletype")) ifamily = wxTELETYPE;
9f5103f1
VZ
2307 else
2308 {
2309 ReportParamError
2310 (
2311 param,
2312 wxString::Format("unknown font family \"%s\"", family)
2313 );
2314 }
1df61962 2315 }
e7a3a5a5
WS
2316
2317
1df61962
VS
2318 wxString facename;
2319 bool hasFacename = HasParam(wxT("face"));
2320 if (hasFacename)
2321 {
2322 wxString faces = GetParamValue(wxT("face"));
1df61962 2323 wxStringTokenizer tk(faces, wxT(","));
63feebce
VS
2324#if wxUSE_FONTENUM
2325 wxArrayString facenames(wxFontEnumerator::GetFacenames());
1df61962 2326 while (tk.HasMoreTokens())
78d14f80 2327 {
6540132f 2328 int index = facenames.Index(tk.GetNextToken(), false);
1df61962
VS
2329 if (index != wxNOT_FOUND)
2330 {
6540132f 2331 facename = facenames[index];
1df61962
VS
2332 break;
2333 }
78d14f80 2334 }
63feebce
VS
2335#else // !wxUSE_FONTENUM
2336 // just use the first face name if we can't check its availability:
2337 if (tk.HasMoreTokens())
2338 facename = tk.GetNextToken();
2339#endif // wxUSE_FONTENUM/!wxUSE_FONTENUM
78d14f80
VS
2340 }
2341
1df61962
VS
2342 // encoding
2343 wxFontEncoding enc = wxFONTENCODING_DEFAULT;
2344 bool hasEncoding = HasParam(wxT("encoding"));
dc2575ba 2345#if wxUSE_FONTMAP
1df61962
VS
2346 if (hasEncoding)
2347 {
2348 wxString encoding = GetParamValue(wxT("encoding"));
2349 wxFontMapper mapper;
e7a3a5a5 2350 if (!encoding.empty())
1df61962
VS
2351 enc = mapper.CharsetToEncoding(encoding);
2352 if (enc == wxFONTENCODING_SYSTEM)
2353 enc = wxFONTENCODING_DEFAULT;
2354 }
dc2575ba 2355#endif // wxUSE_FONTMAP
78d14f80 2356
45df4bb6
VZ
2357 wxFont font;
2358
1df61962 2359 // is this font based on a system font?
45df4bb6
VZ
2360 if (HasParam(wxT("sysfont")))
2361 {
2362 font = GetSystemFont(GetParamValue(wxT("sysfont")));
9f5103f1
VZ
2363 if (HasParam(wxT("inherit")))
2364 {
2365 ReportParamError
2366 (
2367 param,
2368 "double specification of \"sysfont\" and \"inherit\""
2369 );
2370 }
45df4bb6
VZ
2371 }
2372 // or should the font of the widget be used?
2373 else if (GetBool(wxT("inherit"), false))
2374 {
2375 if (parent)
2376 font = parent->GetFont();
2377 else
9f5103f1
VZ
2378 {
2379 ReportParamError
2380 (
2381 param,
2382 "no parent window specified to derive the font from"
2383 );
2384 }
45df4bb6 2385 }
e7a3a5a5 2386
a1b806b9 2387 if (font.IsOk())
1df61962 2388 {
94245f6d 2389 if (hasSize && isize != -1)
9f5103f1 2390 {
94245f6d 2391 font.SetPointSize(isize);
9f5103f1
VZ
2392 if (HasParam(wxT("relativesize")))
2393 {
2394 ReportParamError
2395 (
2396 param,
2397 "double specification of \"size\" and \"relativesize\""
2398 );
2399 }
2400 }
1df61962 2401 else if (HasParam(wxT("relativesize")))
94245f6d 2402 font.SetPointSize(int(font.GetPointSize() *
1df61962 2403 GetFloat(wxT("relativesize"))));
e7a3a5a5 2404
1df61962 2405 if (hasStyle)
94245f6d 2406 font.SetStyle(istyle);
1df61962 2407 if (hasWeight)
94245f6d 2408 font.SetWeight(iweight);
1df61962 2409 if (hasUnderlined)
94245f6d 2410 font.SetUnderlined(underlined);
1df61962 2411 if (hasFamily)
94245f6d 2412 font.SetFamily(ifamily);
1df61962 2413 if (hasFacename)
94245f6d 2414 font.SetFaceName(facename);
1df61962 2415 if (hasEncoding)
94245f6d
VZ
2416 font.SetDefaultEncoding(enc);
2417 }
2418 else // not based on system font
2419 {
2420 font = wxFont(isize == -1 ? wxNORMAL_FONT->GetPointSize() : isize,
2421 ifamily, istyle, iweight,
2422 underlined, facename, enc);
1df61962 2423 }
8516a98b
DS
2424
2425 m_node = oldnode;
94245f6d 2426 return font;
78d14f80
VS
2427}
2428
2429
2430void wxXmlResourceHandler::SetupWindow(wxWindow *wnd)
2431{
2432 //FIXME : add cursor
2433
2434 if (HasParam(wxT("exstyle")))
0099f343
JS
2435 // Have to OR it with existing style, since
2436 // some implementations (e.g. wxGTK) use the extra style
2437 // during creation
2438 wnd->SetExtraStyle(wnd->GetExtraStyle() | GetStyle(wxT("exstyle")));
78d14f80
VS
2439 if (HasParam(wxT("bg")))
2440 wnd->SetBackgroundColour(GetColour(wxT("bg")));
a7435c3e
VZ
2441 if (HasParam(wxT("ownbg")))
2442 wnd->SetOwnBackgroundColour(GetColour(wxT("ownbg")));
78d14f80
VS
2443 if (HasParam(wxT("fg")))
2444 wnd->SetForegroundColour(GetColour(wxT("fg")));
a7435c3e
VZ
2445 if (HasParam(wxT("ownfg")))
2446 wnd->SetOwnForegroundColour(GetColour(wxT("ownfg")));
78d14f80 2447 if (GetBool(wxT("enabled"), 1) == 0)
f80ea77b 2448 wnd->Enable(false);
78d14f80
VS
2449 if (GetBool(wxT("focused"), 0) == 1)
2450 wnd->SetFocus();
2451 if (GetBool(wxT("hidden"), 0) == 1)
f80ea77b 2452 wnd->Show(false);
78d14f80
VS
2453#if wxUSE_TOOLTIPS
2454 if (HasParam(wxT("tooltip")))
2455 wnd->SetToolTip(GetText(wxT("tooltip")));
2456#endif
2457 if (HasParam(wxT("font")))
45df4bb6 2458 wnd->SetFont(GetFont(wxT("font"), wnd));
a7435c3e 2459 if (HasParam(wxT("ownfont")))
45df4bb6 2460 wnd->SetOwnFont(GetFont(wxT("ownfont"), wnd));
b23030d6
JS
2461 if (HasParam(wxT("help")))
2462 wnd->SetHelpText(GetText(wxT("help")));
78d14f80
VS
2463}
2464
2465
2466void wxXmlResourceHandler::CreateChildren(wxObject *parent, bool this_hnd_only)
2467{
23239d94 2468 for ( wxXmlNode *n = m_node->GetChildren(); n; n = n->GetNext() )
78d14f80 2469 {
23239d94 2470 if ( IsObjectNode(n) )
78d14f80 2471 {
af0ac990
VZ
2472 m_resource->DoCreateResFromNode(*n, parent, NULL,
2473 this_hnd_only ? this : NULL);
78d14f80 2474 }
78d14f80
VS
2475 }
2476}
2477
2478
2479void wxXmlResourceHandler::CreateChildrenPrivately(wxObject *parent, wxXmlNode *rootnode)
2480{
2481 wxXmlNode *root;
2482 if (rootnode == NULL) root = m_node; else root = rootnode;
2483 wxXmlNode *n = root->GetChildren();
2484
2485 while (n)
2486 {
2487 if (n->GetType() == wxXML_ELEMENT_NODE && CanHandle(n))
2488 {
2489 CreateResource(n, parent, NULL);
2490 }
2491 n = n->GetNext();
2492 }
2493}
2494
2495
819559b2
VS
2496//-----------------------------------------------------------------------------
2497// errors reporting
2498//-----------------------------------------------------------------------------
2499
2500void wxXmlResourceHandler::ReportError(const wxString& message)
2501{
2502 m_resource->ReportError(m_node, message);
2503}
2504
2505void wxXmlResourceHandler::ReportError(wxXmlNode *context,
2506 const wxString& message)
2507{
2508 m_resource->ReportError(context ? context : m_node, message);
2509}
2510
2511void wxXmlResourceHandler::ReportParamError(const wxString& param,
2512 const wxString& message)
2513{
2514 m_resource->ReportError(GetParamNode(param), message);
2515}
2516
1f6ea935 2517void wxXmlResource::ReportError(const wxXmlNode *context, const wxString& message)
819559b2
VS
2518{
2519 if ( !context )
2520 {
2521 DoReportError("", NULL, message);
2522 return;
2523 }
78d14f80 2524
819559b2
VS
2525 // We need to find out the file that 'context' is part of. Performance of
2526 // this code is not critical, so we simply find the root XML node and
2527 // compare it with all loaded XRC files.
2528 const wxString filename = GetFileNameFromNode(context, Data());
78d14f80 2529
819559b2
VS
2530 DoReportError(filename, context, message);
2531}
78d14f80 2532
1f6ea935 2533void wxXmlResource::DoReportError(const wxString& xrcFile, const wxXmlNode *position,
819559b2
VS
2534 const wxString& message)
2535{
2536 const int line = position ? position->GetLineNumber() : -1;
2537
2538 wxString loc;
2539 if ( !xrcFile.empty() )
2540 loc = xrcFile + ':';
2541 if ( line != -1 )
2542 loc += wxString::Format("%d:", line);
2543 if ( !loc.empty() )
2544 loc += ' ';
2545
2546 wxLogError("XRC error: %s%s", loc, message);
2547}
78d14f80
VS
2548
2549
819559b2
VS
2550//-----------------------------------------------------------------------------
2551// XRCID implementation
2552//-----------------------------------------------------------------------------
78d14f80 2553
5ed345b7 2554#define XRCID_TABLE_SIZE 1024
78d14f80
VS
2555
2556
5ed345b7 2557struct XRCID_record
78d14f80 2558{
cf2810aa
VZ
2559 /* Hold the id so that once an id is allocated for a name, it
2560 does not get created again by NewControlId at least
2561 until we are done with it */
2562 wxWindowIDRef id;
c560da98 2563 char *key;
5ed345b7 2564 XRCID_record *next;
78d14f80
VS
2565};
2566
5ed345b7 2567static XRCID_record *XRCID_Records[XRCID_TABLE_SIZE] = {NULL};
78d14f80 2568
d807030e
VZ
2569// Extremely simplistic hash function which probably ought to be replaced with
2570// wxStringHash::stringHash().
2571static inline unsigned XRCIdHash(const char *str_id)
78d14f80 2572{
d807030e 2573 unsigned index = 0;
78d14f80 2574
e03951b7 2575 for (const char *c = str_id; *c != '\0'; c++) index += (unsigned int)*c;
5ed345b7 2576 index %= XRCID_TABLE_SIZE;
78d14f80 2577
d807030e
VZ
2578 return index;
2579}
2580
3cf2fe54 2581static void XRCID_Assign(const wxString& str_id, int value)
d265ec6b 2582{
d7a46c4e 2583 const wxCharBuffer buf_id(str_id.mb_str());
3cf2fe54 2584 const unsigned index = XRCIdHash(buf_id);
d265ec6b
VZ
2585
2586
2587 XRCID_record *oldrec = NULL;
2588 for (XRCID_record *rec = XRCID_Records[index]; rec; rec = rec->next)
2589 {
3cf2fe54 2590 if (wxStrcmp(rec->key, buf_id) == 0)
d265ec6b
VZ
2591 {
2592 rec->id = value;
2593 return;
2594 }
2595 oldrec = rec;
2596 }
2597
2598 XRCID_record **rec_var = (oldrec == NULL) ?
2599 &XRCID_Records[index] : &oldrec->next;
2600 *rec_var = new XRCID_record;
2601 (*rec_var)->key = wxStrdup(str_id);
2602 (*rec_var)->id = value;
2603 (*rec_var)->next = NULL;
2604}
2605
d807030e
VZ
2606static int XRCID_Lookup(const char *str_id, int value_if_not_found = wxID_NONE)
2607{
2608 const unsigned index = XRCIdHash(str_id);
2609
2610
5ed345b7 2611 XRCID_record *oldrec = NULL;
5ed345b7 2612 for (XRCID_record *rec = XRCID_Records[index]; rec; rec = rec->next)
78d14f80 2613 {
00393283 2614 if (wxStrcmp(rec->key, str_id) == 0)
78d14f80
VS
2615 {
2616 return rec->id;
2617 }
78d14f80
VS
2618 oldrec = rec;
2619 }
2620
5ed345b7
VS
2621 XRCID_record **rec_var = (oldrec == NULL) ?
2622 &XRCID_Records[index] : &oldrec->next;
2623 *rec_var = new XRCID_record;
00393283 2624 (*rec_var)->key = wxStrdup(str_id);
78d14f80
VS
2625 (*rec_var)->next = NULL;
2626
c560da98 2627 char *end;
9b2a7469 2628 if (value_if_not_found != wxID_NONE)
13de23f6 2629 (*rec_var)->id = value_if_not_found;
85452d74
VS
2630 else
2631 {
13de23f6
VS
2632 int asint = wxStrtol(str_id, &end, 10);
2633 if (*str_id && *end == 0)
2634 {
2635 // if str_id was integer, keep it verbosely:
2636 (*rec_var)->id = asint;
2637 }
2638 else
2639 {
f35fdf7e 2640 (*rec_var)->id = wxWindowBase::NewControlId();
13de23f6 2641 }
85452d74
VS
2642 }
2643
78d14f80
VS
2644 return (*rec_var)->id;
2645}
2646
a58804ea 2647namespace
78d14f80 2648{
f35fdf7e 2649
a58804ea
VZ
2650// flag indicating whether standard XRC ids were already initialized
2651static bool gs_stdIDsAdded = false;
78d14f80 2652
a58804ea 2653void AddStdXRCID_Records()
13de23f6 2654{
c560da98 2655#define stdID(id) XRCID_Lookup(#id, id)
13de23f6 2656 stdID(-1);
c369d4f1
VS
2657
2658 stdID(wxID_ANY);
2659 stdID(wxID_SEPARATOR);
e7a3a5a5 2660
c369d4f1
VS
2661 stdID(wxID_OPEN);
2662 stdID(wxID_CLOSE);
2663 stdID(wxID_NEW);
2664 stdID(wxID_SAVE);
2665 stdID(wxID_SAVEAS);
2666 stdID(wxID_REVERT);
2667 stdID(wxID_EXIT);
2668 stdID(wxID_UNDO);
2669 stdID(wxID_REDO);
2670 stdID(wxID_HELP);
2671 stdID(wxID_PRINT);
2672 stdID(wxID_PRINT_SETUP);
e63f19ba 2673 stdID(wxID_PAGE_SETUP);
c369d4f1
VS
2674 stdID(wxID_PREVIEW);
2675 stdID(wxID_ABOUT);
2676 stdID(wxID_HELP_CONTENTS);
9a9c20be
VZ
2677 stdID(wxID_HELP_INDEX),
2678 stdID(wxID_HELP_SEARCH),
c369d4f1
VS
2679 stdID(wxID_HELP_COMMANDS);
2680 stdID(wxID_HELP_PROCEDURES);
2681 stdID(wxID_HELP_CONTEXT);
13de23f6 2682 stdID(wxID_CLOSE_ALL);
c369d4f1 2683 stdID(wxID_PREFERENCES);
9a9c20be 2684
d73195fd 2685 stdID(wxID_EDIT);
c369d4f1
VS
2686 stdID(wxID_CUT);
2687 stdID(wxID_COPY);
2688 stdID(wxID_PASTE);
2689 stdID(wxID_CLEAR);
2690 stdID(wxID_FIND);
2691 stdID(wxID_DUPLICATE);
2692 stdID(wxID_SELECTALL);
2693 stdID(wxID_DELETE);
2694 stdID(wxID_REPLACE);
2695 stdID(wxID_REPLACE_ALL);
2696 stdID(wxID_PROPERTIES);
9a9c20be 2697
c369d4f1
VS
2698 stdID(wxID_VIEW_DETAILS);
2699 stdID(wxID_VIEW_LARGEICONS);
2700 stdID(wxID_VIEW_SMALLICONS);
2701 stdID(wxID_VIEW_LIST);
2702 stdID(wxID_VIEW_SORTDATE);
2703 stdID(wxID_VIEW_SORTNAME);
2704 stdID(wxID_VIEW_SORTSIZE);
2705 stdID(wxID_VIEW_SORTTYPE);
9a9c20be
VZ
2706
2707
c369d4f1
VS
2708 stdID(wxID_FILE1);
2709 stdID(wxID_FILE2);
2710 stdID(wxID_FILE3);
2711 stdID(wxID_FILE4);
2712 stdID(wxID_FILE5);
2713 stdID(wxID_FILE6);
2714 stdID(wxID_FILE7);
2715 stdID(wxID_FILE8);
2716 stdID(wxID_FILE9);
9a9c20be
VZ
2717
2718
c369d4f1
VS
2719 stdID(wxID_OK);
2720 stdID(wxID_CANCEL);
2721 stdID(wxID_APPLY);
2722 stdID(wxID_YES);
2723 stdID(wxID_NO);
2724 stdID(wxID_STATIC);
2725 stdID(wxID_FORWARD);
2726 stdID(wxID_BACKWARD);
2727 stdID(wxID_DEFAULT);
2728 stdID(wxID_MORE);
2729 stdID(wxID_SETUP);
2730 stdID(wxID_RESET);
2731 stdID(wxID_CONTEXT_HELP);
2732 stdID(wxID_YESTOALL);
2733 stdID(wxID_NOTOALL);
2734 stdID(wxID_ABORT);
2735 stdID(wxID_RETRY);
2736 stdID(wxID_IGNORE);
2737 stdID(wxID_ADD);
2738 stdID(wxID_REMOVE);
9a9c20be 2739
c369d4f1
VS
2740 stdID(wxID_UP);
2741 stdID(wxID_DOWN);
2742 stdID(wxID_HOME);
2743 stdID(wxID_REFRESH);
2744 stdID(wxID_STOP);
2745 stdID(wxID_INDEX);
9a9c20be 2746
c369d4f1
VS
2747 stdID(wxID_BOLD);
2748 stdID(wxID_ITALIC);
2749 stdID(wxID_JUSTIFY_CENTER);
2750 stdID(wxID_JUSTIFY_FILL);
2751 stdID(wxID_JUSTIFY_RIGHT);
2752 stdID(wxID_JUSTIFY_LEFT);
2753 stdID(wxID_UNDERLINE);
2754 stdID(wxID_INDENT);
2755 stdID(wxID_UNINDENT);
2756 stdID(wxID_ZOOM_100);
2757 stdID(wxID_ZOOM_FIT);
2758 stdID(wxID_ZOOM_IN);
2759 stdID(wxID_ZOOM_OUT);
2760 stdID(wxID_UNDELETE);
2761 stdID(wxID_REVERT_TO_SAVED);
6b1eedc1
VZ
2762 stdID(wxID_CDROM);
2763 stdID(wxID_CONVERT);
2764 stdID(wxID_EXECUTE);
2765 stdID(wxID_FLOPPY);
2766 stdID(wxID_HARDDISK);
2767 stdID(wxID_BOTTOM);
2768 stdID(wxID_FIRST);
2769 stdID(wxID_LAST);
2770 stdID(wxID_TOP);
2771 stdID(wxID_INFO);
2772 stdID(wxID_JUMP_TO);
2773 stdID(wxID_NETWORK);
2774 stdID(wxID_SELECT_COLOR);
2775 stdID(wxID_SELECT_FONT);
2776 stdID(wxID_SORT_ASCENDING);
2777 stdID(wxID_SORT_DESCENDING);
2778 stdID(wxID_SPELL_CHECK);
2779 stdID(wxID_STRIKETHROUGH);
c369d4f1 2780
9a9c20be
VZ
2781
2782 stdID(wxID_SYSTEM_MENU);
2783 stdID(wxID_CLOSE_FRAME);
2784 stdID(wxID_MOVE_FRAME);
2785 stdID(wxID_RESIZE_FRAME);
2786 stdID(wxID_MAXIMIZE_FRAME);
2787 stdID(wxID_ICONIZE_FRAME);
2788 stdID(wxID_RESTORE_FRAME);
2789
2790
2791
2792 stdID(wxID_MDI_WINDOW_CASCADE);
2793 stdID(wxID_MDI_WINDOW_TILE_HORZ);
2794 stdID(wxID_MDI_WINDOW_TILE_VERT);
2795 stdID(wxID_MDI_WINDOW_ARRANGE_ICONS);
2796 stdID(wxID_MDI_WINDOW_PREV);
2797 stdID(wxID_MDI_WINDOW_NEXT);
13de23f6
VS
2798#undef stdID
2799}
78d14f80 2800
a58804ea 2801} // anonymous namespace
78d14f80
VS
2802
2803
a58804ea
VZ
2804/*static*/
2805int wxXmlResource::DoGetXRCID(const char *str_id, int value_if_not_found)
2806{
2807 if ( !gs_stdIDsAdded )
2808 {
2809 gs_stdIDsAdded = true;
2810 AddStdXRCID_Records();
2811 }
2812
2813 return XRCID_Lookup(str_id, value_if_not_found);
2814}
2815
2816/* static */
2817wxString wxXmlResource::FindXRCIDById(int numId)
2818{
2819 for ( int i = 0; i < XRCID_TABLE_SIZE; i++ )
2820 {
2821 for ( XRCID_record *rec = XRCID_Records[i]; rec; rec = rec->next )
2822 {
2823 if ( rec->id == numId )
2824 return wxString(rec->key);
2825 }
2826 }
2827
2828 return wxString();
2829}
2830
2831static void CleanXRCID_Record(XRCID_record *rec)
2832{
2833 if (rec)
2834 {
2835 CleanXRCID_Record(rec->next);
2836
2837 free(rec->key);
2838 delete rec;
2839 }
2840}
2841
2842static void CleanXRCID_Records()
2843{
2844 for (int i = 0; i < XRCID_TABLE_SIZE; i++)
2845 {
2846 CleanXRCID_Record(XRCID_Records[i]);
2847 XRCID_Records[i] = NULL;
2848 }
2849
2850 gs_stdIDsAdded = false;
2851}
78d14f80
VS
2852
2853
819559b2
VS
2854//-----------------------------------------------------------------------------
2855// module and globals
2856//-----------------------------------------------------------------------------
78d14f80 2857
fd230129
VZ
2858// normally we would do the cleanup from wxXmlResourceModule::OnExit() but it
2859// can happen that some XRC records have been created because of the use of
2860// XRCID() in event tables, which happens during static objects initialization,
2861// but then the application initialization failed and so the wx modules were
2862// neither initialized nor cleaned up -- this static object does the cleanup in
2863// this case
2864static struct wxXRCStaticCleanup
2865{
2866 ~wxXRCStaticCleanup() { CleanXRCID_Records(); }
2867} s_staticCleanup;
2868
78d14f80
VS
2869class wxXmlResourceModule: public wxModule
2870{
2871DECLARE_DYNAMIC_CLASS(wxXmlResourceModule)
2872public:
2873 wxXmlResourceModule() {}
824e8eaa
VS
2874 bool OnInit()
2875 {
2b5f62a0 2876 wxXmlResource::AddSubclassFactory(new wxXmlSubclassFactoryCXX);
f80ea77b 2877 return true;
824e8eaa 2878 }
78d14f80
VS
2879 void OnExit()
2880 {
1542c42e 2881 delete wxXmlResource::Set(NULL);
0526c8cc 2882 delete wxIdRangeManager::Set(NULL);
461932ae 2883 if(wxXmlResource::ms_subclassFactories)
eb2d0d23
VS
2884 {
2885 for ( wxXmlSubclassFactories::iterator i = wxXmlResource::ms_subclassFactories->begin();
2886 i != wxXmlResource::ms_subclassFactories->end(); ++i )
2887 {
2888 delete *i;
2889 }
2890 wxDELETE(wxXmlResource::ms_subclassFactories);
2891 }
5ed345b7 2892 CleanXRCID_Records();
78d14f80
VS
2893 }
2894};
2895
2896IMPLEMENT_DYNAMIC_CLASS(wxXmlResourceModule, wxModule)
2897
2898
2899// When wxXml is loaded dynamically after the application is already running
2900// then the built-in module system won't pick this one up. Add it manually.
2901void wxXmlInitResourceModule()
2902{
2903 wxModule* module = new wxXmlResourceModule;
2904 module->Init();
2905 wxModule::RegisterModule(module);
2906}
a1e4ec87
VS
2907
2908#endif // wxUSE_XRC