added wxXmlResource::LoadFile() to avoid URL-vs-filename ambiguity in Load()
[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
48 #include "wx/xml/xml.h"
49
50
51 class wxXmlResourceDataRecord
52 {
53 public:
54 wxXmlResourceDataRecord() : Doc(NULL) {
55 #if wxUSE_DATETIME
56 Time = wxDateTime::Now();
57 #endif
58 }
59 ~wxXmlResourceDataRecord() {delete Doc;}
60
61 wxString File;
62 wxXmlDocument *Doc;
63 #if wxUSE_DATETIME
64 wxDateTime Time;
65 #endif
66 };
67
68 class wxXmlResourceDataRecords : public wxVector<wxXmlResourceDataRecord*>
69 {
70 // this is a class so that it can be forward-declared
71 };
72
73 namespace
74 {
75
76 // helper used by DoFindResource() and elsewhere: returns true if this is an
77 // object or object_ref node
78 //
79 // node must be non-NULL
80 inline bool IsObjectNode(wxXmlNode *node)
81 {
82 return node->GetType() == wxXML_ELEMENT_NODE &&
83 (node->GetName() == wxS("object") ||
84 node->GetName() == wxS("object_ref"));
85 }
86
87 } // anonymous namespace
88
89
90 wxXmlResource *wxXmlResource::ms_instance = NULL;
91
92 /*static*/ wxXmlResource *wxXmlResource::Get()
93 {
94 if ( !ms_instance )
95 ms_instance = new wxXmlResource;
96 return ms_instance;
97 }
98
99 /*static*/ wxXmlResource *wxXmlResource::Set(wxXmlResource *res)
100 {
101 wxXmlResource *old = ms_instance;
102 ms_instance = res;
103 return old;
104 }
105
106 wxXmlResource::wxXmlResource(int flags, const wxString& domain)
107 {
108 m_flags = flags;
109 m_version = -1;
110 m_data = new wxXmlResourceDataRecords;
111 SetDomain(domain);
112 }
113
114 wxXmlResource::wxXmlResource(const wxString& filemask, int flags, const wxString& domain)
115 {
116 m_flags = flags;
117 m_version = -1;
118 m_data = new wxXmlResourceDataRecords;
119 SetDomain(domain);
120 Load(filemask);
121 }
122
123 wxXmlResource::~wxXmlResource()
124 {
125 ClearHandlers();
126
127 for ( wxXmlResourceDataRecords::iterator i = m_data->begin();
128 i != m_data->end(); ++i )
129 {
130 delete *i;
131 }
132 delete m_data;
133 }
134
135 void wxXmlResource::SetDomain(const wxString& domain)
136 {
137 m_domain = domain;
138 }
139
140
141 /* static */
142 wxString wxXmlResource::ConvertFileNameToURL(const wxString& filename)
143 {
144 wxString fnd(filename);
145
146 // NB: as Load() and Unload() accept both filenames and URLs (should
147 // probably be changed to filenames only, but embedded resources
148 // currently rely on its ability to handle URLs - FIXME) we need to
149 // determine whether found name is filename and not URL and this is the
150 // fastest/simplest way to do it
151 if (wxFileName::FileExists(fnd))
152 {
153 // Make the name absolute filename, because the app may
154 // change working directory later:
155 wxFileName fn(fnd);
156 if (fn.IsRelative())
157 {
158 fn.MakeAbsolute();
159 fnd = fn.GetFullPath();
160 }
161 #if wxUSE_FILESYSTEM
162 fnd = wxFileSystem::FileNameToURL(fnd);
163 #endif
164 }
165
166 return fnd;
167 }
168
169 #if wxUSE_FILESYSTEM
170
171 /* static */
172 bool wxXmlResource::IsArchive(const wxString& filename)
173 {
174 const wxString fnd = filename.Lower();
175
176 return fnd.Matches(wxT("*.zip")) || fnd.Matches(wxT("*.xrs"));
177 }
178
179 #endif // wxUSE_FILESYSTEM
180
181 bool wxXmlResource::LoadFile(const wxFileName& file)
182 {
183 return Load(wxFileSystem::FileNameToURL(file));
184 }
185
186 bool wxXmlResource::Load(const wxString& filemask_)
187 {
188 wxString filemask = ConvertFileNameToURL(filemask_);
189
190 #if wxUSE_FILESYSTEM
191 wxFileSystem fsys;
192 # define wxXmlFindFirst fsys.FindFirst(filemask, wxFILE)
193 # define wxXmlFindNext fsys.FindNext()
194 #else
195 # define wxXmlFindFirst wxFindFirstFile(filemask, wxFILE)
196 # define wxXmlFindNext wxFindNextFile()
197 #endif
198 wxString fnd = wxXmlFindFirst;
199 if ( fnd.empty() )
200 {
201 wxLogError(_("Cannot load resources from '%s'."), filemask);
202 return false;
203 }
204
205 while (!fnd.empty())
206 {
207 #if wxUSE_FILESYSTEM
208 if ( IsArchive(fnd) )
209 {
210 if ( !Load(fnd + wxT("#zip:*.xrc")) )
211 return false;
212 }
213 else // a single resource URL
214 #endif // wxUSE_FILESYSTEM
215 {
216 wxXmlResourceDataRecord *drec = new wxXmlResourceDataRecord;
217 drec->File = fnd;
218 Data().push_back(drec);
219 }
220
221 fnd = wxXmlFindNext;
222 }
223 # undef wxXmlFindFirst
224 # undef wxXmlFindNext
225
226 return UpdateResources();
227 }
228
229 bool wxXmlResource::Unload(const wxString& filename)
230 {
231 wxASSERT_MSG( !wxIsWild(filename),
232 _T("wildcards not supported by wxXmlResource::Unload()") );
233
234 wxString fnd = ConvertFileNameToURL(filename);
235 #if wxUSE_FILESYSTEM
236 const bool isArchive = IsArchive(fnd);
237 if ( isArchive )
238 fnd += _T("#zip:");
239 #endif // wxUSE_FILESYSTEM
240
241 bool unloaded = false;
242 for ( wxXmlResourceDataRecords::iterator i = Data().begin();
243 i != Data().end(); ++i )
244 {
245 #if wxUSE_FILESYSTEM
246 if ( isArchive )
247 {
248 if ( (*i)->File.StartsWith(fnd) )
249 unloaded = true;
250 // don't break from the loop, we can have other matching files
251 }
252 else // a single resource URL
253 #endif // wxUSE_FILESYSTEM
254 {
255 if ( (*i)->File == fnd )
256 {
257 delete *i;
258 Data().erase(i);
259 unloaded = true;
260
261 // no sense in continuing, there is only one file with this URL
262 break;
263 }
264 }
265 }
266
267 return unloaded;
268 }
269
270
271 IMPLEMENT_ABSTRACT_CLASS(wxXmlResourceHandler, wxObject)
272
273 void wxXmlResource::AddHandler(wxXmlResourceHandler *handler)
274 {
275 m_handlers.push_back(handler);
276 handler->SetParentResource(this);
277 }
278
279 void wxXmlResource::InsertHandler(wxXmlResourceHandler *handler)
280 {
281 m_handlers.insert(m_handlers.begin(), handler);
282 handler->SetParentResource(this);
283 }
284
285
286
287 void wxXmlResource::ClearHandlers()
288 {
289 for ( wxVector<wxXmlResourceHandler*>::iterator i = m_handlers.begin();
290 i != m_handlers.end(); ++i )
291 delete *i;
292 m_handlers.clear();
293 }
294
295
296 wxMenu *wxXmlResource::LoadMenu(const wxString& name)
297 {
298 return (wxMenu*)CreateResFromNode(FindResource(name, wxT("wxMenu")), NULL, NULL);
299 }
300
301
302
303 wxMenuBar *wxXmlResource::LoadMenuBar(wxWindow *parent, const wxString& name)
304 {
305 return (wxMenuBar*)CreateResFromNode(FindResource(name, wxT("wxMenuBar")), parent, NULL);
306 }
307
308
309
310 #if wxUSE_TOOLBAR
311 wxToolBar *wxXmlResource::LoadToolBar(wxWindow *parent, const wxString& name)
312 {
313 return (wxToolBar*)CreateResFromNode(FindResource(name, wxT("wxToolBar")), parent, NULL);
314 }
315 #endif
316
317
318 wxDialog *wxXmlResource::LoadDialog(wxWindow *parent, const wxString& name)
319 {
320 return (wxDialog*)CreateResFromNode(FindResource(name, wxT("wxDialog")), parent, NULL);
321 }
322
323 bool wxXmlResource::LoadDialog(wxDialog *dlg, wxWindow *parent, const wxString& name)
324 {
325 return CreateResFromNode(FindResource(name, wxT("wxDialog")), parent, dlg) != NULL;
326 }
327
328
329
330 wxPanel *wxXmlResource::LoadPanel(wxWindow *parent, const wxString& name)
331 {
332 return (wxPanel*)CreateResFromNode(FindResource(name, wxT("wxPanel")), parent, NULL);
333 }
334
335 bool wxXmlResource::LoadPanel(wxPanel *panel, wxWindow *parent, const wxString& name)
336 {
337 return CreateResFromNode(FindResource(name, wxT("wxPanel")), parent, panel) != NULL;
338 }
339
340 wxFrame *wxXmlResource::LoadFrame(wxWindow* parent, const wxString& name)
341 {
342 return (wxFrame*)CreateResFromNode(FindResource(name, wxT("wxFrame")), parent, NULL);
343 }
344
345 bool wxXmlResource::LoadFrame(wxFrame* frame, wxWindow *parent, const wxString& name)
346 {
347 return CreateResFromNode(FindResource(name, wxT("wxFrame")), parent, frame) != NULL;
348 }
349
350 wxBitmap wxXmlResource::LoadBitmap(const wxString& name)
351 {
352 wxBitmap *bmp = (wxBitmap*)CreateResFromNode(
353 FindResource(name, wxT("wxBitmap")), NULL, NULL);
354 wxBitmap rt;
355
356 if (bmp) { rt = *bmp; delete bmp; }
357 return rt;
358 }
359
360 wxIcon wxXmlResource::LoadIcon(const wxString& name)
361 {
362 wxIcon *icon = (wxIcon*)CreateResFromNode(
363 FindResource(name, wxT("wxIcon")), NULL, NULL);
364 wxIcon rt;
365
366 if (icon) { rt = *icon; delete icon; }
367 return rt;
368 }
369
370
371 wxObject *wxXmlResource::LoadObject(wxWindow *parent, const wxString& name, const wxString& classname)
372 {
373 return CreateResFromNode(FindResource(name, classname), parent, NULL);
374 }
375
376 bool wxXmlResource::LoadObject(wxObject *instance, wxWindow *parent, const wxString& name, const wxString& classname)
377 {
378 return CreateResFromNode(FindResource(name, classname), parent, instance) != NULL;
379 }
380
381
382 bool wxXmlResource::AttachUnknownControl(const wxString& name,
383 wxWindow *control, wxWindow *parent)
384 {
385 if (parent == NULL)
386 parent = control->GetParent();
387 wxWindow *container = parent->FindWindow(name + wxT("_container"));
388 if (!container)
389 {
390 wxLogError(_("Cannot find container for unknown control '%s'."), name.c_str());
391 return false;
392 }
393 return control->Reparent(container);
394 }
395
396
397 static void ProcessPlatformProperty(wxXmlNode *node)
398 {
399 wxString s;
400 bool isok;
401
402 wxXmlNode *c = node->GetChildren();
403 while (c)
404 {
405 isok = false;
406 if (!c->GetAttribute(wxT("platform"), &s))
407 isok = true;
408 else
409 {
410 wxStringTokenizer tkn(s, wxT(" |"));
411
412 while (tkn.HasMoreTokens())
413 {
414 s = tkn.GetNextToken();
415 #ifdef __WINDOWS__
416 if (s == wxT("win")) isok = true;
417 #endif
418 #if defined(__MAC__) || defined(__APPLE__)
419 if (s == wxT("mac")) isok = true;
420 #elif defined(__UNIX__)
421 if (s == wxT("unix")) isok = true;
422 #endif
423 #ifdef __OS2__
424 if (s == wxT("os2")) isok = true;
425 #endif
426
427 if (isok)
428 break;
429 }
430 }
431
432 if (isok)
433 {
434 ProcessPlatformProperty(c);
435 c = c->GetNext();
436 }
437 else
438 {
439 wxXmlNode *c2 = c->GetNext();
440 node->RemoveChild(c);
441 delete c;
442 c = c2;
443 }
444 }
445 }
446
447
448
449 bool wxXmlResource::UpdateResources()
450 {
451 bool rt = true;
452 bool modif;
453 # if wxUSE_FILESYSTEM
454 wxFSFile *file = NULL;
455 wxUnusedVar(file);
456 wxFileSystem fsys;
457 # endif
458
459 wxString encoding(wxT("UTF-8"));
460 #if !wxUSE_UNICODE && wxUSE_INTL
461 if ( (GetFlags() & wxXRC_USE_LOCALE) == 0 )
462 {
463 // In case we are not using wxLocale to translate strings, convert the
464 // strings GUI's charset. This must not be done when wxXRC_USE_LOCALE
465 // is on, because it could break wxGetTranslation lookup.
466 encoding = wxLocale::GetSystemEncodingName();
467 }
468 #endif
469
470 for ( wxXmlResourceDataRecords::iterator i = Data().begin();
471 i != Data().end(); ++i )
472 {
473 wxXmlResourceDataRecord* const rec = *i;
474
475 modif = (rec->Doc == NULL);
476
477 if (!modif && !(m_flags & wxXRC_NO_RELOADING))
478 {
479 # if wxUSE_FILESYSTEM
480 file = fsys.OpenFile(rec->File);
481 # if wxUSE_DATETIME
482 modif = file && file->GetModificationTime() > rec->Time;
483 # else // wxUSE_DATETIME
484 modif = true;
485 # endif // wxUSE_DATETIME
486 if (!file)
487 {
488 wxLogError(_("Cannot open file '%s'."), rec->File);
489 rt = false;
490 }
491 wxDELETE(file);
492 wxUnusedVar(file);
493 # else // wxUSE_FILESYSTEM
494 # if wxUSE_DATETIME
495 modif = wxDateTime(wxFileModificationTime(rec->File)) > rec->Time;
496 # else // wxUSE_DATETIME
497 modif = true;
498 # endif // wxUSE_DATETIME
499 # endif // wxUSE_FILESYSTEM
500 }
501
502 if (modif)
503 {
504 wxLogTrace(_T("xrc"), _T("opening file '%s'"), rec->File);
505
506 wxInputStream *stream = NULL;
507
508 # if wxUSE_FILESYSTEM
509 file = fsys.OpenFile(rec->File);
510 if (file)
511 stream = file->GetStream();
512 # else
513 stream = new wxFileInputStream(rec->File);
514 # endif
515
516 if (stream)
517 {
518 delete rec->Doc;
519 rec->Doc = new wxXmlDocument;
520 }
521 if (!stream || !stream->IsOk() || !rec->Doc->Load(*stream, encoding))
522 {
523 wxLogError(_("Cannot load resources from file '%s'."),
524 rec->File);
525 wxDELETE(rec->Doc);
526 rt = false;
527 }
528 else if (rec->Doc->GetRoot()->GetName() != wxT("resource"))
529 {
530 wxLogError(_("Invalid XRC resource '%s': doesn't have root node 'resource'."), rec->File);
531 wxDELETE(rec->Doc);
532 rt = false;
533 }
534 else
535 {
536 long version;
537 int v1, v2, v3, v4;
538 wxString verstr = rec->Doc->GetRoot()->GetAttribute(
539 wxT("version"), wxT("0.0.0.0"));
540 if (wxSscanf(verstr.c_str(), wxT("%i.%i.%i.%i"),
541 &v1, &v2, &v3, &v4) == 4)
542 version = v1*256*256*256+v2*256*256+v3*256+v4;
543 else
544 version = 0;
545 if (m_version == -1)
546 m_version = version;
547 if (m_version != version)
548 {
549 wxLogError(_("Resource files must have same version number!"));
550 rt = false;
551 }
552
553 ProcessPlatformProperty(rec->Doc->GetRoot());
554 #if wxUSE_DATETIME
555 #if wxUSE_FILESYSTEM
556 rec->Time = file->GetModificationTime();
557 #else // wxUSE_FILESYSTEM
558 rec->Time = wxDateTime(wxFileModificationTime(rec->File));
559 #endif // wxUSE_FILESYSTEM
560 #endif // wxUSE_DATETIME
561 }
562
563 # if wxUSE_FILESYSTEM
564 wxDELETE(file);
565 wxUnusedVar(file);
566 # else
567 wxDELETE(stream);
568 # endif
569 }
570 }
571
572 return rt;
573 }
574
575 wxXmlNode *wxXmlResource::DoFindResource(wxXmlNode *parent,
576 const wxString& name,
577 const wxString& classname,
578 bool recursive) const
579 {
580 wxXmlNode *node;
581
582 // first search for match at the top-level nodes (as this is
583 // where the resource is most commonly looked for):
584 for (node = parent->GetChildren(); node; node = node->GetNext())
585 {
586 if ( IsObjectNode(node) && node->GetAttribute(wxS("name")) == name )
587 {
588 // empty class name matches everything
589 if ( classname.empty() )
590 return node;
591
592 wxString cls(node->GetAttribute(wxS("class")));
593
594 // object_ref may not have 'class' attribute:
595 if (cls.empty() && node->GetName() == wxS("object_ref"))
596 {
597 wxString refName = node->GetAttribute(wxS("ref"));
598 if (refName.empty())
599 continue;
600
601 const wxXmlNode * const refNode = GetResourceNode(refName);
602 if ( refNode )
603 cls = refNode->GetAttribute(wxS("class"));
604 }
605
606 if ( cls == classname )
607 return node;
608 }
609 }
610
611 // then recurse in child nodes
612 if ( recursive )
613 {
614 for (node = parent->GetChildren(); node; node = node->GetNext())
615 {
616 if ( IsObjectNode(node) )
617 {
618 wxXmlNode* found = DoFindResource(node, name, classname, true);
619 if ( found )
620 return found;
621 }
622 }
623 }
624
625 return NULL;
626 }
627
628 wxXmlNode *wxXmlResource::FindResource(const wxString& name,
629 const wxString& classname,
630 bool recursive)
631 {
632 wxString path;
633 wxXmlNode * const
634 node = GetResourceNodeAndLocation(name, classname, recursive, &path);
635
636 if ( !node )
637 {
638 wxLogError(_("XRC resource '%s' (class '%s') not found!"),
639 name, classname);
640 }
641 #if wxUSE_FILESYSTEM
642 else // node was found
643 {
644 // ensure that relative paths work correctly when loading this node
645 // (which should happen as soon as we return as FindResource() result
646 // is always passed to CreateResFromNode())
647 m_curFileSystem.ChangePathTo(path);
648 }
649 #endif // wxUSE_FILESYSTEM
650
651 return node;
652 }
653
654 wxXmlNode *
655 wxXmlResource::GetResourceNodeAndLocation(const wxString& name,
656 const wxString& classname,
657 bool recursive,
658 wxString *path) const
659 {
660 // ensure everything is up-to-date: this is needed to support on-remand
661 // reloading of XRC files
662 const_cast<wxXmlResource *>(this)->UpdateResources();
663
664 for ( wxXmlResourceDataRecords::const_iterator f = Data().begin();
665 f != Data().end(); ++f )
666 {
667 wxXmlResourceDataRecord *const rec = *f;
668 wxXmlDocument * const doc = rec->Doc;
669 if ( !doc || !doc->GetRoot() )
670 continue;
671
672 wxXmlNode * const
673 found = DoFindResource(doc->GetRoot(), name, classname, recursive);
674 if ( found )
675 {
676 if ( path )
677 *path = rec->File;
678
679 return found;
680 }
681 }
682
683 return NULL;
684 }
685
686 static void MergeNodes(wxXmlNode& dest, wxXmlNode& with)
687 {
688 // Merge attributes:
689 for ( wxXmlAttribute *attr = with.GetAttributes();
690 attr; attr = attr->GetNext() )
691 {
692 wxXmlAttribute *dattr;
693 for (dattr = dest.GetAttributes(); dattr; dattr = dattr->GetNext())
694 {
695
696 if ( dattr->GetName() == attr->GetName() )
697 {
698 dattr->SetValue(attr->GetValue());
699 break;
700 }
701 }
702
703 if ( !dattr )
704 dest.AddAttribute(attr->GetName(), attr->GetValue());
705 }
706
707 // Merge child nodes:
708 for (wxXmlNode* node = with.GetChildren(); node; node = node->GetNext())
709 {
710 wxString name = node->GetAttribute(wxT("name"), wxEmptyString);
711 wxXmlNode *dnode;
712
713 for (dnode = dest.GetChildren(); dnode; dnode = dnode->GetNext() )
714 {
715 if ( dnode->GetName() == node->GetName() &&
716 dnode->GetAttribute(wxT("name"), wxEmptyString) == name &&
717 dnode->GetType() == node->GetType() )
718 {
719 MergeNodes(*dnode, *node);
720 break;
721 }
722 }
723
724 if ( !dnode )
725 {
726 static const wxChar *AT_END = wxT("end");
727 wxString insert_pos = node->GetAttribute(wxT("insert_at"), AT_END);
728 if ( insert_pos == AT_END )
729 {
730 dest.AddChild(new wxXmlNode(*node));
731 }
732 else if ( insert_pos == wxT("begin") )
733 {
734 dest.InsertChild(new wxXmlNode(*node), dest.GetChildren());
735 }
736 }
737 }
738
739 if ( dest.GetType() == wxXML_TEXT_NODE && with.GetContent().length() )
740 dest.SetContent(with.GetContent());
741 }
742
743 wxObject *wxXmlResource::CreateResFromNode(wxXmlNode *node, wxObject *parent,
744 wxObject *instance,
745 wxXmlResourceHandler *handlerToUse)
746 {
747 if (node == NULL) return NULL;
748
749 // handling of referenced resource
750 if ( node->GetName() == wxT("object_ref") )
751 {
752 wxString refName = node->GetAttribute(wxT("ref"), wxEmptyString);
753 wxXmlNode* refNode = FindResource(refName, wxEmptyString, true);
754
755 if ( !refNode )
756 {
757 wxLogError(_("Referenced object node with ref=\"%s\" not found!"),
758 refName.c_str());
759 return NULL;
760 }
761
762 wxXmlNode copy(*refNode);
763 MergeNodes(copy, *node);
764
765 return CreateResFromNode(&copy, parent, instance);
766 }
767
768 if (handlerToUse)
769 {
770 if (handlerToUse->CanHandle(node))
771 {
772 return handlerToUse->CreateResource(node, parent, instance);
773 }
774 }
775 else if (node->GetName() == wxT("object"))
776 {
777 for ( wxVector<wxXmlResourceHandler*>::iterator h = m_handlers.begin();
778 h != m_handlers.end(); ++h )
779 {
780 wxXmlResourceHandler *handler = *h;
781 if (handler->CanHandle(node))
782 return handler->CreateResource(node, parent, instance);
783 }
784 }
785
786 wxLogError(_("No handler found for XML node '%s', class '%s'!"),
787 node->GetName().c_str(),
788 node->GetAttribute(wxT("class"), wxEmptyString).c_str());
789 return NULL;
790 }
791
792
793 class wxXmlSubclassFactories : public wxVector<wxXmlSubclassFactory*>
794 {
795 // this is a class so that it can be forward-declared
796 };
797
798 wxXmlSubclassFactories *wxXmlResource::ms_subclassFactories = NULL;
799
800 /*static*/ void wxXmlResource::AddSubclassFactory(wxXmlSubclassFactory *factory)
801 {
802 if (!ms_subclassFactories)
803 {
804 ms_subclassFactories = new wxXmlSubclassFactories;
805 }
806 ms_subclassFactories->push_back(factory);
807 }
808
809 class wxXmlSubclassFactoryCXX : public wxXmlSubclassFactory
810 {
811 public:
812 ~wxXmlSubclassFactoryCXX() {}
813
814 wxObject *Create(const wxString& className)
815 {
816 wxClassInfo* classInfo = wxClassInfo::FindClass(className);
817
818 if (classInfo)
819 return classInfo->CreateObject();
820 else
821 return NULL;
822 }
823 };
824
825
826
827
828 wxXmlResourceHandler::wxXmlResourceHandler()
829 : m_node(NULL), m_parent(NULL), m_instance(NULL),
830 m_parentAsWindow(NULL)
831 {}
832
833
834
835 wxObject *wxXmlResourceHandler::CreateResource(wxXmlNode *node, wxObject *parent, wxObject *instance)
836 {
837 wxXmlNode *myNode = m_node;
838 wxString myClass = m_class;
839 wxObject *myParent = m_parent, *myInstance = m_instance;
840 wxWindow *myParentAW = m_parentAsWindow;
841
842 m_instance = instance;
843 if (!m_instance && node->HasAttribute(wxT("subclass")) &&
844 !(m_resource->GetFlags() & wxXRC_NO_SUBCLASSING))
845 {
846 wxString subclass = node->GetAttribute(wxT("subclass"), wxEmptyString);
847 if (!subclass.empty())
848 {
849 for (wxXmlSubclassFactories::iterator i = wxXmlResource::ms_subclassFactories->begin();
850 i != wxXmlResource::ms_subclassFactories->end(); ++i)
851 {
852 m_instance = (*i)->Create(subclass);
853 if (m_instance)
854 break;
855 }
856
857 if (!m_instance)
858 {
859 wxString name = node->GetAttribute(wxT("name"), wxEmptyString);
860 wxLogError(_("Subclass '%s' not found for resource '%s', not subclassing!"),
861 subclass.c_str(), name.c_str());
862 }
863 }
864 }
865
866 m_node = node;
867 m_class = node->GetAttribute(wxT("class"), wxEmptyString);
868 m_parent = parent;
869 m_parentAsWindow = wxDynamicCast(m_parent, wxWindow);
870
871 wxObject *returned = DoCreateResource();
872
873 m_node = myNode;
874 m_class = myClass;
875 m_parent = myParent; m_parentAsWindow = myParentAW;
876 m_instance = myInstance;
877
878 return returned;
879 }
880
881
882 void wxXmlResourceHandler::AddStyle(const wxString& name, int value)
883 {
884 m_styleNames.Add(name);
885 m_styleValues.Add(value);
886 }
887
888
889
890 void wxXmlResourceHandler::AddWindowStyles()
891 {
892 XRC_ADD_STYLE(wxCLIP_CHILDREN);
893
894 // the border styles all have the old and new names, recognize both for now
895 XRC_ADD_STYLE(wxSIMPLE_BORDER); XRC_ADD_STYLE(wxBORDER_SIMPLE);
896 XRC_ADD_STYLE(wxSUNKEN_BORDER); XRC_ADD_STYLE(wxBORDER_SUNKEN);
897 XRC_ADD_STYLE(wxDOUBLE_BORDER); XRC_ADD_STYLE(wxBORDER_DOUBLE);
898 XRC_ADD_STYLE(wxRAISED_BORDER); XRC_ADD_STYLE(wxBORDER_RAISED);
899 XRC_ADD_STYLE(wxSTATIC_BORDER); XRC_ADD_STYLE(wxBORDER_STATIC);
900 XRC_ADD_STYLE(wxNO_BORDER); XRC_ADD_STYLE(wxBORDER_NONE);
901
902 XRC_ADD_STYLE(wxTRANSPARENT_WINDOW);
903 XRC_ADD_STYLE(wxWANTS_CHARS);
904 XRC_ADD_STYLE(wxTAB_TRAVERSAL);
905 XRC_ADD_STYLE(wxNO_FULL_REPAINT_ON_RESIZE);
906 XRC_ADD_STYLE(wxFULL_REPAINT_ON_RESIZE);
907 XRC_ADD_STYLE(wxALWAYS_SHOW_SB);
908 XRC_ADD_STYLE(wxWS_EX_BLOCK_EVENTS);
909 XRC_ADD_STYLE(wxWS_EX_VALIDATE_RECURSIVELY);
910 }
911
912
913
914 bool wxXmlResourceHandler::HasParam(const wxString& param)
915 {
916 return (GetParamNode(param) != NULL);
917 }
918
919
920 int wxXmlResourceHandler::GetStyle(const wxString& param, int defaults)
921 {
922 wxString s = GetParamValue(param);
923
924 if (!s) return defaults;
925
926 wxStringTokenizer tkn(s, wxT("| \t\n"), wxTOKEN_STRTOK);
927 int style = 0;
928 int index;
929 wxString fl;
930 while (tkn.HasMoreTokens())
931 {
932 fl = tkn.GetNextToken();
933 index = m_styleNames.Index(fl);
934 if (index != wxNOT_FOUND)
935 style |= m_styleValues[index];
936 else
937 wxLogError(_("Unknown style flag ") + fl);
938 }
939 return style;
940 }
941
942
943
944 wxString wxXmlResourceHandler::GetText(const wxString& param, bool translate)
945 {
946 wxXmlNode *parNode = GetParamNode(param);
947 wxString str1(GetNodeContent(parNode));
948 wxString str2;
949
950 // "\\" wasn't translated to "\" prior to 2.5.3.0:
951 const bool escapeBackslash = (m_resource->CompareVersion(2,5,3,0) >= 0);
952
953 // VS: First version of XRC resources used $ instead of & (which is
954 // illegal in XML), but later I realized that '_' fits this purpose
955 // much better (because &File means "File with F underlined").
956 const wxChar amp_char = (m_resource->CompareVersion(2,3,0,1) < 0)
957 ? '$' : '_';
958
959 for ( wxString::const_iterator dt = str1.begin(); dt != str1.end(); ++dt )
960 {
961 // Remap amp_char to &, map double amp_char to amp_char (for things
962 // like "&File..." -- this is illegal in XML, so we use "_File..."):
963 if ( *dt == amp_char )
964 {
965 if ( *(++dt) == amp_char )
966 str2 << amp_char;
967 else
968 str2 << wxT('&') << *dt;
969 }
970 // Remap \n to CR, \r to LF, \t to TAB, \\ to \:
971 else if ( *dt == wxT('\\') )
972 {
973 switch ( (*(++dt)).GetValue() )
974 {
975 case wxT('n'):
976 str2 << wxT('\n');
977 break;
978
979 case wxT('t'):
980 str2 << wxT('\t');
981 break;
982
983 case wxT('r'):
984 str2 << wxT('\r');
985 break;
986
987 case wxT('\\') :
988 // "\\" wasn't translated to "\" prior to 2.5.3.0:
989 if ( escapeBackslash )
990 {
991 str2 << wxT('\\');
992 break;
993 }
994 // else fall-through to default: branch below
995
996 default:
997 str2 << wxT('\\') << *dt;
998 break;
999 }
1000 }
1001 else
1002 {
1003 str2 << *dt;
1004 }
1005 }
1006
1007 if (m_resource->GetFlags() & wxXRC_USE_LOCALE)
1008 {
1009 if (translate && parNode &&
1010 parNode->GetAttribute(wxT("translate"), wxEmptyString) != wxT("0"))
1011 {
1012 return wxGetTranslation(str2, m_resource->GetDomain());
1013 }
1014 else
1015 {
1016 #if wxUSE_UNICODE
1017 return str2;
1018 #else
1019 // The string is internally stored as UTF-8, we have to convert
1020 // it into system's default encoding so that it can be displayed:
1021 return wxString(str2.wc_str(wxConvUTF8), wxConvLocal);
1022 #endif
1023 }
1024 }
1025
1026 // If wxXRC_USE_LOCALE is not set, then the string is already in
1027 // system's default encoding in ANSI build, so we don't have to
1028 // do anything special here.
1029 return str2;
1030 }
1031
1032
1033
1034 long wxXmlResourceHandler::GetLong(const wxString& param, long defaultv)
1035 {
1036 long value;
1037 wxString str1 = GetParamValue(param);
1038
1039 if (!str1.ToLong(&value))
1040 value = defaultv;
1041
1042 return value;
1043 }
1044
1045 float wxXmlResourceHandler::GetFloat(const wxString& param, float defaultv)
1046 {
1047 wxString str = GetParamValue(param);
1048
1049 #if wxUSE_INTL
1050 // strings in XRC always use C locale but wxString::ToDouble() uses the
1051 // current one, so transform the string to it supposing that the only
1052 // difference between them is the decimal separator
1053 //
1054 // TODO: use wxString::ToCDouble() when we have it
1055 str.Replace(wxT("."), wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT,
1056 wxLOCALE_CAT_NUMBER));
1057 #endif // wxUSE_INTL
1058
1059 double value;
1060 if (!str.ToDouble(&value))
1061 value = defaultv;
1062
1063 return wx_truncate_cast(float, value);
1064 }
1065
1066
1067 int wxXmlResourceHandler::GetID()
1068 {
1069 return wxXmlResource::GetXRCID(GetName());
1070 }
1071
1072
1073
1074 wxString wxXmlResourceHandler::GetName()
1075 {
1076 return m_node->GetAttribute(wxT("name"), wxT("-1"));
1077 }
1078
1079
1080
1081 bool wxXmlResourceHandler::GetBoolAttr(const wxString& attr, bool defaultv)
1082 {
1083 wxString v;
1084 return m_node->GetAttribute(attr, &v) ? v == '1' : defaultv;
1085 }
1086
1087 bool wxXmlResourceHandler::GetBool(const wxString& param, bool defaultv)
1088 {
1089 const wxString v = GetParamValue(param);
1090
1091 return v.empty() ? defaultv : (v == '1');
1092 }
1093
1094
1095 static wxColour GetSystemColour(const wxString& name)
1096 {
1097 if (!name.empty())
1098 {
1099 #define SYSCLR(clr) \
1100 if (name == _T(#clr)) return wxSystemSettings::GetColour(clr);
1101 SYSCLR(wxSYS_COLOUR_SCROLLBAR)
1102 SYSCLR(wxSYS_COLOUR_BACKGROUND)
1103 SYSCLR(wxSYS_COLOUR_DESKTOP)
1104 SYSCLR(wxSYS_COLOUR_ACTIVECAPTION)
1105 SYSCLR(wxSYS_COLOUR_INACTIVECAPTION)
1106 SYSCLR(wxSYS_COLOUR_MENU)
1107 SYSCLR(wxSYS_COLOUR_WINDOW)
1108 SYSCLR(wxSYS_COLOUR_WINDOWFRAME)
1109 SYSCLR(wxSYS_COLOUR_MENUTEXT)
1110 SYSCLR(wxSYS_COLOUR_WINDOWTEXT)
1111 SYSCLR(wxSYS_COLOUR_CAPTIONTEXT)
1112 SYSCLR(wxSYS_COLOUR_ACTIVEBORDER)
1113 SYSCLR(wxSYS_COLOUR_INACTIVEBORDER)
1114 SYSCLR(wxSYS_COLOUR_APPWORKSPACE)
1115 SYSCLR(wxSYS_COLOUR_HIGHLIGHT)
1116 SYSCLR(wxSYS_COLOUR_HIGHLIGHTTEXT)
1117 SYSCLR(wxSYS_COLOUR_BTNFACE)
1118 SYSCLR(wxSYS_COLOUR_3DFACE)
1119 SYSCLR(wxSYS_COLOUR_BTNSHADOW)
1120 SYSCLR(wxSYS_COLOUR_3DSHADOW)
1121 SYSCLR(wxSYS_COLOUR_GRAYTEXT)
1122 SYSCLR(wxSYS_COLOUR_BTNTEXT)
1123 SYSCLR(wxSYS_COLOUR_INACTIVECAPTIONTEXT)
1124 SYSCLR(wxSYS_COLOUR_BTNHIGHLIGHT)
1125 SYSCLR(wxSYS_COLOUR_BTNHILIGHT)
1126 SYSCLR(wxSYS_COLOUR_3DHIGHLIGHT)
1127 SYSCLR(wxSYS_COLOUR_3DHILIGHT)
1128 SYSCLR(wxSYS_COLOUR_3DDKSHADOW)
1129 SYSCLR(wxSYS_COLOUR_3DLIGHT)
1130 SYSCLR(wxSYS_COLOUR_INFOTEXT)
1131 SYSCLR(wxSYS_COLOUR_INFOBK)
1132 SYSCLR(wxSYS_COLOUR_LISTBOX)
1133 SYSCLR(wxSYS_COLOUR_HOTLIGHT)
1134 SYSCLR(wxSYS_COLOUR_GRADIENTACTIVECAPTION)
1135 SYSCLR(wxSYS_COLOUR_GRADIENTINACTIVECAPTION)
1136 SYSCLR(wxSYS_COLOUR_MENUHILIGHT)
1137 SYSCLR(wxSYS_COLOUR_MENUBAR)
1138 #undef SYSCLR
1139 }
1140
1141 return wxNullColour;
1142 }
1143
1144 wxColour wxXmlResourceHandler::GetColour(const wxString& param, const wxColour& defaultv)
1145 {
1146 wxString v = GetParamValue(param);
1147
1148 if ( v.empty() )
1149 return defaultv;
1150
1151 wxColour clr;
1152
1153 // wxString -> wxColour conversion
1154 if (!clr.Set(v))
1155 {
1156 // the colour doesn't use #RRGGBB format, check if it is symbolic
1157 // colour name:
1158 clr = GetSystemColour(v);
1159 if (clr.Ok())
1160 return clr;
1161
1162 wxLogError(_("XRC resource: Incorrect colour specification '%s' for attribute '%s'."),
1163 v.c_str(), param.c_str());
1164 return wxNullColour;
1165 }
1166
1167 return clr;
1168 }
1169
1170
1171
1172 wxBitmap wxXmlResourceHandler::GetBitmap(const wxString& param,
1173 const wxArtClient& defaultArtClient,
1174 wxSize size)
1175 {
1176 /* If the bitmap is specified as stock item, query wxArtProvider for it: */
1177 wxXmlNode *bmpNode = GetParamNode(param);
1178 if ( bmpNode )
1179 {
1180 wxString sid = bmpNode->GetAttribute(wxT("stock_id"), wxEmptyString);
1181 if ( !sid.empty() )
1182 {
1183 wxString scl = bmpNode->GetAttribute(wxT("stock_client"), wxEmptyString);
1184 if (scl.empty())
1185 scl = defaultArtClient;
1186 else
1187 scl = wxART_MAKE_CLIENT_ID_FROM_STR(scl);
1188
1189 wxBitmap stockArt =
1190 wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(sid),
1191 scl, size);
1192 if ( stockArt.Ok() )
1193 return stockArt;
1194 }
1195 }
1196
1197 /* ...or load the bitmap from file: */
1198 wxString name = GetParamValue(param);
1199 if (name.empty()) return wxNullBitmap;
1200 #if wxUSE_FILESYSTEM
1201 wxFSFile *fsfile = GetCurFileSystem().OpenFile(name, wxFS_READ | wxFS_SEEKABLE);
1202 if (fsfile == NULL)
1203 {
1204 wxLogError(_("XRC resource: Cannot create bitmap from '%s'."),
1205 name.c_str());
1206 return wxNullBitmap;
1207 }
1208 wxImage img(*(fsfile->GetStream()));
1209 delete fsfile;
1210 #else
1211 wxImage img(name);
1212 #endif
1213
1214 if (!img.Ok())
1215 {
1216 wxLogError(_("XRC resource: Cannot create bitmap from '%s'."),
1217 name.c_str());
1218 return wxNullBitmap;
1219 }
1220 if (!(size == wxDefaultSize)) img.Rescale(size.x, size.y);
1221 return wxBitmap(img);
1222 }
1223
1224
1225 wxIcon wxXmlResourceHandler::GetIcon(const wxString& param,
1226 const wxArtClient& defaultArtClient,
1227 wxSize size)
1228 {
1229 wxIcon icon;
1230 icon.CopyFromBitmap(GetBitmap(param, defaultArtClient, size));
1231 return icon;
1232 }
1233
1234
1235
1236 wxXmlNode *wxXmlResourceHandler::GetParamNode(const wxString& param)
1237 {
1238 wxCHECK_MSG(m_node, NULL, wxT("You can't access handler data before it was initialized!"));
1239
1240 wxXmlNode *n = m_node->GetChildren();
1241
1242 while (n)
1243 {
1244 if (n->GetType() == wxXML_ELEMENT_NODE && n->GetName() == param)
1245 {
1246 // TODO: check that there are no other properties/parameters with
1247 // the same name and log an error if there are (can't do this
1248 // right now as I'm not sure if it's not going to break code
1249 // using this function in unintentional way (i.e. for
1250 // accessing other things than properties), for example
1251 // wxBitmapComboBoxXmlHandler almost surely does
1252 return n;
1253 }
1254 n = n->GetNext();
1255 }
1256 return NULL;
1257 }
1258
1259 bool wxXmlResourceHandler::IsOfClass(wxXmlNode *node, const wxString& classname)
1260 {
1261 return node->GetAttribute(wxT("class"), wxEmptyString) == classname;
1262 }
1263
1264
1265
1266 wxString wxXmlResourceHandler::GetNodeContent(wxXmlNode *node)
1267 {
1268 wxXmlNode *n = node;
1269 if (n == NULL) return wxEmptyString;
1270 n = n->GetChildren();
1271
1272 while (n)
1273 {
1274 if (n->GetType() == wxXML_TEXT_NODE ||
1275 n->GetType() == wxXML_CDATA_SECTION_NODE)
1276 return n->GetContent();
1277 n = n->GetNext();
1278 }
1279 return wxEmptyString;
1280 }
1281
1282
1283
1284 wxString wxXmlResourceHandler::GetParamValue(const wxString& param)
1285 {
1286 if (param.empty())
1287 return GetNodeContent(m_node);
1288 else
1289 return GetNodeContent(GetParamNode(param));
1290 }
1291
1292
1293
1294 wxSize wxXmlResourceHandler::GetSize(const wxString& param,
1295 wxWindow *windowToUse)
1296 {
1297 wxString s = GetParamValue(param);
1298 if (s.empty()) s = wxT("-1,-1");
1299 bool is_dlg;
1300 long sx, sy = 0;
1301
1302 is_dlg = s[s.length()-1] == wxT('d');
1303 if (is_dlg) s.RemoveLast();
1304
1305 if (!s.BeforeFirst(wxT(',')).ToLong(&sx) ||
1306 !s.AfterLast(wxT(',')).ToLong(&sy))
1307 {
1308 wxLogError(_("Cannot parse coordinates from '%s'."), s.c_str());
1309 return wxDefaultSize;
1310 }
1311
1312 if (is_dlg)
1313 {
1314 if (windowToUse)
1315 {
1316 return wxDLG_UNIT(windowToUse, wxSize(sx, sy));
1317 }
1318 else if (m_parentAsWindow)
1319 {
1320 return wxDLG_UNIT(m_parentAsWindow, wxSize(sx, sy));
1321 }
1322 else
1323 {
1324 wxLogError(_("Cannot convert dialog units: dialog unknown."));
1325 return wxDefaultSize;
1326 }
1327 }
1328
1329 return wxSize(sx, sy);
1330 }
1331
1332
1333
1334 wxPoint wxXmlResourceHandler::GetPosition(const wxString& param)
1335 {
1336 wxSize sz = GetSize(param);
1337 return wxPoint(sz.x, sz.y);
1338 }
1339
1340
1341
1342 wxCoord wxXmlResourceHandler::GetDimension(const wxString& param,
1343 wxCoord defaultv,
1344 wxWindow *windowToUse)
1345 {
1346 wxString s = GetParamValue(param);
1347 if (s.empty()) return defaultv;
1348 bool is_dlg;
1349 long sx;
1350
1351 is_dlg = s[s.length()-1] == wxT('d');
1352 if (is_dlg) s.RemoveLast();
1353
1354 if (!s.ToLong(&sx))
1355 {
1356 wxLogError(_("Cannot parse dimension from '%s'."), s.c_str());
1357 return defaultv;
1358 }
1359
1360 if (is_dlg)
1361 {
1362 if (windowToUse)
1363 {
1364 return wxDLG_UNIT(windowToUse, wxSize(sx, 0)).x;
1365 }
1366 else if (m_parentAsWindow)
1367 {
1368 return wxDLG_UNIT(m_parentAsWindow, wxSize(sx, 0)).x;
1369 }
1370 else
1371 {
1372 wxLogError(_("Cannot convert dialog units: dialog unknown."));
1373 return defaultv;
1374 }
1375 }
1376
1377 return sx;
1378 }
1379
1380
1381 // Get system font index using indexname
1382 static wxFont GetSystemFont(const wxString& name)
1383 {
1384 if (!name.empty())
1385 {
1386 #define SYSFNT(fnt) \
1387 if (name == _T(#fnt)) return wxSystemSettings::GetFont(fnt);
1388 SYSFNT(wxSYS_OEM_FIXED_FONT)
1389 SYSFNT(wxSYS_ANSI_FIXED_FONT)
1390 SYSFNT(wxSYS_ANSI_VAR_FONT)
1391 SYSFNT(wxSYS_SYSTEM_FONT)
1392 SYSFNT(wxSYS_DEVICE_DEFAULT_FONT)
1393 SYSFNT(wxSYS_DEFAULT_PALETTE)
1394 SYSFNT(wxSYS_SYSTEM_FIXED_FONT)
1395 SYSFNT(wxSYS_DEFAULT_GUI_FONT)
1396 #undef SYSFNT
1397 }
1398
1399 return wxNullFont;
1400 }
1401
1402 wxFont wxXmlResourceHandler::GetFont(const wxString& param)
1403 {
1404 wxXmlNode *font_node = GetParamNode(param);
1405 if (font_node == NULL)
1406 {
1407 wxLogError(_("Cannot find font node '%s'."), param.c_str());
1408 return wxNullFont;
1409 }
1410
1411 wxXmlNode *oldnode = m_node;
1412 m_node = font_node;
1413
1414 // font attributes:
1415
1416 // size
1417 int isize = -1;
1418 bool hasSize = HasParam(wxT("size"));
1419 if (hasSize)
1420 isize = GetLong(wxT("size"), -1);
1421
1422 // style
1423 int istyle = wxNORMAL;
1424 bool hasStyle = HasParam(wxT("style"));
1425 if (hasStyle)
1426 {
1427 wxString style = GetParamValue(wxT("style"));
1428 if (style == wxT("italic"))
1429 istyle = wxITALIC;
1430 else if (style == wxT("slant"))
1431 istyle = wxSLANT;
1432 }
1433
1434 // weight
1435 int iweight = wxNORMAL;
1436 bool hasWeight = HasParam(wxT("weight"));
1437 if (hasWeight)
1438 {
1439 wxString weight = GetParamValue(wxT("weight"));
1440 if (weight == wxT("bold"))
1441 iweight = wxBOLD;
1442 else if (weight == wxT("light"))
1443 iweight = wxLIGHT;
1444 }
1445
1446 // underline
1447 bool hasUnderlined = HasParam(wxT("underlined"));
1448 bool underlined = hasUnderlined ? GetBool(wxT("underlined"), false) : false;
1449
1450 // family and facename
1451 int ifamily = wxDEFAULT;
1452 bool hasFamily = HasParam(wxT("family"));
1453 if (hasFamily)
1454 {
1455 wxString family = GetParamValue(wxT("family"));
1456 if (family == wxT("decorative")) ifamily = wxDECORATIVE;
1457 else if (family == wxT("roman")) ifamily = wxROMAN;
1458 else if (family == wxT("script")) ifamily = wxSCRIPT;
1459 else if (family == wxT("swiss")) ifamily = wxSWISS;
1460 else if (family == wxT("modern")) ifamily = wxMODERN;
1461 else if (family == wxT("teletype")) ifamily = wxTELETYPE;
1462 }
1463
1464
1465 wxString facename;
1466 bool hasFacename = HasParam(wxT("face"));
1467 if (hasFacename)
1468 {
1469 wxString faces = GetParamValue(wxT("face"));
1470 wxStringTokenizer tk(faces, wxT(","));
1471 #if wxUSE_FONTENUM
1472 wxArrayString facenames(wxFontEnumerator::GetFacenames());
1473 while (tk.HasMoreTokens())
1474 {
1475 int index = facenames.Index(tk.GetNextToken(), false);
1476 if (index != wxNOT_FOUND)
1477 {
1478 facename = facenames[index];
1479 break;
1480 }
1481 }
1482 #else // !wxUSE_FONTENUM
1483 // just use the first face name if we can't check its availability:
1484 if (tk.HasMoreTokens())
1485 facename = tk.GetNextToken();
1486 #endif // wxUSE_FONTENUM/!wxUSE_FONTENUM
1487 }
1488
1489 // encoding
1490 wxFontEncoding enc = wxFONTENCODING_DEFAULT;
1491 bool hasEncoding = HasParam(wxT("encoding"));
1492 if (hasEncoding)
1493 {
1494 wxString encoding = GetParamValue(wxT("encoding"));
1495 wxFontMapper mapper;
1496 if (!encoding.empty())
1497 enc = mapper.CharsetToEncoding(encoding);
1498 if (enc == wxFONTENCODING_SYSTEM)
1499 enc = wxFONTENCODING_DEFAULT;
1500 }
1501
1502 // is this font based on a system font?
1503 wxFont font = GetSystemFont(GetParamValue(wxT("sysfont")));
1504
1505 if (font.Ok())
1506 {
1507 if (hasSize && isize != -1)
1508 font.SetPointSize(isize);
1509 else if (HasParam(wxT("relativesize")))
1510 font.SetPointSize(int(font.GetPointSize() *
1511 GetFloat(wxT("relativesize"))));
1512
1513 if (hasStyle)
1514 font.SetStyle(istyle);
1515 if (hasWeight)
1516 font.SetWeight(iweight);
1517 if (hasUnderlined)
1518 font.SetUnderlined(underlined);
1519 if (hasFamily)
1520 font.SetFamily(ifamily);
1521 if (hasFacename)
1522 font.SetFaceName(facename);
1523 if (hasEncoding)
1524 font.SetDefaultEncoding(enc);
1525 }
1526 else // not based on system font
1527 {
1528 font = wxFont(isize == -1 ? wxNORMAL_FONT->GetPointSize() : isize,
1529 ifamily, istyle, iweight,
1530 underlined, facename, enc);
1531 }
1532
1533 m_node = oldnode;
1534 return font;
1535 }
1536
1537
1538 void wxXmlResourceHandler::SetupWindow(wxWindow *wnd)
1539 {
1540 //FIXME : add cursor
1541
1542 if (HasParam(wxT("exstyle")))
1543 // Have to OR it with existing style, since
1544 // some implementations (e.g. wxGTK) use the extra style
1545 // during creation
1546 wnd->SetExtraStyle(wnd->GetExtraStyle() | GetStyle(wxT("exstyle")));
1547 if (HasParam(wxT("bg")))
1548 wnd->SetBackgroundColour(GetColour(wxT("bg")));
1549 if (HasParam(wxT("fg")))
1550 wnd->SetForegroundColour(GetColour(wxT("fg")));
1551 if (GetBool(wxT("enabled"), 1) == 0)
1552 wnd->Enable(false);
1553 if (GetBool(wxT("focused"), 0) == 1)
1554 wnd->SetFocus();
1555 if (GetBool(wxT("hidden"), 0) == 1)
1556 wnd->Show(false);
1557 #if wxUSE_TOOLTIPS
1558 if (HasParam(wxT("tooltip")))
1559 wnd->SetToolTip(GetText(wxT("tooltip")));
1560 #endif
1561 if (HasParam(wxT("font")))
1562 wnd->SetFont(GetFont());
1563 if (HasParam(wxT("help")))
1564 wnd->SetHelpText(GetText(wxT("help")));
1565 }
1566
1567
1568 void wxXmlResourceHandler::CreateChildren(wxObject *parent, bool this_hnd_only)
1569 {
1570 for ( wxXmlNode *n = m_node->GetChildren(); n; n = n->GetNext() )
1571 {
1572 if ( IsObjectNode(n) )
1573 {
1574 m_resource->CreateResFromNode(n, parent, NULL,
1575 this_hnd_only ? this : NULL);
1576 }
1577 }
1578 }
1579
1580
1581 void wxXmlResourceHandler::CreateChildrenPrivately(wxObject *parent, wxXmlNode *rootnode)
1582 {
1583 wxXmlNode *root;
1584 if (rootnode == NULL) root = m_node; else root = rootnode;
1585 wxXmlNode *n = root->GetChildren();
1586
1587 while (n)
1588 {
1589 if (n->GetType() == wxXML_ELEMENT_NODE && CanHandle(n))
1590 {
1591 CreateResource(n, parent, NULL);
1592 }
1593 n = n->GetNext();
1594 }
1595 }
1596
1597
1598
1599
1600
1601
1602
1603 // --------------- XRCID implementation -----------------------------
1604
1605 #define XRCID_TABLE_SIZE 1024
1606
1607
1608 struct XRCID_record
1609 {
1610 /* Hold the id so that once an id is allocated for a name, it
1611 does not get created again by NewControlId at least
1612 until we are done with it */
1613 wxWindowIDRef id;
1614 char *key;
1615 XRCID_record *next;
1616 };
1617
1618 static XRCID_record *XRCID_Records[XRCID_TABLE_SIZE] = {NULL};
1619
1620 static int XRCID_Lookup(const char *str_id, int value_if_not_found = wxID_NONE)
1621 {
1622 int index = 0;
1623
1624 for (const char *c = str_id; *c != '\0'; c++) index += (int)*c;
1625 index %= XRCID_TABLE_SIZE;
1626
1627 XRCID_record *oldrec = NULL;
1628 for (XRCID_record *rec = XRCID_Records[index]; rec; rec = rec->next)
1629 {
1630 if (wxStrcmp(rec->key, str_id) == 0)
1631 {
1632 return rec->id;
1633 }
1634 oldrec = rec;
1635 }
1636
1637 XRCID_record **rec_var = (oldrec == NULL) ?
1638 &XRCID_Records[index] : &oldrec->next;
1639 *rec_var = new XRCID_record;
1640 (*rec_var)->key = wxStrdup(str_id);
1641 (*rec_var)->next = NULL;
1642
1643 char *end;
1644 if (value_if_not_found != wxID_NONE)
1645 (*rec_var)->id = value_if_not_found;
1646 else
1647 {
1648 int asint = wxStrtol(str_id, &end, 10);
1649 if (*str_id && *end == 0)
1650 {
1651 // if str_id was integer, keep it verbosely:
1652 (*rec_var)->id = asint;
1653 }
1654 else
1655 {
1656 (*rec_var)->id = wxWindowBase::NewControlId();
1657 }
1658 }
1659
1660 return (*rec_var)->id;
1661 }
1662
1663 static void AddStdXRCID_Records();
1664
1665 /*static*/
1666 int wxXmlResource::DoGetXRCID(const char *str_id, int value_if_not_found)
1667 {
1668 static bool s_stdIDsAdded = false;
1669
1670 if ( !s_stdIDsAdded )
1671 {
1672 s_stdIDsAdded = true;
1673 AddStdXRCID_Records();
1674 }
1675
1676 return XRCID_Lookup(str_id, value_if_not_found);
1677 }
1678
1679 /* static */
1680 wxString wxXmlResource::FindXRCIDById(int numId)
1681 {
1682 for ( int i = 0; i < XRCID_TABLE_SIZE; i++ )
1683 {
1684 for ( XRCID_record *rec = XRCID_Records[i]; rec; rec = rec->next )
1685 {
1686 if ( rec->id == numId )
1687 return wxString(rec->key);
1688 }
1689 }
1690
1691 return wxString();
1692 }
1693
1694 static void CleanXRCID_Record(XRCID_record *rec)
1695 {
1696 if (rec)
1697 {
1698 CleanXRCID_Record(rec->next);
1699
1700 free(rec->key);
1701 delete rec;
1702 }
1703 }
1704
1705 static void CleanXRCID_Records()
1706 {
1707 for (int i = 0; i < XRCID_TABLE_SIZE; i++)
1708 {
1709 CleanXRCID_Record(XRCID_Records[i]);
1710 XRCID_Records[i] = NULL;
1711 }
1712 }
1713
1714 static void AddStdXRCID_Records()
1715 {
1716 #define stdID(id) XRCID_Lookup(#id, id)
1717 stdID(-1);
1718
1719 stdID(wxID_ANY);
1720 stdID(wxID_SEPARATOR);
1721
1722 stdID(wxID_OPEN);
1723 stdID(wxID_CLOSE);
1724 stdID(wxID_NEW);
1725 stdID(wxID_SAVE);
1726 stdID(wxID_SAVEAS);
1727 stdID(wxID_REVERT);
1728 stdID(wxID_EXIT);
1729 stdID(wxID_UNDO);
1730 stdID(wxID_REDO);
1731 stdID(wxID_HELP);
1732 stdID(wxID_PRINT);
1733 stdID(wxID_PRINT_SETUP);
1734 stdID(wxID_PAGE_SETUP);
1735 stdID(wxID_PREVIEW);
1736 stdID(wxID_ABOUT);
1737 stdID(wxID_HELP_CONTENTS);
1738 stdID(wxID_HELP_COMMANDS);
1739 stdID(wxID_HELP_PROCEDURES);
1740 stdID(wxID_HELP_CONTEXT);
1741 stdID(wxID_CLOSE_ALL);
1742 stdID(wxID_PREFERENCES);
1743 stdID(wxID_EDIT);
1744 stdID(wxID_CUT);
1745 stdID(wxID_COPY);
1746 stdID(wxID_PASTE);
1747 stdID(wxID_CLEAR);
1748 stdID(wxID_FIND);
1749 stdID(wxID_DUPLICATE);
1750 stdID(wxID_SELECTALL);
1751 stdID(wxID_DELETE);
1752 stdID(wxID_REPLACE);
1753 stdID(wxID_REPLACE_ALL);
1754 stdID(wxID_PROPERTIES);
1755 stdID(wxID_VIEW_DETAILS);
1756 stdID(wxID_VIEW_LARGEICONS);
1757 stdID(wxID_VIEW_SMALLICONS);
1758 stdID(wxID_VIEW_LIST);
1759 stdID(wxID_VIEW_SORTDATE);
1760 stdID(wxID_VIEW_SORTNAME);
1761 stdID(wxID_VIEW_SORTSIZE);
1762 stdID(wxID_VIEW_SORTTYPE);
1763 stdID(wxID_FILE1);
1764 stdID(wxID_FILE2);
1765 stdID(wxID_FILE3);
1766 stdID(wxID_FILE4);
1767 stdID(wxID_FILE5);
1768 stdID(wxID_FILE6);
1769 stdID(wxID_FILE7);
1770 stdID(wxID_FILE8);
1771 stdID(wxID_FILE9);
1772 stdID(wxID_OK);
1773 stdID(wxID_CANCEL);
1774 stdID(wxID_APPLY);
1775 stdID(wxID_YES);
1776 stdID(wxID_NO);
1777 stdID(wxID_STATIC);
1778 stdID(wxID_FORWARD);
1779 stdID(wxID_BACKWARD);
1780 stdID(wxID_DEFAULT);
1781 stdID(wxID_MORE);
1782 stdID(wxID_SETUP);
1783 stdID(wxID_RESET);
1784 stdID(wxID_CONTEXT_HELP);
1785 stdID(wxID_YESTOALL);
1786 stdID(wxID_NOTOALL);
1787 stdID(wxID_ABORT);
1788 stdID(wxID_RETRY);
1789 stdID(wxID_IGNORE);
1790 stdID(wxID_ADD);
1791 stdID(wxID_REMOVE);
1792 stdID(wxID_UP);
1793 stdID(wxID_DOWN);
1794 stdID(wxID_HOME);
1795 stdID(wxID_REFRESH);
1796 stdID(wxID_STOP);
1797 stdID(wxID_INDEX);
1798 stdID(wxID_BOLD);
1799 stdID(wxID_ITALIC);
1800 stdID(wxID_JUSTIFY_CENTER);
1801 stdID(wxID_JUSTIFY_FILL);
1802 stdID(wxID_JUSTIFY_RIGHT);
1803 stdID(wxID_JUSTIFY_LEFT);
1804 stdID(wxID_UNDERLINE);
1805 stdID(wxID_INDENT);
1806 stdID(wxID_UNINDENT);
1807 stdID(wxID_ZOOM_100);
1808 stdID(wxID_ZOOM_FIT);
1809 stdID(wxID_ZOOM_IN);
1810 stdID(wxID_ZOOM_OUT);
1811 stdID(wxID_UNDELETE);
1812 stdID(wxID_REVERT_TO_SAVED);
1813 stdID(wxID_SYSTEM_MENU);
1814 stdID(wxID_CLOSE_FRAME);
1815 stdID(wxID_MOVE_FRAME);
1816 stdID(wxID_RESIZE_FRAME);
1817 stdID(wxID_MAXIMIZE_FRAME);
1818 stdID(wxID_ICONIZE_FRAME);
1819 stdID(wxID_RESTORE_FRAME);
1820 stdID(wxID_CDROM);
1821 stdID(wxID_CONVERT);
1822 stdID(wxID_EXECUTE);
1823 stdID(wxID_FLOPPY);
1824 stdID(wxID_HARDDISK);
1825 stdID(wxID_BOTTOM);
1826 stdID(wxID_FIRST);
1827 stdID(wxID_LAST);
1828 stdID(wxID_TOP);
1829 stdID(wxID_INFO);
1830 stdID(wxID_JUMP_TO);
1831 stdID(wxID_NETWORK);
1832 stdID(wxID_SELECT_COLOR);
1833 stdID(wxID_SELECT_FONT);
1834 stdID(wxID_SORT_ASCENDING);
1835 stdID(wxID_SORT_DESCENDING);
1836 stdID(wxID_SPELL_CHECK);
1837 stdID(wxID_STRIKETHROUGH);
1838
1839 #undef stdID
1840 }
1841
1842
1843
1844
1845
1846 // --------------- module and globals -----------------------------
1847
1848 // normally we would do the cleanup from wxXmlResourceModule::OnExit() but it
1849 // can happen that some XRC records have been created because of the use of
1850 // XRCID() in event tables, which happens during static objects initialization,
1851 // but then the application initialization failed and so the wx modules were
1852 // neither initialized nor cleaned up -- this static object does the cleanup in
1853 // this case
1854 static struct wxXRCStaticCleanup
1855 {
1856 ~wxXRCStaticCleanup() { CleanXRCID_Records(); }
1857 } s_staticCleanup;
1858
1859 class wxXmlResourceModule: public wxModule
1860 {
1861 DECLARE_DYNAMIC_CLASS(wxXmlResourceModule)
1862 public:
1863 wxXmlResourceModule() {}
1864 bool OnInit()
1865 {
1866 wxXmlResource::AddSubclassFactory(new wxXmlSubclassFactoryCXX);
1867 return true;
1868 }
1869 void OnExit()
1870 {
1871 delete wxXmlResource::Set(NULL);
1872 if(wxXmlResource::ms_subclassFactories)
1873 {
1874 for ( wxXmlSubclassFactories::iterator i = wxXmlResource::ms_subclassFactories->begin();
1875 i != wxXmlResource::ms_subclassFactories->end(); ++i )
1876 {
1877 delete *i;
1878 }
1879 wxDELETE(wxXmlResource::ms_subclassFactories);
1880 }
1881 CleanXRCID_Records();
1882 }
1883 };
1884
1885 IMPLEMENT_DYNAMIC_CLASS(wxXmlResourceModule, wxModule)
1886
1887
1888 // When wxXml is loaded dynamically after the application is already running
1889 // then the built-in module system won't pick this one up. Add it manually.
1890 void wxXmlInitResourceModule()
1891 {
1892 wxModule* module = new wxXmlResourceModule;
1893 module->Init();
1894 wxModule::RegisterModule(module);
1895 }
1896
1897 #endif // wxUSE_XRC