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