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