Add missing styles support to wxWindow XRC handler.
[wxWidgets.git] / src / xrc / xmlres.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/xrc/xmlres.cpp
3 // Purpose: XRC resources
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
11 // For compilers that support precompilation, includes "wx.h".
12 #include "wx/wxprec.h"
13
14 #ifdef __BORLANDC__
15 #pragma hdrstop
16 #endif
17
18 #if wxUSE_XRC
19
20 #include "wx/xrc/xmlres.h"
21
22 #ifndef WX_PRECOMP
23 #include "wx/intl.h"
24 #include "wx/log.h"
25 #include "wx/panel.h"
26 #include "wx/frame.h"
27 #include "wx/dialog.h"
28 #include "wx/settings.h"
29 #include "wx/bitmap.h"
30 #include "wx/image.h"
31 #include "wx/module.h"
32 #include "wx/wxcrtvararg.h"
33 #endif
34
35 #ifndef __WXWINCE__
36 #include <locale.h>
37 #endif
38
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"
48 #include "wx/dir.h"
49 #include "wx/xml/xml.h"
50 #include "wx/hashset.h"
51 #include "wx/scopedptr.h"
52
53 namespace
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
60 wxDateTime 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
75
76 // Assign the given value to the specified entry or add a new value with this
77 // name.
78 static void XRCID_Assign(const wxString& str_id, int value);
79
80 class wxXmlResourceDataRecord
81 {
82 public:
83 // Ctor takes ownership of the document pointer.
84 wxXmlResourceDataRecord(const wxString& File_,
85 wxXmlDocument *Doc_
86 )
87 : File(File_), Doc(Doc_)
88 {
89 #if wxUSE_DATETIME
90 Time = GetXRCFileModTime(File);
91 #endif
92 }
93
94 ~wxXmlResourceDataRecord() {delete Doc;}
95
96 wxString File;
97 wxXmlDocument *Doc;
98 #if wxUSE_DATETIME
99 wxDateTime Time;
100 #endif
101
102 wxDECLARE_NO_COPY_CLASS(wxXmlResourceDataRecord);
103 };
104
105 class wxXmlResourceDataRecords : public wxVector<wxXmlResourceDataRecord*>
106 {
107 // this is a class so that it can be forward-declared
108 };
109
110 WX_DECLARE_HASH_SET_PTR(int, wxIntegerHash, wxIntegerEqual, wxHashSetInt);
111
112 class wxIdRange // Holds data for a particular rangename
113 {
114 protected:
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
140 class wxIdRangeManager
141 {
142 public:
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;
159
160 protected:
161 wxIdRange* FindRangeForItem(const wxXmlNode* node,
162 const wxString& item,
163 wxString& value) const;
164 wxVector<wxIdRange*> m_IdRanges;
165
166 private:
167 static wxIdRangeManager *ms_instance;
168 };
169
170 namespace
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
177 inline 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
184 // special XML attribute with name of input file, see GetFileNameFromNode()
185 const char *ATTR_INPUT_FILENAME = "__wx:filename";
186
187 // helper to get filename corresponding to an XML node
188 wxString
189 GetFileNameFromNode(const wxXmlNode *node, const wxXmlResourceDataRecords& files)
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
226 } // anonymous namespace
227
228
229 wxXmlResource *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
245 wxXmlResource::wxXmlResource(int flags, const wxString& domain)
246 {
247 m_flags = flags;
248 m_version = -1;
249 m_data = new wxXmlResourceDataRecords;
250 SetDomain(domain);
251 }
252
253 wxXmlResource::wxXmlResource(const wxString& filemask, int flags, const wxString& domain)
254 {
255 m_flags = flags;
256 m_version = -1;
257 m_data = new wxXmlResourceDataRecords;
258 SetDomain(domain);
259 Load(filemask);
260 }
261
262 wxXmlResource::~wxXmlResource()
263 {
264 ClearHandlers();
265
266 for ( wxXmlResourceDataRecords::iterator i = m_data->begin();
267 i != m_data->end(); ++i )
268 {
269 delete *i;
270 }
271 delete m_data;
272 }
273
274 void wxXmlResource::SetDomain(const wxString& domain)
275 {
276 m_domain = domain;
277 }
278
279
280 /* static */
281 wxString 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 */
311 bool 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
320 bool wxXmlResource::LoadFile(const wxFileName& file)
321 {
322 #if wxUSE_FILESYSTEM
323 return Load(wxFileSystem::FileNameToURL(file));
324 #else
325 return Load(file.GetFullPath());
326 #endif
327 }
328
329 bool 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
345 bool wxXmlResource::Load(const wxString& filemask_)
346 {
347 wxString filemask = ConvertFileNameToURL(filemask_);
348
349 bool allOK = true;
350
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
359 wxString fnd = wxXmlFindFirst;
360 if ( fnd.empty() )
361 {
362 wxLogError(_("Cannot load resources from '%s'."), filemask);
363 return false;
364 }
365
366 while (!fnd.empty())
367 {
368 #if wxUSE_FILESYSTEM
369 if ( IsArchive(fnd) )
370 {
371 if ( !Load(fnd + wxT("#zip:*.xrc")) )
372 allOK = false;
373 }
374 else // a single resource URL
375 #endif // wxUSE_FILESYSTEM
376 {
377 wxXmlDocument * const doc = DoLoadFile(fnd);
378 if ( !doc )
379 allOK = false;
380 else
381 Data().push_back(new wxXmlResourceDataRecord(fnd, doc));
382 }
383
384 fnd = wxXmlFindNext;
385 }
386 # undef wxXmlFindFirst
387 # undef wxXmlFindNext
388
389 return allOK;
390 }
391
392 bool wxXmlResource::Unload(const wxString& filename)
393 {
394 wxASSERT_MSG( !wxIsWild(filename),
395 wxT("wildcards not supported by wxXmlResource::Unload()") );
396
397 wxString fnd = ConvertFileNameToURL(filename);
398 #if wxUSE_FILESYSTEM
399 const bool isArchive = IsArchive(fnd);
400 if ( isArchive )
401 fnd += wxT("#zip:");
402 #endif // wxUSE_FILESYSTEM
403
404 bool unloaded = false;
405 for ( wxXmlResourceDataRecords::iterator i = Data().begin();
406 i != Data().end(); ++i )
407 {
408 #if wxUSE_FILESYSTEM
409 if ( isArchive )
410 {
411 if ( (*i)->File.StartsWith(fnd) )
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 {
418 if ( (*i)->File == fnd )
419 {
420 delete *i;
421 Data().erase(i);
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
433
434 IMPLEMENT_ABSTRACT_CLASS(wxXmlResourceHandler, wxObject)
435
436 void wxXmlResource::AddHandler(wxXmlResourceHandler *handler)
437 {
438 m_handlers.push_back(handler);
439 handler->SetParentResource(this);
440 }
441
442 void wxXmlResource::InsertHandler(wxXmlResourceHandler *handler)
443 {
444 m_handlers.insert(m_handlers.begin(), handler);
445 handler->SetParentResource(this);
446 }
447
448
449
450 void wxXmlResource::ClearHandlers()
451 {
452 for ( wxVector<wxXmlResourceHandler*>::iterator i = m_handlers.begin();
453 i != m_handlers.end(); ++i )
454 delete *i;
455 m_handlers.clear();
456 }
457
458
459 wxMenu *wxXmlResource::LoadMenu(const wxString& name)
460 {
461 return (wxMenu*)CreateResFromNode(FindResource(name, wxT("wxMenu")), NULL, NULL);
462 }
463
464
465
466 wxMenuBar *wxXmlResource::LoadMenuBar(wxWindow *parent, const wxString& name)
467 {
468 return (wxMenuBar*)CreateResFromNode(FindResource(name, wxT("wxMenuBar")), parent, NULL);
469 }
470
471
472
473 #if wxUSE_TOOLBAR
474 wxToolBar *wxXmlResource::LoadToolBar(wxWindow *parent, const wxString& name)
475 {
476 return (wxToolBar*)CreateResFromNode(FindResource(name, wxT("wxToolBar")), parent, NULL);
477 }
478 #endif
479
480
481 wxDialog *wxXmlResource::LoadDialog(wxWindow *parent, const wxString& name)
482 {
483 return (wxDialog*)CreateResFromNode(FindResource(name, wxT("wxDialog")), parent, NULL);
484 }
485
486 bool wxXmlResource::LoadDialog(wxDialog *dlg, wxWindow *parent, const wxString& name)
487 {
488 return CreateResFromNode(FindResource(name, wxT("wxDialog")), parent, dlg) != NULL;
489 }
490
491
492
493 wxPanel *wxXmlResource::LoadPanel(wxWindow *parent, const wxString& name)
494 {
495 return (wxPanel*)CreateResFromNode(FindResource(name, wxT("wxPanel")), parent, NULL);
496 }
497
498 bool wxXmlResource::LoadPanel(wxPanel *panel, wxWindow *parent, const wxString& name)
499 {
500 return CreateResFromNode(FindResource(name, wxT("wxPanel")), parent, panel) != NULL;
501 }
502
503 wxFrame *wxXmlResource::LoadFrame(wxWindow* parent, const wxString& name)
504 {
505 return (wxFrame*)CreateResFromNode(FindResource(name, wxT("wxFrame")), parent, NULL);
506 }
507
508 bool wxXmlResource::LoadFrame(wxFrame* frame, wxWindow *parent, const wxString& name)
509 {
510 return CreateResFromNode(FindResource(name, wxT("wxFrame")), parent, frame) != NULL;
511 }
512
513 wxBitmap 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
523 wxIcon 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
533
534 wxObject *
535 wxXmlResource::DoLoadObject(wxWindow *parent,
536 const wxString& name,
537 const wxString& classname,
538 bool recursive)
539 {
540 wxXmlNode * const node = FindResource(name, classname, recursive);
541
542 return node ? DoCreateResFromNode(*node, parent, NULL) : NULL;
543 }
544
545 bool
546 wxXmlResource::DoLoadObject(wxObject *instance,
547 wxWindow *parent,
548 const wxString& name,
549 const wxString& classname,
550 bool recursive)
551 {
552 wxXmlNode * const node = FindResource(name, classname, recursive);
553
554 return node && DoCreateResFromNode(*node, parent, instance) != NULL;
555 }
556
557
558 bool 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 {
566 wxLogError("Cannot find container for unknown control '%s'.", name);
567 return false;
568 }
569 return control->Reparent(container);
570 }
571
572
573 static void ProcessPlatformProperty(wxXmlNode *node)
574 {
575 wxString s;
576 bool isok;
577
578 wxXmlNode *c = node->GetChildren();
579 while (c)
580 {
581 isok = false;
582 if (!c->GetAttribute(wxT("platform"), &s))
583 isok = true;
584 else
585 {
586 wxStringTokenizer tkn(s, wxT(" |"));
587
588 while (tkn.HasMoreTokens())
589 {
590 s = tkn.GetNextToken();
591 #ifdef __WINDOWS__
592 if (s == wxT("win")) isok = true;
593 #endif
594 #if defined(__MAC__) || defined(__APPLE__)
595 if (s == wxT("mac")) isok = true;
596 #elif defined(__UNIX__)
597 if (s == wxT("unix")) isok = true;
598 #endif
599 #ifdef __OS2__
600 if (s == wxT("os2")) isok = true;
601 #endif
602
603 if (isok)
604 break;
605 }
606 }
607
608 if (isok)
609 {
610 ProcessPlatformProperty(c);
611 c = c->GetNext();
612 }
613 else
614 {
615 wxXmlNode *c2 = c->GetNext();
616 node->RemoveChild(c);
617 delete c;
618 c = c2;
619 }
620 }
621 }
622
623 static 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);
642
643 // Do any children by recursion, then proceed to the next sibling
644 PreprocessForIdRanges(c);
645 c = c->GetNext();
646 }
647 }
648
649 bool wxXmlResource::UpdateResources()
650 {
651 bool rt = true;
652
653 for ( wxXmlResourceDataRecords::iterator i = Data().begin();
654 i != Data().end(); ++i )
655 {
656 wxXmlResourceDataRecord* const rec = *i;
657
658 // Check if we need to reload this one.
659
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
676 {
677 // No need to reload, the file wasn't modified since we did it
678 // last.
679 continue;
680 }
681
682 wxXmlDocument * const doc = DoLoadFile(rec->File);
683 if ( !doc )
684 {
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 }
691
692 // Replace the old resource contents with the new one.
693 delete rec->Doc;
694 rec->Doc = doc;
695
696 // And, now that we loaded it successfully, update the last load time.
697 #if wxUSE_DATETIME
698 rec->Time = lastModTime.IsValid() ? lastModTime : wxDateTime::Now();
699 #endif // wxUSE_DATETIME
700 }
701
702 return rt;
703 }
704
705 wxXmlDocument *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
781 wxXmlNode *wxXmlResource::DoFindResource(wxXmlNode *parent,
782 const wxString& name,
783 const wxString& classname,
784 bool recursive) const
785 {
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 {
792 if ( IsObjectNode(node) && node->GetAttribute(wxS("name")) == name )
793 {
794 // empty class name matches everything
795 if ( classname.empty() )
796 return node;
797
798 wxString cls(node->GetAttribute(wxS("class")));
799
800 // object_ref may not have 'class' attribute:
801 if (cls.empty() && node->GetName() == wxS("object_ref"))
802 {
803 wxString refName = node->GetAttribute(wxS("ref"));
804 if (refName.empty())
805 continue;
806
807 const wxXmlNode * const refNode = GetResourceNode(refName);
808 if ( refNode )
809 cls = refNode->GetAttribute(wxS("class"));
810 }
811
812 if ( cls == classname )
813 return node;
814 }
815 }
816
817 // then recurse in child nodes
818 if ( recursive )
819 {
820 for (node = parent->GetChildren(); node; node = node->GetNext())
821 {
822 if ( IsObjectNode(node) )
823 {
824 wxXmlNode* found = DoFindResource(node, name, classname, true);
825 if ( found )
826 return found;
827 }
828 }
829 }
830
831 return NULL;
832 }
833
834 wxXmlNode *wxXmlResource::FindResource(const wxString& name,
835 const wxString& classname,
836 bool recursive)
837 {
838 wxString path;
839 wxXmlNode * const
840 node = GetResourceNodeAndLocation(name, classname, recursive, &path);
841
842 if ( !node )
843 {
844 ReportError
845 (
846 NULL,
847 wxString::Format
848 (
849 "XRC resource \"%s\" (class \"%s\") not found",
850 name, classname
851 )
852 );
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
867 wxXmlNode *
868 wxXmlResource::GetResourceNodeAndLocation(const wxString& name,
869 const wxString& classname,
870 bool recursive,
871 wxString *path) const
872 {
873 // ensure everything is up-to-date: this is needed to support on-demand
874 // reloading of XRC files
875 const_cast<wxXmlResource *>(this)->UpdateResources();
876
877 for ( wxXmlResourceDataRecords::const_iterator f = Data().begin();
878 f != Data().end(); ++f )
879 {
880 wxXmlResourceDataRecord *const rec = *f;
881 wxXmlDocument * const doc = rec->Doc;
882 if ( !doc || !doc->GetRoot() )
883 continue;
884
885 wxXmlNode * const
886 found = DoFindResource(doc->GetRoot(), name, classname, recursive);
887 if ( found )
888 {
889 if ( path )
890 *path = rec->File;
891
892 return found;
893 }
894 }
895
896 return NULL;
897 }
898
899 static void MergeNodesOver(wxXmlNode& dest, wxXmlNode& overwriteWith,
900 const wxString& overwriteFilename)
901 {
902 // Merge attributes:
903 for ( wxXmlAttribute *attr = overwriteWith.GetAttributes();
904 attr; attr = attr->GetNext() )
905 {
906 wxXmlAttribute *dattr;
907 for (dattr = dest.GetAttributes(); dattr; dattr = dattr->GetNext())
908 {
909
910 if ( dattr->GetName() == attr->GetName() )
911 {
912 dattr->SetValue(attr->GetValue());
913 break;
914 }
915 }
916
917 if ( !dattr )
918 dest.AddAttribute(attr->GetName(), attr->GetValue());
919 }
920
921 // Merge child nodes:
922 for (wxXmlNode* node = overwriteWith.GetChildren(); node; node = node->GetNext())
923 {
924 wxString name = node->GetAttribute(wxT("name"), wxEmptyString);
925 wxXmlNode *dnode;
926
927 for (dnode = dest.GetChildren(); dnode; dnode = dnode->GetNext() )
928 {
929 if ( dnode->GetName() == node->GetName() &&
930 dnode->GetAttribute(wxT("name"), wxEmptyString) == name &&
931 dnode->GetType() == node->GetType() )
932 {
933 MergeNodesOver(*dnode, *node, overwriteFilename);
934 break;
935 }
936 }
937
938 if ( !dnode )
939 {
940 wxXmlNode *copyOfNode = new wxXmlNode(*node);
941 // remember referenced object's file, see GetFileNameFromNode()
942 copyOfNode->AddAttribute(ATTR_INPUT_FILENAME, overwriteFilename);
943
944 static const wxChar *AT_END = wxT("end");
945 wxString insert_pos = node->GetAttribute(wxT("insert_at"), AT_END);
946 if ( insert_pos == AT_END )
947 {
948 dest.AddChild(copyOfNode);
949 }
950 else if ( insert_pos == wxT("begin") )
951 {
952 dest.InsertChild(copyOfNode, dest.GetChildren());
953 }
954 }
955 }
956
957 if ( dest.GetType() == wxXML_TEXT_NODE && overwriteWith.GetContent().length() )
958 dest.SetContent(overwriteWith.GetContent());
959 }
960
961 wxObject *
962 wxXmlResource::DoCreateResFromNode(wxXmlNode& node,
963 wxObject *parent,
964 wxObject *instance,
965 wxXmlResourceHandler *handlerToUse)
966 {
967 // handling of referenced resource
968 if ( node.GetName() == wxT("object_ref") )
969 {
970 wxString refName = node.GetAttribute(wxT("ref"), wxEmptyString);
971 wxXmlNode* refNode = FindResource(refName, wxEmptyString, true);
972
973 if ( !refNode )
974 {
975 ReportError
976 (
977 &node,
978 wxString::Format
979 (
980 "referenced object node with ref=\"%s\" not found",
981 refName
982 )
983 );
984 return NULL;
985 }
986
987 const bool hasOnlyRefAttr = node.GetAttributes() != NULL &&
988 node.GetAttributes()->GetNext() == NULL;
989
990 if ( hasOnlyRefAttr && !node.GetChildren() )
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
997 return DoCreateResFromNode(*refNode, parent, instance);
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);
1007 MergeNodesOver(copy, node, GetFileNameFromNode(&node, Data()));
1008
1009 // remember referenced object's file, see GetFileNameFromNode()
1010 copy.AddAttribute(ATTR_INPUT_FILENAME,
1011 GetFileNameFromNode(refNode, Data()));
1012
1013 return DoCreateResFromNode(copy, parent, instance);
1014 }
1015 }
1016
1017 if (handlerToUse)
1018 {
1019 if (handlerToUse->CanHandle(&node))
1020 {
1021 return handlerToUse->CreateResource(&node, parent, instance);
1022 }
1023 }
1024 else if (node.GetName() == wxT("object"))
1025 {
1026 for ( wxVector<wxXmlResourceHandler*>::iterator h = m_handlers.begin();
1027 h != m_handlers.end(); ++h )
1028 {
1029 wxXmlResourceHandler *handler = *h;
1030 if (handler->CanHandle(&node))
1031 return handler->CreateResource(&node, parent, instance);
1032 }
1033 }
1034
1035 ReportError
1036 (
1037 &node,
1038 wxString::Format
1039 (
1040 "no handler found for XML node \"%s\" (class \"%s\")",
1041 node.GetName(),
1042 node.GetAttribute("class", wxEmptyString)
1043 )
1044 );
1045 return NULL;
1046 }
1047
1048 wxIdRange::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
1098 void 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
1173 void 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 {
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);
1223
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()));
1229 }
1230 // and these special ones
1231 XRCID_Assign(m_name + "[start]", m_start);
1232 XRCID_Assign(m_name + "[end]", m_end);
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
1240 wxIdRangeManager *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
1256 wxIdRangeManager::~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
1268 void 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
1306 wxIdRange *
1307 wxIdRangeManager::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
1332 void
1333 wxIdRangeManager::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
1342 int 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
1353 void 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
1368
1369 class wxXmlSubclassFactories : public wxVector<wxXmlSubclassFactory*>
1370 {
1371 // this is a class so that it can be forward-declared
1372 };
1373
1374 wxXmlSubclassFactories *wxXmlResource::ms_subclassFactories = NULL;
1375
1376 /*static*/ void wxXmlResource::AddSubclassFactory(wxXmlSubclassFactory *factory)
1377 {
1378 if (!ms_subclassFactories)
1379 {
1380 ms_subclassFactories = new wxXmlSubclassFactories;
1381 }
1382 ms_subclassFactories->push_back(factory);
1383 }
1384
1385 class wxXmlSubclassFactoryCXX : public wxXmlSubclassFactory
1386 {
1387 public:
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
1403
1404 wxXmlResourceHandler::wxXmlResourceHandler()
1405 : m_node(NULL), m_parent(NULL), m_instance(NULL),
1406 m_parentAsWindow(NULL)
1407 {}
1408
1409
1410
1411 wxObject *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;
1416 wxWindow *myParentAW = m_parentAsWindow;
1417
1418 m_instance = instance;
1419 if (!m_instance && node->HasAttribute(wxT("subclass")) &&
1420 !(m_resource->GetFlags() & wxXRC_NO_SUBCLASSING))
1421 {
1422 wxString subclass = node->GetAttribute(wxT("subclass"), wxEmptyString);
1423 if (!subclass.empty())
1424 {
1425 for (wxXmlSubclassFactories::iterator i = wxXmlResource::ms_subclassFactories->begin();
1426 i != wxXmlResource::ms_subclassFactories->end(); ++i)
1427 {
1428 m_instance = (*i)->Create(subclass);
1429 if (m_instance)
1430 break;
1431 }
1432
1433 if (!m_instance)
1434 {
1435 wxString name = node->GetAttribute(wxT("name"), wxEmptyString);
1436 ReportError
1437 (
1438 node,
1439 wxString::Format
1440 (
1441 "subclass \"%s\" not found for resource \"%s\", not subclassing",
1442 subclass, name
1443 )
1444 );
1445 }
1446 }
1447 }
1448
1449 m_node = node;
1450 m_class = node->GetAttribute(wxT("class"), wxEmptyString);
1451 m_parent = parent;
1452 m_parentAsWindow = wxDynamicCast(m_parent, wxWindow);
1453
1454 wxObject *returned = DoCreateResource();
1455
1456 m_node = myNode;
1457 m_class = myClass;
1458 m_parent = myParent; m_parentAsWindow = myParentAW;
1459 m_instance = myInstance;
1460
1461 return returned;
1462 }
1463
1464
1465 void wxXmlResourceHandler::AddStyle(const wxString& name, int value)
1466 {
1467 m_styleNames.Add(name);
1468 m_styleValues.Add(value);
1469 }
1470
1471
1472
1473 void wxXmlResourceHandler::AddWindowStyles()
1474 {
1475 XRC_ADD_STYLE(wxCLIP_CHILDREN);
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);
1480 XRC_ADD_STYLE(wxDOUBLE_BORDER); XRC_ADD_STYLE(wxBORDER_DOUBLE); // deprecated
1481 XRC_ADD_STYLE(wxBORDER_THEME);
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);
1485 XRC_ADD_STYLE(wxBORDER_DEFAULT);
1486
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(wxVSCROLL);
1493 XRC_ADD_STYLE(wxHSCROLL);
1494 XRC_ADD_STYLE(wxALWAYS_SHOW_SB);
1495
1496 XRC_ADD_STYLE(wxWS_EX_BLOCK_EVENTS);
1497 XRC_ADD_STYLE(wxWS_EX_VALIDATE_RECURSIVELY);
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);
1502 }
1503
1504
1505
1506 bool wxXmlResourceHandler::HasParam(const wxString& param)
1507 {
1508 return (GetParamNode(param) != NULL);
1509 }
1510
1511
1512 int wxXmlResourceHandler::GetStyle(const wxString& param, int defaults)
1513 {
1514 wxString s = GetParamValue(param);
1515
1516 if (!s) return defaults;
1517
1518 wxStringTokenizer tkn(s, wxT("| \t\n"), wxTOKEN_STRTOK);
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)
1527 {
1528 style |= m_styleValues[index];
1529 }
1530 else
1531 {
1532 ReportParamError
1533 (
1534 param,
1535 wxString::Format("unknown style flag \"%s\"", fl)
1536 );
1537 }
1538 }
1539 return style;
1540 }
1541
1542
1543
1544 wxString wxXmlResourceHandler::GetText(const wxString& param, bool translate)
1545 {
1546 wxXmlNode *parNode = GetParamNode(param);
1547 wxString str1(GetNodeContent(parNode));
1548 wxString str2;
1549
1550 // "\\" wasn't translated to "\" prior to 2.5.3.0:
1551 const bool escapeBackslash = (m_resource->CompareVersion(2,5,3,0) >= 0);
1552
1553 // VS: First version of XRC resources used $ instead of & (which is
1554 // illegal in XML), but later I realized that '_' fits this purpose
1555 // much better (because &File means "File with F underlined").
1556 const wxChar amp_char = (m_resource->CompareVersion(2,3,0,1) < 0)
1557 ? '$' : '_';
1558
1559 for ( wxString::const_iterator dt = str1.begin(); dt != str1.end(); ++dt )
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..."):
1563 if ( *dt == amp_char )
1564 {
1565 if ( dt+1 == str1.end() || *(++dt) == amp_char )
1566 str2 << amp_char;
1567 else
1568 str2 << wxT('&') << *dt;
1569 }
1570 // Remap \n to CR, \r to LF, \t to TAB, \\ to \:
1571 else if ( *dt == wxT('\\') )
1572 {
1573 switch ( (*(++dt)).GetValue() )
1574 {
1575 case wxT('n'):
1576 str2 << wxT('\n');
1577 break;
1578
1579 case wxT('t'):
1580 str2 << wxT('\t');
1581 break;
1582
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:
1589 if ( escapeBackslash )
1590 {
1591 str2 << wxT('\\');
1592 break;
1593 }
1594 // else fall-through to default: branch below
1595
1596 default:
1597 str2 << wxT('\\') << *dt;
1598 break;
1599 }
1600 }
1601 else
1602 {
1603 str2 << *dt;
1604 }
1605 }
1606
1607 if (m_resource->GetFlags() & wxXRC_USE_LOCALE)
1608 {
1609 if (translate && parNode &&
1610 parNode->GetAttribute(wxT("translate"), wxEmptyString) != wxT("0"))
1611 {
1612 return wxGetTranslation(str2, m_resource->GetDomain());
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:
1621 return wxString(str2.wc_str(wxConvUTF8), wxConvLocal);
1622 #endif
1623 }
1624 }
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;
1630 }
1631
1632
1633
1634 long wxXmlResourceHandler::GetLong(const wxString& param, long defaultv)
1635 {
1636 long value;
1637 wxString str1 = GetParamValue(param);
1638
1639 if (!str1.ToLong(&value))
1640 value = defaultv;
1641
1642 return value;
1643 }
1644
1645 float wxXmlResourceHandler::GetFloat(const wxString& param, float defaultv)
1646 {
1647 wxString str = GetParamValue(param);
1648
1649 // strings in XRC always use C locale so make sure to use the
1650 // locale-independent wxString::ToCDouble() and not ToDouble() which uses
1651 // the current locale with a potentially different decimal point character
1652 double value;
1653 if (!str.ToCDouble(&value))
1654 value = defaultv;
1655
1656 return wx_truncate_cast(float, value);
1657 }
1658
1659
1660 int wxXmlResourceHandler::GetID()
1661 {
1662 return wxXmlResource::GetXRCID(GetName());
1663 }
1664
1665
1666
1667 wxString wxXmlResourceHandler::GetName()
1668 {
1669 return m_node->GetAttribute(wxT("name"), wxT("-1"));
1670 }
1671
1672
1673
1674 bool wxXmlResourceHandler::GetBoolAttr(const wxString& attr, bool defaultv)
1675 {
1676 wxString v;
1677 return m_node->GetAttribute(attr, &v) ? v == '1' : defaultv;
1678 }
1679
1680 bool wxXmlResourceHandler::GetBool(const wxString& param, bool defaultv)
1681 {
1682 const wxString v = GetParamValue(param);
1683
1684 return v.empty() ? defaultv : (v == '1');
1685 }
1686
1687
1688 static wxColour GetSystemColour(const wxString& name)
1689 {
1690 if (!name.empty())
1691 {
1692 #define SYSCLR(clr) \
1693 if (name == wxT(#clr)) return wxSystemSettings::GetColour(clr);
1694 SYSCLR(wxSYS_COLOUR_SCROLLBAR)
1695 SYSCLR(wxSYS_COLOUR_BACKGROUND)
1696 SYSCLR(wxSYS_COLOUR_DESKTOP)
1697 SYSCLR(wxSYS_COLOUR_ACTIVECAPTION)
1698 SYSCLR(wxSYS_COLOUR_INACTIVECAPTION)
1699 SYSCLR(wxSYS_COLOUR_MENU)
1700 SYSCLR(wxSYS_COLOUR_WINDOW)
1701 SYSCLR(wxSYS_COLOUR_WINDOWFRAME)
1702 SYSCLR(wxSYS_COLOUR_MENUTEXT)
1703 SYSCLR(wxSYS_COLOUR_WINDOWTEXT)
1704 SYSCLR(wxSYS_COLOUR_CAPTIONTEXT)
1705 SYSCLR(wxSYS_COLOUR_ACTIVEBORDER)
1706 SYSCLR(wxSYS_COLOUR_INACTIVEBORDER)
1707 SYSCLR(wxSYS_COLOUR_APPWORKSPACE)
1708 SYSCLR(wxSYS_COLOUR_HIGHLIGHT)
1709 SYSCLR(wxSYS_COLOUR_HIGHLIGHTTEXT)
1710 SYSCLR(wxSYS_COLOUR_BTNFACE)
1711 SYSCLR(wxSYS_COLOUR_3DFACE)
1712 SYSCLR(wxSYS_COLOUR_BTNSHADOW)
1713 SYSCLR(wxSYS_COLOUR_3DSHADOW)
1714 SYSCLR(wxSYS_COLOUR_GRAYTEXT)
1715 SYSCLR(wxSYS_COLOUR_BTNTEXT)
1716 SYSCLR(wxSYS_COLOUR_INACTIVECAPTIONTEXT)
1717 SYSCLR(wxSYS_COLOUR_BTNHIGHLIGHT)
1718 SYSCLR(wxSYS_COLOUR_BTNHILIGHT)
1719 SYSCLR(wxSYS_COLOUR_3DHIGHLIGHT)
1720 SYSCLR(wxSYS_COLOUR_3DHILIGHT)
1721 SYSCLR(wxSYS_COLOUR_3DDKSHADOW)
1722 SYSCLR(wxSYS_COLOUR_3DLIGHT)
1723 SYSCLR(wxSYS_COLOUR_INFOTEXT)
1724 SYSCLR(wxSYS_COLOUR_INFOBK)
1725 SYSCLR(wxSYS_COLOUR_LISTBOX)
1726 SYSCLR(wxSYS_COLOUR_HOTLIGHT)
1727 SYSCLR(wxSYS_COLOUR_GRADIENTACTIVECAPTION)
1728 SYSCLR(wxSYS_COLOUR_GRADIENTINACTIVECAPTION)
1729 SYSCLR(wxSYS_COLOUR_MENUHILIGHT)
1730 SYSCLR(wxSYS_COLOUR_MENUBAR)
1731 #undef SYSCLR
1732 }
1733
1734 return wxNullColour;
1735 }
1736
1737 wxColour wxXmlResourceHandler::GetColour(const wxString& param, const wxColour& defaultv)
1738 {
1739 wxString v = GetParamValue(param);
1740
1741 if ( v.empty() )
1742 return defaultv;
1743
1744 wxColour clr;
1745
1746 // wxString -> wxColour conversion
1747 if (!clr.Set(v))
1748 {
1749 // the colour doesn't use #RRGGBB format, check if it is symbolic
1750 // colour name:
1751 clr = GetSystemColour(v);
1752 if (clr.IsOk())
1753 return clr;
1754
1755 ReportParamError
1756 (
1757 param,
1758 wxString::Format("incorrect colour specification \"%s\"", v)
1759 );
1760 return wxNullColour;
1761 }
1762
1763 return clr;
1764 }
1765
1766 namespace
1767 {
1768
1769 // if 'param' has stock_id/stock_client, extracts them and returns true
1770 bool GetStockArtAttrs(const wxXmlNode *paramNode,
1771 const wxString& defaultArtClient,
1772 wxString& art_id, wxString& art_client)
1773 {
1774 if ( paramNode )
1775 {
1776 art_id = paramNode->GetAttribute("stock_id", "");
1777
1778 if ( !art_id.empty() )
1779 {
1780 art_id = wxART_MAKE_ART_ID_FROM_STR(art_id);
1781
1782 art_client = paramNode->GetAttribute("stock_client", "");
1783 if ( art_client.empty() )
1784 art_client = defaultArtClient;
1785 else
1786 art_client = wxART_MAKE_CLIENT_ID_FROM_STR(art_client);
1787
1788 return true;
1789 }
1790 }
1791
1792 return false;
1793 }
1794
1795 } // anonymous namespace
1796
1797 wxBitmap wxXmlResourceHandler::GetBitmap(const wxString& param,
1798 const wxArtClient& defaultArtClient,
1799 wxSize size)
1800 {
1801 // it used to be possible to pass an empty string here to indicate that the
1802 // bitmap name should be read from this node itself but this is not
1803 // supported any more because GetBitmap(m_node) can be used directly
1804 // instead
1805 wxASSERT_MSG( !param.empty(), "bitmap parameter name can't be empty" );
1806
1807 const wxXmlNode* const node = GetParamNode(param);
1808
1809 if ( !node )
1810 {
1811 // this is not an error as bitmap parameter could be optional
1812 return wxNullBitmap;
1813 }
1814
1815 return GetBitmap(node, defaultArtClient, size);
1816 }
1817
1818 wxBitmap wxXmlResourceHandler::GetBitmap(const wxXmlNode* node,
1819 const wxArtClient& defaultArtClient,
1820 wxSize size)
1821 {
1822 wxCHECK_MSG( node, wxNullBitmap, "bitmap node can't be NULL" );
1823
1824 /* If the bitmap is specified as stock item, query wxArtProvider for it: */
1825 wxString art_id, art_client;
1826 if ( GetStockArtAttrs(node, defaultArtClient,
1827 art_id, art_client) )
1828 {
1829 wxBitmap stockArt(wxArtProvider::GetBitmap(art_id, art_client, size));
1830 if ( stockArt.IsOk() )
1831 return stockArt;
1832 }
1833
1834 /* ...or load the bitmap from file: */
1835 wxString name = GetParamValue(node);
1836 if (name.empty()) return wxNullBitmap;
1837 #if wxUSE_FILESYSTEM
1838 wxFSFile *fsfile = GetCurFileSystem().OpenFile(name, wxFS_READ | wxFS_SEEKABLE);
1839 if (fsfile == NULL)
1840 {
1841 ReportParamError
1842 (
1843 node->GetName(),
1844 wxString::Format("cannot open bitmap resource \"%s\"", name)
1845 );
1846 return wxNullBitmap;
1847 }
1848 wxImage img(*(fsfile->GetStream()));
1849 delete fsfile;
1850 #else
1851 wxImage img(name);
1852 #endif
1853
1854 if (!img.IsOk())
1855 {
1856 ReportParamError
1857 (
1858 node->GetName(),
1859 wxString::Format("cannot create bitmap from \"%s\"", name)
1860 );
1861 return wxNullBitmap;
1862 }
1863 if (!(size == wxDefaultSize)) img.Rescale(size.x, size.y);
1864 return wxBitmap(img);
1865 }
1866
1867
1868 wxIcon wxXmlResourceHandler::GetIcon(const wxString& param,
1869 const wxArtClient& defaultArtClient,
1870 wxSize size)
1871 {
1872 // see comment in GetBitmap(wxString) overload
1873 wxASSERT_MSG( !param.empty(), "icon parameter name can't be empty" );
1874
1875 const wxXmlNode* const node = GetParamNode(param);
1876
1877 if ( !node )
1878 {
1879 // this is not an error as icon parameter could be optional
1880 return wxIcon();
1881 }
1882
1883 return GetIcon(node, defaultArtClient, size);
1884 }
1885
1886 wxIcon wxXmlResourceHandler::GetIcon(const wxXmlNode* node,
1887 const wxArtClient& defaultArtClient,
1888 wxSize size)
1889 {
1890 wxIcon icon;
1891 icon.CopyFromBitmap(GetBitmap(node, defaultArtClient, size));
1892 return icon;
1893 }
1894
1895
1896 wxIconBundle wxXmlResourceHandler::GetIconBundle(const wxString& param,
1897 const wxArtClient& defaultArtClient)
1898 {
1899 wxString art_id, art_client;
1900 if ( GetStockArtAttrs(GetParamNode(param), defaultArtClient,
1901 art_id, art_client) )
1902 {
1903 wxIconBundle stockArt(wxArtProvider::GetIconBundle(art_id, art_client));
1904 if ( stockArt.IsOk() )
1905 return stockArt;
1906 }
1907
1908 const wxString name = GetParamValue(param);
1909 if ( name.empty() )
1910 return wxNullIconBundle;
1911
1912 #if wxUSE_FILESYSTEM
1913 wxFSFile *fsfile = GetCurFileSystem().OpenFile(name, wxFS_READ | wxFS_SEEKABLE);
1914 if ( fsfile == NULL )
1915 {
1916 ReportParamError
1917 (
1918 param,
1919 wxString::Format("cannot open icon resource \"%s\"", name)
1920 );
1921 return wxNullIconBundle;
1922 }
1923
1924 wxIconBundle bundle(*(fsfile->GetStream()));
1925 delete fsfile;
1926 #else
1927 wxIconBundle bundle(name);
1928 #endif
1929
1930 if ( !bundle.IsOk() )
1931 {
1932 ReportParamError
1933 (
1934 param,
1935 wxString::Format("cannot create icon from \"%s\"", name)
1936 );
1937 return wxNullIconBundle;
1938 }
1939
1940 return bundle;
1941 }
1942
1943
1944 wxImageList *wxXmlResourceHandler::GetImageList(const wxString& param)
1945 {
1946 wxXmlNode * const imagelist_node = GetParamNode(param);
1947 if ( !imagelist_node )
1948 return NULL;
1949
1950 wxXmlNode * const oldnode = m_node;
1951 m_node = imagelist_node;
1952
1953 // Get the size if we have it, otherwise we will use the size of the first
1954 // list element.
1955 wxSize size = GetSize();
1956
1957 // Start adding images, we'll create the image list when adding the first
1958 // one.
1959 wxImageList * imagelist = NULL;
1960 wxString parambitmap = wxT("bitmap");
1961 if ( HasParam(parambitmap) )
1962 {
1963 wxXmlNode *n = m_node->GetChildren();
1964 while (n)
1965 {
1966 if (n->GetType() == wxXML_ELEMENT_NODE && n->GetName() == parambitmap)
1967 {
1968 wxIcon icon = GetIcon(n, wxART_OTHER, size);
1969 if ( !imagelist )
1970 {
1971 // We need the real image list size to create it.
1972 if ( size == wxDefaultSize )
1973 size = icon.GetSize();
1974
1975 // We use the mask by default.
1976 bool mask = !HasParam(wxS("mask")) || GetBool(wxS("mask"));
1977
1978 imagelist = new wxImageList(size.x, size.y, mask);
1979 }
1980
1981 // add icon instead of bitmap to keep the bitmap mask
1982 imagelist->Add(icon);
1983 }
1984 n = n->GetNext();
1985 }
1986 }
1987
1988 m_node = oldnode;
1989 return imagelist;
1990 }
1991
1992 wxXmlNode *wxXmlResourceHandler::GetParamNode(const wxString& param)
1993 {
1994 wxCHECK_MSG(m_node, NULL, wxT("You can't access handler data before it was initialized!"));
1995
1996 wxXmlNode *n = m_node->GetChildren();
1997
1998 while (n)
1999 {
2000 if (n->GetType() == wxXML_ELEMENT_NODE && n->GetName() == param)
2001 {
2002 // TODO: check that there are no other properties/parameters with
2003 // the same name and log an error if there are (can't do this
2004 // right now as I'm not sure if it's not going to break code
2005 // using this function in unintentional way (i.e. for
2006 // accessing other things than properties), for example
2007 // wxBitmapComboBoxXmlHandler almost surely does
2008 return n;
2009 }
2010 n = n->GetNext();
2011 }
2012 return NULL;
2013 }
2014
2015 /* static */
2016 bool wxXmlResourceHandler::IsOfClass(wxXmlNode *node, const wxString& classname)
2017 {
2018 return node->GetAttribute(wxT("class")) == classname;
2019 }
2020
2021
2022
2023 wxString wxXmlResourceHandler::GetNodeContent(const wxXmlNode *node)
2024 {
2025 const wxXmlNode *n = node;
2026 if (n == NULL) return wxEmptyString;
2027 n = n->GetChildren();
2028
2029 while (n)
2030 {
2031 if (n->GetType() == wxXML_TEXT_NODE ||
2032 n->GetType() == wxXML_CDATA_SECTION_NODE)
2033 return n->GetContent();
2034 n = n->GetNext();
2035 }
2036 return wxEmptyString;
2037 }
2038
2039
2040
2041 wxString wxXmlResourceHandler::GetParamValue(const wxString& param)
2042 {
2043 if (param.empty())
2044 return GetNodeContent(m_node);
2045 else
2046 return GetNodeContent(GetParamNode(param));
2047 }
2048
2049 wxString wxXmlResourceHandler::GetParamValue(const wxXmlNode* node)
2050 {
2051 return GetNodeContent(node);
2052 }
2053
2054
2055 wxSize wxXmlResourceHandler::GetSize(const wxString& param,
2056 wxWindow *windowToUse)
2057 {
2058 wxString s = GetParamValue(param);
2059 if (s.empty()) s = wxT("-1,-1");
2060 bool is_dlg;
2061 long sx, sy = 0;
2062
2063 is_dlg = s[s.length()-1] == wxT('d');
2064 if (is_dlg) s.RemoveLast();
2065
2066 if (!s.BeforeFirst(wxT(',')).ToLong(&sx) ||
2067 !s.AfterLast(wxT(',')).ToLong(&sy))
2068 {
2069 ReportParamError
2070 (
2071 param,
2072 wxString::Format("cannot parse coordinates value \"%s\"", s)
2073 );
2074 return wxDefaultSize;
2075 }
2076
2077 if (is_dlg)
2078 {
2079 if (windowToUse)
2080 {
2081 return wxDLG_UNIT(windowToUse, wxSize(sx, sy));
2082 }
2083 else if (m_parentAsWindow)
2084 {
2085 return wxDLG_UNIT(m_parentAsWindow, wxSize(sx, sy));
2086 }
2087 else
2088 {
2089 ReportParamError
2090 (
2091 param,
2092 "cannot convert dialog units: dialog unknown"
2093 );
2094 return wxDefaultSize;
2095 }
2096 }
2097
2098 return wxSize(sx, sy);
2099 }
2100
2101
2102
2103 wxPoint wxXmlResourceHandler::GetPosition(const wxString& param)
2104 {
2105 wxSize sz = GetSize(param);
2106 return wxPoint(sz.x, sz.y);
2107 }
2108
2109
2110
2111 wxCoord wxXmlResourceHandler::GetDimension(const wxString& param,
2112 wxCoord defaultv,
2113 wxWindow *windowToUse)
2114 {
2115 wxString s = GetParamValue(param);
2116 if (s.empty()) return defaultv;
2117 bool is_dlg;
2118 long sx;
2119
2120 is_dlg = s[s.length()-1] == wxT('d');
2121 if (is_dlg) s.RemoveLast();
2122
2123 if (!s.ToLong(&sx))
2124 {
2125 ReportParamError
2126 (
2127 param,
2128 wxString::Format("cannot parse dimension value \"%s\"", s)
2129 );
2130 return defaultv;
2131 }
2132
2133 if (is_dlg)
2134 {
2135 if (windowToUse)
2136 {
2137 return wxDLG_UNIT(windowToUse, wxSize(sx, 0)).x;
2138 }
2139 else if (m_parentAsWindow)
2140 {
2141 return wxDLG_UNIT(m_parentAsWindow, wxSize(sx, 0)).x;
2142 }
2143 else
2144 {
2145 ReportParamError
2146 (
2147 param,
2148 "cannot convert dialog units: dialog unknown"
2149 );
2150 return defaultv;
2151 }
2152 }
2153
2154 return sx;
2155 }
2156
2157 wxDirection
2158 wxXmlResourceHandler::GetDirection(const wxString& param, wxDirection dirDefault)
2159 {
2160 wxDirection dir;
2161
2162 const wxString dirstr = GetParamValue(param);
2163 if ( dirstr.empty() )
2164 dir = dirDefault;
2165 else if ( dirstr == "wxLEFT" )
2166 dir = wxLEFT;
2167 else if ( dirstr == "wxRIGHT" )
2168 dir = wxRIGHT;
2169 else if ( dirstr == "wxTOP" )
2170 dir = wxTOP;
2171 else if ( dirstr == "wxBOTTOM" )
2172 dir = wxBOTTOM;
2173 else
2174 {
2175 ReportError
2176 (
2177 GetParamNode(param),
2178 wxString::Format
2179 (
2180 "Invalid direction \"%s\": must be one of "
2181 "wxLEFT|wxRIGHT|wxTOP|wxBOTTOM.",
2182 dirstr
2183 )
2184 );
2185
2186 dir = dirDefault;
2187 }
2188
2189 return dir;
2190 }
2191
2192 // Get system font index using indexname
2193 static wxFont GetSystemFont(const wxString& name)
2194 {
2195 if (!name.empty())
2196 {
2197 #define SYSFNT(fnt) \
2198 if (name == wxT(#fnt)) return wxSystemSettings::GetFont(fnt);
2199 SYSFNT(wxSYS_OEM_FIXED_FONT)
2200 SYSFNT(wxSYS_ANSI_FIXED_FONT)
2201 SYSFNT(wxSYS_ANSI_VAR_FONT)
2202 SYSFNT(wxSYS_SYSTEM_FONT)
2203 SYSFNT(wxSYS_DEVICE_DEFAULT_FONT)
2204 SYSFNT(wxSYS_SYSTEM_FIXED_FONT)
2205 SYSFNT(wxSYS_DEFAULT_GUI_FONT)
2206 #undef SYSFNT
2207 }
2208
2209 return wxNullFont;
2210 }
2211
2212 wxFont wxXmlResourceHandler::GetFont(const wxString& param, wxWindow* parent)
2213 {
2214 wxXmlNode *font_node = GetParamNode(param);
2215 if (font_node == NULL)
2216 {
2217 ReportError(
2218 wxString::Format("cannot find font node \"%s\"", param));
2219 return wxNullFont;
2220 }
2221
2222 wxXmlNode *oldnode = m_node;
2223 m_node = font_node;
2224
2225 // font attributes:
2226
2227 // size
2228 int isize = -1;
2229 bool hasSize = HasParam(wxT("size"));
2230 if (hasSize)
2231 isize = GetLong(wxT("size"), -1);
2232
2233 // style
2234 int istyle = wxNORMAL;
2235 bool hasStyle = HasParam(wxT("style"));
2236 if (hasStyle)
2237 {
2238 wxString style = GetParamValue(wxT("style"));
2239 if (style == wxT("italic"))
2240 istyle = wxITALIC;
2241 else if (style == wxT("slant"))
2242 istyle = wxSLANT;
2243 }
2244
2245 // weight
2246 int iweight = wxNORMAL;
2247 bool hasWeight = HasParam(wxT("weight"));
2248 if (hasWeight)
2249 {
2250 wxString weight = GetParamValue(wxT("weight"));
2251 if (weight == wxT("bold"))
2252 iweight = wxBOLD;
2253 else if (weight == wxT("light"))
2254 iweight = wxLIGHT;
2255 }
2256
2257 // underline
2258 bool hasUnderlined = HasParam(wxT("underlined"));
2259 bool underlined = hasUnderlined ? GetBool(wxT("underlined"), false) : false;
2260
2261 // family and facename
2262 int ifamily = wxDEFAULT;
2263 bool hasFamily = HasParam(wxT("family"));
2264 if (hasFamily)
2265 {
2266 wxString family = GetParamValue(wxT("family"));
2267 if (family == wxT("decorative")) ifamily = wxDECORATIVE;
2268 else if (family == wxT("roman")) ifamily = wxROMAN;
2269 else if (family == wxT("script")) ifamily = wxSCRIPT;
2270 else if (family == wxT("swiss")) ifamily = wxSWISS;
2271 else if (family == wxT("modern")) ifamily = wxMODERN;
2272 else if (family == wxT("teletype")) ifamily = wxTELETYPE;
2273 }
2274
2275
2276 wxString facename;
2277 bool hasFacename = HasParam(wxT("face"));
2278 if (hasFacename)
2279 {
2280 wxString faces = GetParamValue(wxT("face"));
2281 wxStringTokenizer tk(faces, wxT(","));
2282 #if wxUSE_FONTENUM
2283 wxArrayString facenames(wxFontEnumerator::GetFacenames());
2284 while (tk.HasMoreTokens())
2285 {
2286 int index = facenames.Index(tk.GetNextToken(), false);
2287 if (index != wxNOT_FOUND)
2288 {
2289 facename = facenames[index];
2290 break;
2291 }
2292 }
2293 #else // !wxUSE_FONTENUM
2294 // just use the first face name if we can't check its availability:
2295 if (tk.HasMoreTokens())
2296 facename = tk.GetNextToken();
2297 #endif // wxUSE_FONTENUM/!wxUSE_FONTENUM
2298 }
2299
2300 // encoding
2301 wxFontEncoding enc = wxFONTENCODING_DEFAULT;
2302 bool hasEncoding = HasParam(wxT("encoding"));
2303 #if wxUSE_FONTMAP
2304 if (hasEncoding)
2305 {
2306 wxString encoding = GetParamValue(wxT("encoding"));
2307 wxFontMapper mapper;
2308 if (!encoding.empty())
2309 enc = mapper.CharsetToEncoding(encoding);
2310 if (enc == wxFONTENCODING_SYSTEM)
2311 enc = wxFONTENCODING_DEFAULT;
2312 }
2313 #endif // wxUSE_FONTMAP
2314
2315 wxFont font;
2316
2317 // is this font based on a system font?
2318 if (HasParam(wxT("sysfont")))
2319 {
2320 font = GetSystemFont(GetParamValue(wxT("sysfont")));
2321 }
2322 // or should the font of the widget be used?
2323 else if (GetBool(wxT("inherit"), false))
2324 {
2325 if (parent)
2326 font = parent->GetFont();
2327 else
2328 ReportError("no parent window specified to derive the font from");
2329 }
2330
2331 if (font.IsOk())
2332 {
2333 if (hasSize && isize != -1)
2334 font.SetPointSize(isize);
2335 else if (HasParam(wxT("relativesize")))
2336 font.SetPointSize(int(font.GetPointSize() *
2337 GetFloat(wxT("relativesize"))));
2338
2339 if (hasStyle)
2340 font.SetStyle(istyle);
2341 if (hasWeight)
2342 font.SetWeight(iweight);
2343 if (hasUnderlined)
2344 font.SetUnderlined(underlined);
2345 if (hasFamily)
2346 font.SetFamily(ifamily);
2347 if (hasFacename)
2348 font.SetFaceName(facename);
2349 if (hasEncoding)
2350 font.SetDefaultEncoding(enc);
2351 }
2352 else // not based on system font
2353 {
2354 font = wxFont(isize == -1 ? wxNORMAL_FONT->GetPointSize() : isize,
2355 ifamily, istyle, iweight,
2356 underlined, facename, enc);
2357 }
2358
2359 m_node = oldnode;
2360 return font;
2361 }
2362
2363
2364 void wxXmlResourceHandler::SetupWindow(wxWindow *wnd)
2365 {
2366 //FIXME : add cursor
2367
2368 if (HasParam(wxT("exstyle")))
2369 // Have to OR it with existing style, since
2370 // some implementations (e.g. wxGTK) use the extra style
2371 // during creation
2372 wnd->SetExtraStyle(wnd->GetExtraStyle() | GetStyle(wxT("exstyle")));
2373 if (HasParam(wxT("bg")))
2374 wnd->SetBackgroundColour(GetColour(wxT("bg")));
2375 if (HasParam(wxT("ownbg")))
2376 wnd->SetOwnBackgroundColour(GetColour(wxT("ownbg")));
2377 if (HasParam(wxT("fg")))
2378 wnd->SetForegroundColour(GetColour(wxT("fg")));
2379 if (HasParam(wxT("ownfg")))
2380 wnd->SetOwnForegroundColour(GetColour(wxT("ownfg")));
2381 if (GetBool(wxT("enabled"), 1) == 0)
2382 wnd->Enable(false);
2383 if (GetBool(wxT("focused"), 0) == 1)
2384 wnd->SetFocus();
2385 if (GetBool(wxT("hidden"), 0) == 1)
2386 wnd->Show(false);
2387 #if wxUSE_TOOLTIPS
2388 if (HasParam(wxT("tooltip")))
2389 wnd->SetToolTip(GetText(wxT("tooltip")));
2390 #endif
2391 if (HasParam(wxT("font")))
2392 wnd->SetFont(GetFont(wxT("font"), wnd));
2393 if (HasParam(wxT("ownfont")))
2394 wnd->SetOwnFont(GetFont(wxT("ownfont"), wnd));
2395 if (HasParam(wxT("help")))
2396 wnd->SetHelpText(GetText(wxT("help")));
2397 }
2398
2399
2400 void wxXmlResourceHandler::CreateChildren(wxObject *parent, bool this_hnd_only)
2401 {
2402 for ( wxXmlNode *n = m_node->GetChildren(); n; n = n->GetNext() )
2403 {
2404 if ( IsObjectNode(n) )
2405 {
2406 m_resource->DoCreateResFromNode(*n, parent, NULL,
2407 this_hnd_only ? this : NULL);
2408 }
2409 }
2410 }
2411
2412
2413 void wxXmlResourceHandler::CreateChildrenPrivately(wxObject *parent, wxXmlNode *rootnode)
2414 {
2415 wxXmlNode *root;
2416 if (rootnode == NULL) root = m_node; else root = rootnode;
2417 wxXmlNode *n = root->GetChildren();
2418
2419 while (n)
2420 {
2421 if (n->GetType() == wxXML_ELEMENT_NODE && CanHandle(n))
2422 {
2423 CreateResource(n, parent, NULL);
2424 }
2425 n = n->GetNext();
2426 }
2427 }
2428
2429
2430 //-----------------------------------------------------------------------------
2431 // errors reporting
2432 //-----------------------------------------------------------------------------
2433
2434 void wxXmlResourceHandler::ReportError(const wxString& message)
2435 {
2436 m_resource->ReportError(m_node, message);
2437 }
2438
2439 void wxXmlResourceHandler::ReportError(wxXmlNode *context,
2440 const wxString& message)
2441 {
2442 m_resource->ReportError(context ? context : m_node, message);
2443 }
2444
2445 void wxXmlResourceHandler::ReportParamError(const wxString& param,
2446 const wxString& message)
2447 {
2448 m_resource->ReportError(GetParamNode(param), message);
2449 }
2450
2451 void wxXmlResource::ReportError(const wxXmlNode *context, const wxString& message)
2452 {
2453 if ( !context )
2454 {
2455 DoReportError("", NULL, message);
2456 return;
2457 }
2458
2459 // We need to find out the file that 'context' is part of. Performance of
2460 // this code is not critical, so we simply find the root XML node and
2461 // compare it with all loaded XRC files.
2462 const wxString filename = GetFileNameFromNode(context, Data());
2463
2464 DoReportError(filename, context, message);
2465 }
2466
2467 void wxXmlResource::DoReportError(const wxString& xrcFile, const wxXmlNode *position,
2468 const wxString& message)
2469 {
2470 const int line = position ? position->GetLineNumber() : -1;
2471
2472 wxString loc;
2473 if ( !xrcFile.empty() )
2474 loc = xrcFile + ':';
2475 if ( line != -1 )
2476 loc += wxString::Format("%d:", line);
2477 if ( !loc.empty() )
2478 loc += ' ';
2479
2480 wxLogError("XRC error: %s%s", loc, message);
2481 }
2482
2483
2484 //-----------------------------------------------------------------------------
2485 // XRCID implementation
2486 //-----------------------------------------------------------------------------
2487
2488 #define XRCID_TABLE_SIZE 1024
2489
2490
2491 struct XRCID_record
2492 {
2493 /* Hold the id so that once an id is allocated for a name, it
2494 does not get created again by NewControlId at least
2495 until we are done with it */
2496 wxWindowIDRef id;
2497 char *key;
2498 XRCID_record *next;
2499 };
2500
2501 static XRCID_record *XRCID_Records[XRCID_TABLE_SIZE] = {NULL};
2502
2503 // Extremely simplistic hash function which probably ought to be replaced with
2504 // wxStringHash::stringHash().
2505 static inline unsigned XRCIdHash(const char *str_id)
2506 {
2507 unsigned index = 0;
2508
2509 for (const char *c = str_id; *c != '\0'; c++) index += (unsigned int)*c;
2510 index %= XRCID_TABLE_SIZE;
2511
2512 return index;
2513 }
2514
2515 static void XRCID_Assign(const wxString& str_id, int value)
2516 {
2517 const wxCharBuffer buf_id(str_id.mb_str());
2518 const unsigned index = XRCIdHash(buf_id);
2519
2520
2521 XRCID_record *oldrec = NULL;
2522 for (XRCID_record *rec = XRCID_Records[index]; rec; rec = rec->next)
2523 {
2524 if (wxStrcmp(rec->key, buf_id) == 0)
2525 {
2526 rec->id = value;
2527 return;
2528 }
2529 oldrec = rec;
2530 }
2531
2532 XRCID_record **rec_var = (oldrec == NULL) ?
2533 &XRCID_Records[index] : &oldrec->next;
2534 *rec_var = new XRCID_record;
2535 (*rec_var)->key = wxStrdup(str_id);
2536 (*rec_var)->id = value;
2537 (*rec_var)->next = NULL;
2538 }
2539
2540 static int XRCID_Lookup(const char *str_id, int value_if_not_found = wxID_NONE)
2541 {
2542 const unsigned index = XRCIdHash(str_id);
2543
2544
2545 XRCID_record *oldrec = NULL;
2546 for (XRCID_record *rec = XRCID_Records[index]; rec; rec = rec->next)
2547 {
2548 if (wxStrcmp(rec->key, str_id) == 0)
2549 {
2550 return rec->id;
2551 }
2552 oldrec = rec;
2553 }
2554
2555 XRCID_record **rec_var = (oldrec == NULL) ?
2556 &XRCID_Records[index] : &oldrec->next;
2557 *rec_var = new XRCID_record;
2558 (*rec_var)->key = wxStrdup(str_id);
2559 (*rec_var)->next = NULL;
2560
2561 char *end;
2562 if (value_if_not_found != wxID_NONE)
2563 (*rec_var)->id = value_if_not_found;
2564 else
2565 {
2566 int asint = wxStrtol(str_id, &end, 10);
2567 if (*str_id && *end == 0)
2568 {
2569 // if str_id was integer, keep it verbosely:
2570 (*rec_var)->id = asint;
2571 }
2572 else
2573 {
2574 (*rec_var)->id = wxWindowBase::NewControlId();
2575 }
2576 }
2577
2578 return (*rec_var)->id;
2579 }
2580
2581 namespace
2582 {
2583
2584 // flag indicating whether standard XRC ids were already initialized
2585 static bool gs_stdIDsAdded = false;
2586
2587 void AddStdXRCID_Records()
2588 {
2589 #define stdID(id) XRCID_Lookup(#id, id)
2590 stdID(-1);
2591
2592 stdID(wxID_ANY);
2593 stdID(wxID_SEPARATOR);
2594
2595 stdID(wxID_OPEN);
2596 stdID(wxID_CLOSE);
2597 stdID(wxID_NEW);
2598 stdID(wxID_SAVE);
2599 stdID(wxID_SAVEAS);
2600 stdID(wxID_REVERT);
2601 stdID(wxID_EXIT);
2602 stdID(wxID_UNDO);
2603 stdID(wxID_REDO);
2604 stdID(wxID_HELP);
2605 stdID(wxID_PRINT);
2606 stdID(wxID_PRINT_SETUP);
2607 stdID(wxID_PAGE_SETUP);
2608 stdID(wxID_PREVIEW);
2609 stdID(wxID_ABOUT);
2610 stdID(wxID_HELP_CONTENTS);
2611 stdID(wxID_HELP_INDEX),
2612 stdID(wxID_HELP_SEARCH),
2613 stdID(wxID_HELP_COMMANDS);
2614 stdID(wxID_HELP_PROCEDURES);
2615 stdID(wxID_HELP_CONTEXT);
2616 stdID(wxID_CLOSE_ALL);
2617 stdID(wxID_PREFERENCES);
2618
2619 stdID(wxID_EDIT);
2620 stdID(wxID_CUT);
2621 stdID(wxID_COPY);
2622 stdID(wxID_PASTE);
2623 stdID(wxID_CLEAR);
2624 stdID(wxID_FIND);
2625 stdID(wxID_DUPLICATE);
2626 stdID(wxID_SELECTALL);
2627 stdID(wxID_DELETE);
2628 stdID(wxID_REPLACE);
2629 stdID(wxID_REPLACE_ALL);
2630 stdID(wxID_PROPERTIES);
2631
2632 stdID(wxID_VIEW_DETAILS);
2633 stdID(wxID_VIEW_LARGEICONS);
2634 stdID(wxID_VIEW_SMALLICONS);
2635 stdID(wxID_VIEW_LIST);
2636 stdID(wxID_VIEW_SORTDATE);
2637 stdID(wxID_VIEW_SORTNAME);
2638 stdID(wxID_VIEW_SORTSIZE);
2639 stdID(wxID_VIEW_SORTTYPE);
2640
2641
2642 stdID(wxID_FILE1);
2643 stdID(wxID_FILE2);
2644 stdID(wxID_FILE3);
2645 stdID(wxID_FILE4);
2646 stdID(wxID_FILE5);
2647 stdID(wxID_FILE6);
2648 stdID(wxID_FILE7);
2649 stdID(wxID_FILE8);
2650 stdID(wxID_FILE9);
2651
2652
2653 stdID(wxID_OK);
2654 stdID(wxID_CANCEL);
2655 stdID(wxID_APPLY);
2656 stdID(wxID_YES);
2657 stdID(wxID_NO);
2658 stdID(wxID_STATIC);
2659 stdID(wxID_FORWARD);
2660 stdID(wxID_BACKWARD);
2661 stdID(wxID_DEFAULT);
2662 stdID(wxID_MORE);
2663 stdID(wxID_SETUP);
2664 stdID(wxID_RESET);
2665 stdID(wxID_CONTEXT_HELP);
2666 stdID(wxID_YESTOALL);
2667 stdID(wxID_NOTOALL);
2668 stdID(wxID_ABORT);
2669 stdID(wxID_RETRY);
2670 stdID(wxID_IGNORE);
2671 stdID(wxID_ADD);
2672 stdID(wxID_REMOVE);
2673
2674 stdID(wxID_UP);
2675 stdID(wxID_DOWN);
2676 stdID(wxID_HOME);
2677 stdID(wxID_REFRESH);
2678 stdID(wxID_STOP);
2679 stdID(wxID_INDEX);
2680
2681 stdID(wxID_BOLD);
2682 stdID(wxID_ITALIC);
2683 stdID(wxID_JUSTIFY_CENTER);
2684 stdID(wxID_JUSTIFY_FILL);
2685 stdID(wxID_JUSTIFY_RIGHT);
2686 stdID(wxID_JUSTIFY_LEFT);
2687 stdID(wxID_UNDERLINE);
2688 stdID(wxID_INDENT);
2689 stdID(wxID_UNINDENT);
2690 stdID(wxID_ZOOM_100);
2691 stdID(wxID_ZOOM_FIT);
2692 stdID(wxID_ZOOM_IN);
2693 stdID(wxID_ZOOM_OUT);
2694 stdID(wxID_UNDELETE);
2695 stdID(wxID_REVERT_TO_SAVED);
2696 stdID(wxID_CDROM);
2697 stdID(wxID_CONVERT);
2698 stdID(wxID_EXECUTE);
2699 stdID(wxID_FLOPPY);
2700 stdID(wxID_HARDDISK);
2701 stdID(wxID_BOTTOM);
2702 stdID(wxID_FIRST);
2703 stdID(wxID_LAST);
2704 stdID(wxID_TOP);
2705 stdID(wxID_INFO);
2706 stdID(wxID_JUMP_TO);
2707 stdID(wxID_NETWORK);
2708 stdID(wxID_SELECT_COLOR);
2709 stdID(wxID_SELECT_FONT);
2710 stdID(wxID_SORT_ASCENDING);
2711 stdID(wxID_SORT_DESCENDING);
2712 stdID(wxID_SPELL_CHECK);
2713 stdID(wxID_STRIKETHROUGH);
2714
2715
2716 stdID(wxID_SYSTEM_MENU);
2717 stdID(wxID_CLOSE_FRAME);
2718 stdID(wxID_MOVE_FRAME);
2719 stdID(wxID_RESIZE_FRAME);
2720 stdID(wxID_MAXIMIZE_FRAME);
2721 stdID(wxID_ICONIZE_FRAME);
2722 stdID(wxID_RESTORE_FRAME);
2723
2724
2725
2726 stdID(wxID_MDI_WINDOW_CASCADE);
2727 stdID(wxID_MDI_WINDOW_TILE_HORZ);
2728 stdID(wxID_MDI_WINDOW_TILE_VERT);
2729 stdID(wxID_MDI_WINDOW_ARRANGE_ICONS);
2730 stdID(wxID_MDI_WINDOW_PREV);
2731 stdID(wxID_MDI_WINDOW_NEXT);
2732 #undef stdID
2733 }
2734
2735 } // anonymous namespace
2736
2737
2738 /*static*/
2739 int wxXmlResource::DoGetXRCID(const char *str_id, int value_if_not_found)
2740 {
2741 if ( !gs_stdIDsAdded )
2742 {
2743 gs_stdIDsAdded = true;
2744 AddStdXRCID_Records();
2745 }
2746
2747 return XRCID_Lookup(str_id, value_if_not_found);
2748 }
2749
2750 /* static */
2751 wxString wxXmlResource::FindXRCIDById(int numId)
2752 {
2753 for ( int i = 0; i < XRCID_TABLE_SIZE; i++ )
2754 {
2755 for ( XRCID_record *rec = XRCID_Records[i]; rec; rec = rec->next )
2756 {
2757 if ( rec->id == numId )
2758 return wxString(rec->key);
2759 }
2760 }
2761
2762 return wxString();
2763 }
2764
2765 static void CleanXRCID_Record(XRCID_record *rec)
2766 {
2767 if (rec)
2768 {
2769 CleanXRCID_Record(rec->next);
2770
2771 free(rec->key);
2772 delete rec;
2773 }
2774 }
2775
2776 static void CleanXRCID_Records()
2777 {
2778 for (int i = 0; i < XRCID_TABLE_SIZE; i++)
2779 {
2780 CleanXRCID_Record(XRCID_Records[i]);
2781 XRCID_Records[i] = NULL;
2782 }
2783
2784 gs_stdIDsAdded = false;
2785 }
2786
2787
2788 //-----------------------------------------------------------------------------
2789 // module and globals
2790 //-----------------------------------------------------------------------------
2791
2792 // normally we would do the cleanup from wxXmlResourceModule::OnExit() but it
2793 // can happen that some XRC records have been created because of the use of
2794 // XRCID() in event tables, which happens during static objects initialization,
2795 // but then the application initialization failed and so the wx modules were
2796 // neither initialized nor cleaned up -- this static object does the cleanup in
2797 // this case
2798 static struct wxXRCStaticCleanup
2799 {
2800 ~wxXRCStaticCleanup() { CleanXRCID_Records(); }
2801 } s_staticCleanup;
2802
2803 class wxXmlResourceModule: public wxModule
2804 {
2805 DECLARE_DYNAMIC_CLASS(wxXmlResourceModule)
2806 public:
2807 wxXmlResourceModule() {}
2808 bool OnInit()
2809 {
2810 wxXmlResource::AddSubclassFactory(new wxXmlSubclassFactoryCXX);
2811 return true;
2812 }
2813 void OnExit()
2814 {
2815 delete wxXmlResource::Set(NULL);
2816 delete wxIdRangeManager::Set(NULL);
2817 if(wxXmlResource::ms_subclassFactories)
2818 {
2819 for ( wxXmlSubclassFactories::iterator i = wxXmlResource::ms_subclassFactories->begin();
2820 i != wxXmlResource::ms_subclassFactories->end(); ++i )
2821 {
2822 delete *i;
2823 }
2824 wxDELETE(wxXmlResource::ms_subclassFactories);
2825 }
2826 CleanXRCID_Records();
2827 }
2828 };
2829
2830 IMPLEMENT_DYNAMIC_CLASS(wxXmlResourceModule, wxModule)
2831
2832
2833 // When wxXml is loaded dynamically after the application is already running
2834 // then the built-in module system won't pick this one up. Add it manually.
2835 void wxXmlInitResourceModule()
2836 {
2837 wxModule* module = new wxXmlResourceModule;
2838 module->Init();
2839 wxModule::RegisterModule(module);
2840 }
2841
2842 #endif // wxUSE_XRC