]> git.saurik.com Git - wxWidgets.git/blob - src/xrc/xmlres.cpp
e9942ba2850af3b982190bd6f9ca3ab1f02074ba
[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 if ( !node->GetChildren() )
848 {
849 // In the typical, simple case, <object_ref> is used to link
850 // to another node and doesn't have any content of its own that
851 // would overwrite linked object's properties. In this case,
852 // we can simply create the resource from linked node.
853
854 return CreateResFromNode(refNode, parent, instance);
855 }
856 else
857 {
858 // In the more complicated (but rare) case, <object_ref> has
859 // subnodes that partially overwrite content of the referenced
860 // object. In this case, we need to merge both XML trees and
861 // load the resource from result of the merge.
862
863 wxXmlNode copy(*refNode);
864 MergeNodesOver(copy, *node, GetFileNameFromNode(node, Data()));
865
866 // remember referenced object's file, see GetFileNameFromNode()
867 copy.AddAttribute(ATTR_INPUT_FILENAME,
868 GetFileNameFromNode(refNode, Data()));
869
870 return CreateResFromNode(&copy, parent, instance);
871 }
872 }
873
874 if (handlerToUse)
875 {
876 if (handlerToUse->CanHandle(node))
877 {
878 return handlerToUse->CreateResource(node, parent, instance);
879 }
880 }
881 else if (node->GetName() == wxT("object"))
882 {
883 for ( wxVector<wxXmlResourceHandler*>::iterator h = m_handlers.begin();
884 h != m_handlers.end(); ++h )
885 {
886 wxXmlResourceHandler *handler = *h;
887 if (handler->CanHandle(node))
888 return handler->CreateResource(node, parent, instance);
889 }
890 }
891
892 ReportError
893 (
894 node,
895 wxString::Format
896 (
897 "no handler found for XML node \"%s\" (class \"%s\")",
898 node->GetName(),
899 node->GetAttribute("class", wxEmptyString)
900 )
901 );
902 return NULL;
903 }
904
905
906 class wxXmlSubclassFactories : public wxVector<wxXmlSubclassFactory*>
907 {
908 // this is a class so that it can be forward-declared
909 };
910
911 wxXmlSubclassFactories *wxXmlResource::ms_subclassFactories = NULL;
912
913 /*static*/ void wxXmlResource::AddSubclassFactory(wxXmlSubclassFactory *factory)
914 {
915 if (!ms_subclassFactories)
916 {
917 ms_subclassFactories = new wxXmlSubclassFactories;
918 }
919 ms_subclassFactories->push_back(factory);
920 }
921
922 class wxXmlSubclassFactoryCXX : public wxXmlSubclassFactory
923 {
924 public:
925 ~wxXmlSubclassFactoryCXX() {}
926
927 wxObject *Create(const wxString& className)
928 {
929 wxClassInfo* classInfo = wxClassInfo::FindClass(className);
930
931 if (classInfo)
932 return classInfo->CreateObject();
933 else
934 return NULL;
935 }
936 };
937
938
939
940
941 wxXmlResourceHandler::wxXmlResourceHandler()
942 : m_node(NULL), m_parent(NULL), m_instance(NULL),
943 m_parentAsWindow(NULL)
944 {}
945
946
947
948 wxObject *wxXmlResourceHandler::CreateResource(wxXmlNode *node, wxObject *parent, wxObject *instance)
949 {
950 wxXmlNode *myNode = m_node;
951 wxString myClass = m_class;
952 wxObject *myParent = m_parent, *myInstance = m_instance;
953 wxWindow *myParentAW = m_parentAsWindow;
954
955 m_instance = instance;
956 if (!m_instance && node->HasAttribute(wxT("subclass")) &&
957 !(m_resource->GetFlags() & wxXRC_NO_SUBCLASSING))
958 {
959 wxString subclass = node->GetAttribute(wxT("subclass"), wxEmptyString);
960 if (!subclass.empty())
961 {
962 for (wxXmlSubclassFactories::iterator i = wxXmlResource::ms_subclassFactories->begin();
963 i != wxXmlResource::ms_subclassFactories->end(); ++i)
964 {
965 m_instance = (*i)->Create(subclass);
966 if (m_instance)
967 break;
968 }
969
970 if (!m_instance)
971 {
972 wxString name = node->GetAttribute(wxT("name"), wxEmptyString);
973 ReportError
974 (
975 node,
976 wxString::Format
977 (
978 "subclass \"%s\" not found for resource \"%s\", not subclassing",
979 subclass, name
980 )
981 );
982 }
983 }
984 }
985
986 m_node = node;
987 m_class = node->GetAttribute(wxT("class"), wxEmptyString);
988 m_parent = parent;
989 m_parentAsWindow = wxDynamicCast(m_parent, wxWindow);
990
991 wxObject *returned = DoCreateResource();
992
993 m_node = myNode;
994 m_class = myClass;
995 m_parent = myParent; m_parentAsWindow = myParentAW;
996 m_instance = myInstance;
997
998 return returned;
999 }
1000
1001
1002 void wxXmlResourceHandler::AddStyle(const wxString& name, int value)
1003 {
1004 m_styleNames.Add(name);
1005 m_styleValues.Add(value);
1006 }
1007
1008
1009
1010 void wxXmlResourceHandler::AddWindowStyles()
1011 {
1012 XRC_ADD_STYLE(wxCLIP_CHILDREN);
1013
1014 // the border styles all have the old and new names, recognize both for now
1015 XRC_ADD_STYLE(wxSIMPLE_BORDER); XRC_ADD_STYLE(wxBORDER_SIMPLE);
1016 XRC_ADD_STYLE(wxSUNKEN_BORDER); XRC_ADD_STYLE(wxBORDER_SUNKEN);
1017 XRC_ADD_STYLE(wxDOUBLE_BORDER); XRC_ADD_STYLE(wxBORDER_DOUBLE);
1018 XRC_ADD_STYLE(wxRAISED_BORDER); XRC_ADD_STYLE(wxBORDER_RAISED);
1019 XRC_ADD_STYLE(wxSTATIC_BORDER); XRC_ADD_STYLE(wxBORDER_STATIC);
1020 XRC_ADD_STYLE(wxNO_BORDER); XRC_ADD_STYLE(wxBORDER_NONE);
1021
1022 XRC_ADD_STYLE(wxTRANSPARENT_WINDOW);
1023 XRC_ADD_STYLE(wxWANTS_CHARS);
1024 XRC_ADD_STYLE(wxTAB_TRAVERSAL);
1025 XRC_ADD_STYLE(wxNO_FULL_REPAINT_ON_RESIZE);
1026 XRC_ADD_STYLE(wxFULL_REPAINT_ON_RESIZE);
1027 XRC_ADD_STYLE(wxALWAYS_SHOW_SB);
1028 XRC_ADD_STYLE(wxWS_EX_BLOCK_EVENTS);
1029 XRC_ADD_STYLE(wxWS_EX_VALIDATE_RECURSIVELY);
1030 }
1031
1032
1033
1034 bool wxXmlResourceHandler::HasParam(const wxString& param)
1035 {
1036 return (GetParamNode(param) != NULL);
1037 }
1038
1039
1040 int wxXmlResourceHandler::GetStyle(const wxString& param, int defaults)
1041 {
1042 wxString s = GetParamValue(param);
1043
1044 if (!s) return defaults;
1045
1046 wxStringTokenizer tkn(s, wxT("| \t\n"), wxTOKEN_STRTOK);
1047 int style = 0;
1048 int index;
1049 wxString fl;
1050 while (tkn.HasMoreTokens())
1051 {
1052 fl = tkn.GetNextToken();
1053 index = m_styleNames.Index(fl);
1054 if (index != wxNOT_FOUND)
1055 {
1056 style |= m_styleValues[index];
1057 }
1058 else
1059 {
1060 ReportParamError
1061 (
1062 param,
1063 wxString::Format("unknown style flag \"%s\"", fl)
1064 );
1065 }
1066 }
1067 return style;
1068 }
1069
1070
1071
1072 wxString wxXmlResourceHandler::GetText(const wxString& param, bool translate)
1073 {
1074 wxXmlNode *parNode = GetParamNode(param);
1075 wxString str1(GetNodeContent(parNode));
1076 wxString str2;
1077
1078 // "\\" wasn't translated to "\" prior to 2.5.3.0:
1079 const bool escapeBackslash = (m_resource->CompareVersion(2,5,3,0) >= 0);
1080
1081 // VS: First version of XRC resources used $ instead of & (which is
1082 // illegal in XML), but later I realized that '_' fits this purpose
1083 // much better (because &File means "File with F underlined").
1084 const wxChar amp_char = (m_resource->CompareVersion(2,3,0,1) < 0)
1085 ? '$' : '_';
1086
1087 for ( wxString::const_iterator dt = str1.begin(); dt != str1.end(); ++dt )
1088 {
1089 // Remap amp_char to &, map double amp_char to amp_char (for things
1090 // like "&File..." -- this is illegal in XML, so we use "_File..."):
1091 if ( *dt == amp_char )
1092 {
1093 if ( *(++dt) == amp_char )
1094 str2 << amp_char;
1095 else
1096 str2 << wxT('&') << *dt;
1097 }
1098 // Remap \n to CR, \r to LF, \t to TAB, \\ to \:
1099 else if ( *dt == wxT('\\') )
1100 {
1101 switch ( (*(++dt)).GetValue() )
1102 {
1103 case wxT('n'):
1104 str2 << wxT('\n');
1105 break;
1106
1107 case wxT('t'):
1108 str2 << wxT('\t');
1109 break;
1110
1111 case wxT('r'):
1112 str2 << wxT('\r');
1113 break;
1114
1115 case wxT('\\') :
1116 // "\\" wasn't translated to "\" prior to 2.5.3.0:
1117 if ( escapeBackslash )
1118 {
1119 str2 << wxT('\\');
1120 break;
1121 }
1122 // else fall-through to default: branch below
1123
1124 default:
1125 str2 << wxT('\\') << *dt;
1126 break;
1127 }
1128 }
1129 else
1130 {
1131 str2 << *dt;
1132 }
1133 }
1134
1135 if (m_resource->GetFlags() & wxXRC_USE_LOCALE)
1136 {
1137 if (translate && parNode &&
1138 parNode->GetAttribute(wxT("translate"), wxEmptyString) != wxT("0"))
1139 {
1140 return wxGetTranslation(str2, m_resource->GetDomain());
1141 }
1142 else
1143 {
1144 #if wxUSE_UNICODE
1145 return str2;
1146 #else
1147 // The string is internally stored as UTF-8, we have to convert
1148 // it into system's default encoding so that it can be displayed:
1149 return wxString(str2.wc_str(wxConvUTF8), wxConvLocal);
1150 #endif
1151 }
1152 }
1153
1154 // If wxXRC_USE_LOCALE is not set, then the string is already in
1155 // system's default encoding in ANSI build, so we don't have to
1156 // do anything special here.
1157 return str2;
1158 }
1159
1160
1161
1162 long wxXmlResourceHandler::GetLong(const wxString& param, long defaultv)
1163 {
1164 long value;
1165 wxString str1 = GetParamValue(param);
1166
1167 if (!str1.ToLong(&value))
1168 value = defaultv;
1169
1170 return value;
1171 }
1172
1173 float wxXmlResourceHandler::GetFloat(const wxString& param, float defaultv)
1174 {
1175 wxString str = GetParamValue(param);
1176
1177 #if wxUSE_INTL
1178 // strings in XRC always use C locale but wxString::ToDouble() uses the
1179 // current one, so transform the string to it supposing that the only
1180 // difference between them is the decimal separator
1181 //
1182 // TODO: use wxString::ToCDouble() when we have it
1183 str.Replace(wxT("."), wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT,
1184 wxLOCALE_CAT_NUMBER));
1185 #endif // wxUSE_INTL
1186
1187 double value;
1188 if (!str.ToDouble(&value))
1189 value = defaultv;
1190
1191 return wx_truncate_cast(float, value);
1192 }
1193
1194
1195 int wxXmlResourceHandler::GetID()
1196 {
1197 return wxXmlResource::GetXRCID(GetName());
1198 }
1199
1200
1201
1202 wxString wxXmlResourceHandler::GetName()
1203 {
1204 return m_node->GetAttribute(wxT("name"), wxT("-1"));
1205 }
1206
1207
1208
1209 bool wxXmlResourceHandler::GetBoolAttr(const wxString& attr, bool defaultv)
1210 {
1211 wxString v;
1212 return m_node->GetAttribute(attr, &v) ? v == '1' : defaultv;
1213 }
1214
1215 bool wxXmlResourceHandler::GetBool(const wxString& param, bool defaultv)
1216 {
1217 const wxString v = GetParamValue(param);
1218
1219 return v.empty() ? defaultv : (v == '1');
1220 }
1221
1222
1223 static wxColour GetSystemColour(const wxString& name)
1224 {
1225 if (!name.empty())
1226 {
1227 #define SYSCLR(clr) \
1228 if (name == _T(#clr)) return wxSystemSettings::GetColour(clr);
1229 SYSCLR(wxSYS_COLOUR_SCROLLBAR)
1230 SYSCLR(wxSYS_COLOUR_BACKGROUND)
1231 SYSCLR(wxSYS_COLOUR_DESKTOP)
1232 SYSCLR(wxSYS_COLOUR_ACTIVECAPTION)
1233 SYSCLR(wxSYS_COLOUR_INACTIVECAPTION)
1234 SYSCLR(wxSYS_COLOUR_MENU)
1235 SYSCLR(wxSYS_COLOUR_WINDOW)
1236 SYSCLR(wxSYS_COLOUR_WINDOWFRAME)
1237 SYSCLR(wxSYS_COLOUR_MENUTEXT)
1238 SYSCLR(wxSYS_COLOUR_WINDOWTEXT)
1239 SYSCLR(wxSYS_COLOUR_CAPTIONTEXT)
1240 SYSCLR(wxSYS_COLOUR_ACTIVEBORDER)
1241 SYSCLR(wxSYS_COLOUR_INACTIVEBORDER)
1242 SYSCLR(wxSYS_COLOUR_APPWORKSPACE)
1243 SYSCLR(wxSYS_COLOUR_HIGHLIGHT)
1244 SYSCLR(wxSYS_COLOUR_HIGHLIGHTTEXT)
1245 SYSCLR(wxSYS_COLOUR_BTNFACE)
1246 SYSCLR(wxSYS_COLOUR_3DFACE)
1247 SYSCLR(wxSYS_COLOUR_BTNSHADOW)
1248 SYSCLR(wxSYS_COLOUR_3DSHADOW)
1249 SYSCLR(wxSYS_COLOUR_GRAYTEXT)
1250 SYSCLR(wxSYS_COLOUR_BTNTEXT)
1251 SYSCLR(wxSYS_COLOUR_INACTIVECAPTIONTEXT)
1252 SYSCLR(wxSYS_COLOUR_BTNHIGHLIGHT)
1253 SYSCLR(wxSYS_COLOUR_BTNHILIGHT)
1254 SYSCLR(wxSYS_COLOUR_3DHIGHLIGHT)
1255 SYSCLR(wxSYS_COLOUR_3DHILIGHT)
1256 SYSCLR(wxSYS_COLOUR_3DDKSHADOW)
1257 SYSCLR(wxSYS_COLOUR_3DLIGHT)
1258 SYSCLR(wxSYS_COLOUR_INFOTEXT)
1259 SYSCLR(wxSYS_COLOUR_INFOBK)
1260 SYSCLR(wxSYS_COLOUR_LISTBOX)
1261 SYSCLR(wxSYS_COLOUR_HOTLIGHT)
1262 SYSCLR(wxSYS_COLOUR_GRADIENTACTIVECAPTION)
1263 SYSCLR(wxSYS_COLOUR_GRADIENTINACTIVECAPTION)
1264 SYSCLR(wxSYS_COLOUR_MENUHILIGHT)
1265 SYSCLR(wxSYS_COLOUR_MENUBAR)
1266 #undef SYSCLR
1267 }
1268
1269 return wxNullColour;
1270 }
1271
1272 wxColour wxXmlResourceHandler::GetColour(const wxString& param, const wxColour& defaultv)
1273 {
1274 wxString v = GetParamValue(param);
1275
1276 if ( v.empty() )
1277 return defaultv;
1278
1279 wxColour clr;
1280
1281 // wxString -> wxColour conversion
1282 if (!clr.Set(v))
1283 {
1284 // the colour doesn't use #RRGGBB format, check if it is symbolic
1285 // colour name:
1286 clr = GetSystemColour(v);
1287 if (clr.Ok())
1288 return clr;
1289
1290 ReportParamError
1291 (
1292 param,
1293 wxString::Format("incorrect colour specification \"%s\"", v)
1294 );
1295 return wxNullColour;
1296 }
1297
1298 return clr;
1299 }
1300
1301 namespace
1302 {
1303
1304 // if 'param' has stock_id/stock_client, extracts them and returns true
1305 bool GetStockArtAttrs(const wxXmlNode *paramNode,
1306 const wxString& defaultArtClient,
1307 wxString& art_id, wxString& art_client)
1308 {
1309 if ( paramNode )
1310 {
1311 art_id = paramNode->GetAttribute("stock_id", "");
1312
1313 if ( !art_id.empty() )
1314 {
1315 art_id = wxART_MAKE_ART_ID_FROM_STR(art_id);
1316
1317 art_client = paramNode->GetAttribute("stock_client", "");
1318 if ( art_client.empty() )
1319 art_client = defaultArtClient;
1320 else
1321 art_client = wxART_MAKE_CLIENT_ID_FROM_STR(art_client);
1322
1323 return true;
1324 }
1325 }
1326
1327 return false;
1328 }
1329
1330 } // anonymous namespace
1331
1332 wxBitmap wxXmlResourceHandler::GetBitmap(const wxString& param,
1333 const wxArtClient& defaultArtClient,
1334 wxSize size)
1335 {
1336 /* If the bitmap is specified as stock item, query wxArtProvider for it: */
1337 wxString art_id, art_client;
1338 if ( GetStockArtAttrs(GetParamNode(param), defaultArtClient,
1339 art_id, art_client) )
1340 {
1341 wxBitmap stockArt(wxArtProvider::GetBitmap(art_id, art_client, size));
1342 if ( stockArt.Ok() )
1343 return stockArt;
1344 }
1345
1346 /* ...or load the bitmap from file: */
1347 wxString name = GetParamValue(param);
1348 if (name.empty()) return wxNullBitmap;
1349 #if wxUSE_FILESYSTEM
1350 wxFSFile *fsfile = GetCurFileSystem().OpenFile(name, wxFS_READ | wxFS_SEEKABLE);
1351 if (fsfile == NULL)
1352 {
1353 ReportParamError
1354 (
1355 param,
1356 wxString::Format("cannot open bitmap resource \"%s\"", name)
1357 );
1358 return wxNullBitmap;
1359 }
1360 wxImage img(*(fsfile->GetStream()));
1361 delete fsfile;
1362 #else
1363 wxImage img(name);
1364 #endif
1365
1366 if (!img.Ok())
1367 {
1368 ReportParamError
1369 (
1370 param,
1371 wxString::Format("cannot create bitmap from \"%s\"", name)
1372 );
1373 return wxNullBitmap;
1374 }
1375 if (!(size == wxDefaultSize)) img.Rescale(size.x, size.y);
1376 return wxBitmap(img);
1377 }
1378
1379
1380 wxIcon wxXmlResourceHandler::GetIcon(const wxString& param,
1381 const wxArtClient& defaultArtClient,
1382 wxSize size)
1383 {
1384 wxIcon icon;
1385 icon.CopyFromBitmap(GetBitmap(param, defaultArtClient, size));
1386 return icon;
1387 }
1388
1389 wxIconBundle wxXmlResourceHandler::GetIconBundle(const wxString& param,
1390 const wxArtClient& defaultArtClient)
1391 {
1392 wxString art_id, art_client;
1393 if ( GetStockArtAttrs(GetParamNode(param), defaultArtClient,
1394 art_id, art_client) )
1395 {
1396 wxIconBundle stockArt(wxArtProvider::GetIconBundle(art_id, art_client));
1397 if ( stockArt.IsOk() )
1398 return stockArt;
1399 }
1400
1401 const wxString name = GetParamValue(param);
1402 if ( name.empty() )
1403 return wxNullIconBundle;
1404
1405 #if wxUSE_FILESYSTEM
1406 wxFSFile *fsfile = GetCurFileSystem().OpenFile(name, wxFS_READ | wxFS_SEEKABLE);
1407 if ( fsfile == NULL )
1408 {
1409 ReportParamError
1410 (
1411 param,
1412 wxString::Format("cannot open icon resource \"%s\"", name)
1413 );
1414 return wxNullIconBundle;
1415 }
1416
1417 wxIconBundle bundle(*(fsfile->GetStream()));
1418 delete fsfile;
1419 #else
1420 wxIconBundle bundle(name);
1421 #endif
1422
1423 if ( !bundle.IsOk() )
1424 {
1425 ReportParamError
1426 (
1427 param,
1428 wxString::Format("cannot create icon from \"%s\"", name)
1429 );
1430 return wxNullIconBundle;
1431 }
1432
1433 return bundle;
1434 }
1435
1436
1437 wxXmlNode *wxXmlResourceHandler::GetParamNode(const wxString& param)
1438 {
1439 wxCHECK_MSG(m_node, NULL, wxT("You can't access handler data before it was initialized!"));
1440
1441 wxXmlNode *n = m_node->GetChildren();
1442
1443 while (n)
1444 {
1445 if (n->GetType() == wxXML_ELEMENT_NODE && n->GetName() == param)
1446 {
1447 // TODO: check that there are no other properties/parameters with
1448 // the same name and log an error if there are (can't do this
1449 // right now as I'm not sure if it's not going to break code
1450 // using this function in unintentional way (i.e. for
1451 // accessing other things than properties), for example
1452 // wxBitmapComboBoxXmlHandler almost surely does
1453 return n;
1454 }
1455 n = n->GetNext();
1456 }
1457 return NULL;
1458 }
1459
1460 bool wxXmlResourceHandler::IsOfClass(wxXmlNode *node, const wxString& classname)
1461 {
1462 return node->GetAttribute(wxT("class"), wxEmptyString) == classname;
1463 }
1464
1465
1466
1467 wxString wxXmlResourceHandler::GetNodeContent(wxXmlNode *node)
1468 {
1469 wxXmlNode *n = node;
1470 if (n == NULL) return wxEmptyString;
1471 n = n->GetChildren();
1472
1473 while (n)
1474 {
1475 if (n->GetType() == wxXML_TEXT_NODE ||
1476 n->GetType() == wxXML_CDATA_SECTION_NODE)
1477 return n->GetContent();
1478 n = n->GetNext();
1479 }
1480 return wxEmptyString;
1481 }
1482
1483
1484
1485 wxString wxXmlResourceHandler::GetParamValue(const wxString& param)
1486 {
1487 if (param.empty())
1488 return GetNodeContent(m_node);
1489 else
1490 return GetNodeContent(GetParamNode(param));
1491 }
1492
1493
1494
1495 wxSize wxXmlResourceHandler::GetSize(const wxString& param,
1496 wxWindow *windowToUse)
1497 {
1498 wxString s = GetParamValue(param);
1499 if (s.empty()) s = wxT("-1,-1");
1500 bool is_dlg;
1501 long sx, sy = 0;
1502
1503 is_dlg = s[s.length()-1] == wxT('d');
1504 if (is_dlg) s.RemoveLast();
1505
1506 if (!s.BeforeFirst(wxT(',')).ToLong(&sx) ||
1507 !s.AfterLast(wxT(',')).ToLong(&sy))
1508 {
1509 ReportParamError
1510 (
1511 param,
1512 wxString::Format("cannot parse coordinates value \"%s\"", s)
1513 );
1514 return wxDefaultSize;
1515 }
1516
1517 if (is_dlg)
1518 {
1519 if (windowToUse)
1520 {
1521 return wxDLG_UNIT(windowToUse, wxSize(sx, sy));
1522 }
1523 else if (m_parentAsWindow)
1524 {
1525 return wxDLG_UNIT(m_parentAsWindow, wxSize(sx, sy));
1526 }
1527 else
1528 {
1529 ReportParamError
1530 (
1531 param,
1532 "cannot convert dialog units: dialog unknown"
1533 );
1534 return wxDefaultSize;
1535 }
1536 }
1537
1538 return wxSize(sx, sy);
1539 }
1540
1541
1542
1543 wxPoint wxXmlResourceHandler::GetPosition(const wxString& param)
1544 {
1545 wxSize sz = GetSize(param);
1546 return wxPoint(sz.x, sz.y);
1547 }
1548
1549
1550
1551 wxCoord wxXmlResourceHandler::GetDimension(const wxString& param,
1552 wxCoord defaultv,
1553 wxWindow *windowToUse)
1554 {
1555 wxString s = GetParamValue(param);
1556 if (s.empty()) return defaultv;
1557 bool is_dlg;
1558 long sx;
1559
1560 is_dlg = s[s.length()-1] == wxT('d');
1561 if (is_dlg) s.RemoveLast();
1562
1563 if (!s.ToLong(&sx))
1564 {
1565 ReportParamError
1566 (
1567 param,
1568 wxString::Format("cannot parse dimension value \"%s\"", s)
1569 );
1570 return defaultv;
1571 }
1572
1573 if (is_dlg)
1574 {
1575 if (windowToUse)
1576 {
1577 return wxDLG_UNIT(windowToUse, wxSize(sx, 0)).x;
1578 }
1579 else if (m_parentAsWindow)
1580 {
1581 return wxDLG_UNIT(m_parentAsWindow, wxSize(sx, 0)).x;
1582 }
1583 else
1584 {
1585 ReportParamError
1586 (
1587 param,
1588 "cannot convert dialog units: dialog unknown"
1589 );
1590 return defaultv;
1591 }
1592 }
1593
1594 return sx;
1595 }
1596
1597
1598 // Get system font index using indexname
1599 static wxFont GetSystemFont(const wxString& name)
1600 {
1601 if (!name.empty())
1602 {
1603 #define SYSFNT(fnt) \
1604 if (name == _T(#fnt)) return wxSystemSettings::GetFont(fnt);
1605 SYSFNT(wxSYS_OEM_FIXED_FONT)
1606 SYSFNT(wxSYS_ANSI_FIXED_FONT)
1607 SYSFNT(wxSYS_ANSI_VAR_FONT)
1608 SYSFNT(wxSYS_SYSTEM_FONT)
1609 SYSFNT(wxSYS_DEVICE_DEFAULT_FONT)
1610 SYSFNT(wxSYS_SYSTEM_FIXED_FONT)
1611 SYSFNT(wxSYS_DEFAULT_GUI_FONT)
1612 #undef SYSFNT
1613 }
1614
1615 return wxNullFont;
1616 }
1617
1618 wxFont wxXmlResourceHandler::GetFont(const wxString& param)
1619 {
1620 wxXmlNode *font_node = GetParamNode(param);
1621 if (font_node == NULL)
1622 {
1623 ReportError(
1624 wxString::Format("cannot find font node \"%s\"", param));
1625 return wxNullFont;
1626 }
1627
1628 wxXmlNode *oldnode = m_node;
1629 m_node = font_node;
1630
1631 // font attributes:
1632
1633 // size
1634 int isize = -1;
1635 bool hasSize = HasParam(wxT("size"));
1636 if (hasSize)
1637 isize = GetLong(wxT("size"), -1);
1638
1639 // style
1640 int istyle = wxNORMAL;
1641 bool hasStyle = HasParam(wxT("style"));
1642 if (hasStyle)
1643 {
1644 wxString style = GetParamValue(wxT("style"));
1645 if (style == wxT("italic"))
1646 istyle = wxITALIC;
1647 else if (style == wxT("slant"))
1648 istyle = wxSLANT;
1649 }
1650
1651 // weight
1652 int iweight = wxNORMAL;
1653 bool hasWeight = HasParam(wxT("weight"));
1654 if (hasWeight)
1655 {
1656 wxString weight = GetParamValue(wxT("weight"));
1657 if (weight == wxT("bold"))
1658 iweight = wxBOLD;
1659 else if (weight == wxT("light"))
1660 iweight = wxLIGHT;
1661 }
1662
1663 // underline
1664 bool hasUnderlined = HasParam(wxT("underlined"));
1665 bool underlined = hasUnderlined ? GetBool(wxT("underlined"), false) : false;
1666
1667 // family and facename
1668 int ifamily = wxDEFAULT;
1669 bool hasFamily = HasParam(wxT("family"));
1670 if (hasFamily)
1671 {
1672 wxString family = GetParamValue(wxT("family"));
1673 if (family == wxT("decorative")) ifamily = wxDECORATIVE;
1674 else if (family == wxT("roman")) ifamily = wxROMAN;
1675 else if (family == wxT("script")) ifamily = wxSCRIPT;
1676 else if (family == wxT("swiss")) ifamily = wxSWISS;
1677 else if (family == wxT("modern")) ifamily = wxMODERN;
1678 else if (family == wxT("teletype")) ifamily = wxTELETYPE;
1679 }
1680
1681
1682 wxString facename;
1683 bool hasFacename = HasParam(wxT("face"));
1684 if (hasFacename)
1685 {
1686 wxString faces = GetParamValue(wxT("face"));
1687 wxStringTokenizer tk(faces, wxT(","));
1688 #if wxUSE_FONTENUM
1689 wxArrayString facenames(wxFontEnumerator::GetFacenames());
1690 while (tk.HasMoreTokens())
1691 {
1692 int index = facenames.Index(tk.GetNextToken(), false);
1693 if (index != wxNOT_FOUND)
1694 {
1695 facename = facenames[index];
1696 break;
1697 }
1698 }
1699 #else // !wxUSE_FONTENUM
1700 // just use the first face name if we can't check its availability:
1701 if (tk.HasMoreTokens())
1702 facename = tk.GetNextToken();
1703 #endif // wxUSE_FONTENUM/!wxUSE_FONTENUM
1704 }
1705
1706 // encoding
1707 wxFontEncoding enc = wxFONTENCODING_DEFAULT;
1708 bool hasEncoding = HasParam(wxT("encoding"));
1709 if (hasEncoding)
1710 {
1711 wxString encoding = GetParamValue(wxT("encoding"));
1712 wxFontMapper mapper;
1713 if (!encoding.empty())
1714 enc = mapper.CharsetToEncoding(encoding);
1715 if (enc == wxFONTENCODING_SYSTEM)
1716 enc = wxFONTENCODING_DEFAULT;
1717 }
1718
1719 // is this font based on a system font?
1720 wxFont font = GetSystemFont(GetParamValue(wxT("sysfont")));
1721
1722 if (font.Ok())
1723 {
1724 if (hasSize && isize != -1)
1725 font.SetPointSize(isize);
1726 else if (HasParam(wxT("relativesize")))
1727 font.SetPointSize(int(font.GetPointSize() *
1728 GetFloat(wxT("relativesize"))));
1729
1730 if (hasStyle)
1731 font.SetStyle(istyle);
1732 if (hasWeight)
1733 font.SetWeight(iweight);
1734 if (hasUnderlined)
1735 font.SetUnderlined(underlined);
1736 if (hasFamily)
1737 font.SetFamily(ifamily);
1738 if (hasFacename)
1739 font.SetFaceName(facename);
1740 if (hasEncoding)
1741 font.SetDefaultEncoding(enc);
1742 }
1743 else // not based on system font
1744 {
1745 font = wxFont(isize == -1 ? wxNORMAL_FONT->GetPointSize() : isize,
1746 ifamily, istyle, iweight,
1747 underlined, facename, enc);
1748 }
1749
1750 m_node = oldnode;
1751 return font;
1752 }
1753
1754
1755 void wxXmlResourceHandler::SetupWindow(wxWindow *wnd)
1756 {
1757 //FIXME : add cursor
1758
1759 if (HasParam(wxT("exstyle")))
1760 // Have to OR it with existing style, since
1761 // some implementations (e.g. wxGTK) use the extra style
1762 // during creation
1763 wnd->SetExtraStyle(wnd->GetExtraStyle() | GetStyle(wxT("exstyle")));
1764 if (HasParam(wxT("bg")))
1765 wnd->SetBackgroundColour(GetColour(wxT("bg")));
1766 if (HasParam(wxT("fg")))
1767 wnd->SetForegroundColour(GetColour(wxT("fg")));
1768 if (GetBool(wxT("enabled"), 1) == 0)
1769 wnd->Enable(false);
1770 if (GetBool(wxT("focused"), 0) == 1)
1771 wnd->SetFocus();
1772 if (GetBool(wxT("hidden"), 0) == 1)
1773 wnd->Show(false);
1774 #if wxUSE_TOOLTIPS
1775 if (HasParam(wxT("tooltip")))
1776 wnd->SetToolTip(GetText(wxT("tooltip")));
1777 #endif
1778 if (HasParam(wxT("font")))
1779 wnd->SetFont(GetFont());
1780 if (HasParam(wxT("help")))
1781 wnd->SetHelpText(GetText(wxT("help")));
1782 }
1783
1784
1785 void wxXmlResourceHandler::CreateChildren(wxObject *parent, bool this_hnd_only)
1786 {
1787 for ( wxXmlNode *n = m_node->GetChildren(); n; n = n->GetNext() )
1788 {
1789 if ( IsObjectNode(n) )
1790 {
1791 m_resource->CreateResFromNode(n, parent, NULL,
1792 this_hnd_only ? this : NULL);
1793 }
1794 }
1795 }
1796
1797
1798 void wxXmlResourceHandler::CreateChildrenPrivately(wxObject *parent, wxXmlNode *rootnode)
1799 {
1800 wxXmlNode *root;
1801 if (rootnode == NULL) root = m_node; else root = rootnode;
1802 wxXmlNode *n = root->GetChildren();
1803
1804 while (n)
1805 {
1806 if (n->GetType() == wxXML_ELEMENT_NODE && CanHandle(n))
1807 {
1808 CreateResource(n, parent, NULL);
1809 }
1810 n = n->GetNext();
1811 }
1812 }
1813
1814
1815 //-----------------------------------------------------------------------------
1816 // errors reporting
1817 //-----------------------------------------------------------------------------
1818
1819 void wxXmlResourceHandler::ReportError(const wxString& message)
1820 {
1821 m_resource->ReportError(m_node, message);
1822 }
1823
1824 void wxXmlResourceHandler::ReportError(wxXmlNode *context,
1825 const wxString& message)
1826 {
1827 m_resource->ReportError(context ? context : m_node, message);
1828 }
1829
1830 void wxXmlResourceHandler::ReportParamError(const wxString& param,
1831 const wxString& message)
1832 {
1833 m_resource->ReportError(GetParamNode(param), message);
1834 }
1835
1836 void wxXmlResource::ReportError(wxXmlNode *context, const wxString& message)
1837 {
1838 if ( !context )
1839 {
1840 DoReportError("", NULL, message);
1841 return;
1842 }
1843
1844 // We need to find out the file that 'context' is part of. Performance of
1845 // this code is not critical, so we simply find the root XML node and
1846 // compare it with all loaded XRC files.
1847 const wxString filename = GetFileNameFromNode(context, Data());
1848
1849 DoReportError(filename, context, message);
1850 }
1851
1852 void wxXmlResource::DoReportError(const wxString& xrcFile, wxXmlNode *position,
1853 const wxString& message)
1854 {
1855 const int line = position ? position->GetLineNumber() : -1;
1856
1857 wxString loc;
1858 if ( !xrcFile.empty() )
1859 loc = xrcFile + ':';
1860 if ( line != -1 )
1861 loc += wxString::Format("%d:", line);
1862 if ( !loc.empty() )
1863 loc += ' ';
1864
1865 wxLogError("XRC error: %s%s", loc, message);
1866 }
1867
1868
1869 //-----------------------------------------------------------------------------
1870 // XRCID implementation
1871 //-----------------------------------------------------------------------------
1872
1873 #define XRCID_TABLE_SIZE 1024
1874
1875
1876 struct XRCID_record
1877 {
1878 /* Hold the id so that once an id is allocated for a name, it
1879 does not get created again by NewControlId at least
1880 until we are done with it */
1881 wxWindowIDRef id;
1882 char *key;
1883 XRCID_record *next;
1884 };
1885
1886 static XRCID_record *XRCID_Records[XRCID_TABLE_SIZE] = {NULL};
1887
1888 static int XRCID_Lookup(const char *str_id, int value_if_not_found = wxID_NONE)
1889 {
1890 int index = 0;
1891
1892 for (const char *c = str_id; *c != '\0'; c++) index += (int)*c;
1893 index %= XRCID_TABLE_SIZE;
1894
1895 XRCID_record *oldrec = NULL;
1896 for (XRCID_record *rec = XRCID_Records[index]; rec; rec = rec->next)
1897 {
1898 if (wxStrcmp(rec->key, str_id) == 0)
1899 {
1900 return rec->id;
1901 }
1902 oldrec = rec;
1903 }
1904
1905 XRCID_record **rec_var = (oldrec == NULL) ?
1906 &XRCID_Records[index] : &oldrec->next;
1907 *rec_var = new XRCID_record;
1908 (*rec_var)->key = wxStrdup(str_id);
1909 (*rec_var)->next = NULL;
1910
1911 char *end;
1912 if (value_if_not_found != wxID_NONE)
1913 (*rec_var)->id = value_if_not_found;
1914 else
1915 {
1916 int asint = wxStrtol(str_id, &end, 10);
1917 if (*str_id && *end == 0)
1918 {
1919 // if str_id was integer, keep it verbosely:
1920 (*rec_var)->id = asint;
1921 }
1922 else
1923 {
1924 (*rec_var)->id = wxWindowBase::NewControlId();
1925 }
1926 }
1927
1928 return (*rec_var)->id;
1929 }
1930
1931 static void AddStdXRCID_Records();
1932
1933 /*static*/
1934 int wxXmlResource::DoGetXRCID(const char *str_id, int value_if_not_found)
1935 {
1936 static bool s_stdIDsAdded = false;
1937
1938 if ( !s_stdIDsAdded )
1939 {
1940 s_stdIDsAdded = true;
1941 AddStdXRCID_Records();
1942 }
1943
1944 return XRCID_Lookup(str_id, value_if_not_found);
1945 }
1946
1947 /* static */
1948 wxString wxXmlResource::FindXRCIDById(int numId)
1949 {
1950 for ( int i = 0; i < XRCID_TABLE_SIZE; i++ )
1951 {
1952 for ( XRCID_record *rec = XRCID_Records[i]; rec; rec = rec->next )
1953 {
1954 if ( rec->id == numId )
1955 return wxString(rec->key);
1956 }
1957 }
1958
1959 return wxString();
1960 }
1961
1962 static void CleanXRCID_Record(XRCID_record *rec)
1963 {
1964 if (rec)
1965 {
1966 CleanXRCID_Record(rec->next);
1967
1968 free(rec->key);
1969 delete rec;
1970 }
1971 }
1972
1973 static void CleanXRCID_Records()
1974 {
1975 for (int i = 0; i < XRCID_TABLE_SIZE; i++)
1976 {
1977 CleanXRCID_Record(XRCID_Records[i]);
1978 XRCID_Records[i] = NULL;
1979 }
1980 }
1981
1982 static void AddStdXRCID_Records()
1983 {
1984 #define stdID(id) XRCID_Lookup(#id, id)
1985 stdID(-1);
1986
1987 stdID(wxID_ANY);
1988 stdID(wxID_SEPARATOR);
1989
1990 stdID(wxID_OPEN);
1991 stdID(wxID_CLOSE);
1992 stdID(wxID_NEW);
1993 stdID(wxID_SAVE);
1994 stdID(wxID_SAVEAS);
1995 stdID(wxID_REVERT);
1996 stdID(wxID_EXIT);
1997 stdID(wxID_UNDO);
1998 stdID(wxID_REDO);
1999 stdID(wxID_HELP);
2000 stdID(wxID_PRINT);
2001 stdID(wxID_PRINT_SETUP);
2002 stdID(wxID_PAGE_SETUP);
2003 stdID(wxID_PREVIEW);
2004 stdID(wxID_ABOUT);
2005 stdID(wxID_HELP_CONTENTS);
2006 stdID(wxID_HELP_COMMANDS);
2007 stdID(wxID_HELP_PROCEDURES);
2008 stdID(wxID_HELP_CONTEXT);
2009 stdID(wxID_CLOSE_ALL);
2010 stdID(wxID_PREFERENCES);
2011 stdID(wxID_EDIT);
2012 stdID(wxID_CUT);
2013 stdID(wxID_COPY);
2014 stdID(wxID_PASTE);
2015 stdID(wxID_CLEAR);
2016 stdID(wxID_FIND);
2017 stdID(wxID_DUPLICATE);
2018 stdID(wxID_SELECTALL);
2019 stdID(wxID_DELETE);
2020 stdID(wxID_REPLACE);
2021 stdID(wxID_REPLACE_ALL);
2022 stdID(wxID_PROPERTIES);
2023 stdID(wxID_VIEW_DETAILS);
2024 stdID(wxID_VIEW_LARGEICONS);
2025 stdID(wxID_VIEW_SMALLICONS);
2026 stdID(wxID_VIEW_LIST);
2027 stdID(wxID_VIEW_SORTDATE);
2028 stdID(wxID_VIEW_SORTNAME);
2029 stdID(wxID_VIEW_SORTSIZE);
2030 stdID(wxID_VIEW_SORTTYPE);
2031 stdID(wxID_FILE1);
2032 stdID(wxID_FILE2);
2033 stdID(wxID_FILE3);
2034 stdID(wxID_FILE4);
2035 stdID(wxID_FILE5);
2036 stdID(wxID_FILE6);
2037 stdID(wxID_FILE7);
2038 stdID(wxID_FILE8);
2039 stdID(wxID_FILE9);
2040 stdID(wxID_OK);
2041 stdID(wxID_CANCEL);
2042 stdID(wxID_APPLY);
2043 stdID(wxID_YES);
2044 stdID(wxID_NO);
2045 stdID(wxID_STATIC);
2046 stdID(wxID_FORWARD);
2047 stdID(wxID_BACKWARD);
2048 stdID(wxID_DEFAULT);
2049 stdID(wxID_MORE);
2050 stdID(wxID_SETUP);
2051 stdID(wxID_RESET);
2052 stdID(wxID_CONTEXT_HELP);
2053 stdID(wxID_YESTOALL);
2054 stdID(wxID_NOTOALL);
2055 stdID(wxID_ABORT);
2056 stdID(wxID_RETRY);
2057 stdID(wxID_IGNORE);
2058 stdID(wxID_ADD);
2059 stdID(wxID_REMOVE);
2060 stdID(wxID_UP);
2061 stdID(wxID_DOWN);
2062 stdID(wxID_HOME);
2063 stdID(wxID_REFRESH);
2064 stdID(wxID_STOP);
2065 stdID(wxID_INDEX);
2066 stdID(wxID_BOLD);
2067 stdID(wxID_ITALIC);
2068 stdID(wxID_JUSTIFY_CENTER);
2069 stdID(wxID_JUSTIFY_FILL);
2070 stdID(wxID_JUSTIFY_RIGHT);
2071 stdID(wxID_JUSTIFY_LEFT);
2072 stdID(wxID_UNDERLINE);
2073 stdID(wxID_INDENT);
2074 stdID(wxID_UNINDENT);
2075 stdID(wxID_ZOOM_100);
2076 stdID(wxID_ZOOM_FIT);
2077 stdID(wxID_ZOOM_IN);
2078 stdID(wxID_ZOOM_OUT);
2079 stdID(wxID_UNDELETE);
2080 stdID(wxID_REVERT_TO_SAVED);
2081 stdID(wxID_SYSTEM_MENU);
2082 stdID(wxID_CLOSE_FRAME);
2083 stdID(wxID_MOVE_FRAME);
2084 stdID(wxID_RESIZE_FRAME);
2085 stdID(wxID_MAXIMIZE_FRAME);
2086 stdID(wxID_ICONIZE_FRAME);
2087 stdID(wxID_RESTORE_FRAME);
2088 stdID(wxID_CDROM);
2089 stdID(wxID_CONVERT);
2090 stdID(wxID_EXECUTE);
2091 stdID(wxID_FLOPPY);
2092 stdID(wxID_HARDDISK);
2093 stdID(wxID_BOTTOM);
2094 stdID(wxID_FIRST);
2095 stdID(wxID_LAST);
2096 stdID(wxID_TOP);
2097 stdID(wxID_INFO);
2098 stdID(wxID_JUMP_TO);
2099 stdID(wxID_NETWORK);
2100 stdID(wxID_SELECT_COLOR);
2101 stdID(wxID_SELECT_FONT);
2102 stdID(wxID_SORT_ASCENDING);
2103 stdID(wxID_SORT_DESCENDING);
2104 stdID(wxID_SPELL_CHECK);
2105 stdID(wxID_STRIKETHROUGH);
2106
2107 #undef stdID
2108 }
2109
2110
2111
2112
2113
2114 //-----------------------------------------------------------------------------
2115 // module and globals
2116 //-----------------------------------------------------------------------------
2117
2118 // normally we would do the cleanup from wxXmlResourceModule::OnExit() but it
2119 // can happen that some XRC records have been created because of the use of
2120 // XRCID() in event tables, which happens during static objects initialization,
2121 // but then the application initialization failed and so the wx modules were
2122 // neither initialized nor cleaned up -- this static object does the cleanup in
2123 // this case
2124 static struct wxXRCStaticCleanup
2125 {
2126 ~wxXRCStaticCleanup() { CleanXRCID_Records(); }
2127 } s_staticCleanup;
2128
2129 class wxXmlResourceModule: public wxModule
2130 {
2131 DECLARE_DYNAMIC_CLASS(wxXmlResourceModule)
2132 public:
2133 wxXmlResourceModule() {}
2134 bool OnInit()
2135 {
2136 wxXmlResource::AddSubclassFactory(new wxXmlSubclassFactoryCXX);
2137 return true;
2138 }
2139 void OnExit()
2140 {
2141 delete wxXmlResource::Set(NULL);
2142 if(wxXmlResource::ms_subclassFactories)
2143 {
2144 for ( wxXmlSubclassFactories::iterator i = wxXmlResource::ms_subclassFactories->begin();
2145 i != wxXmlResource::ms_subclassFactories->end(); ++i )
2146 {
2147 delete *i;
2148 }
2149 wxDELETE(wxXmlResource::ms_subclassFactories);
2150 }
2151 CleanXRCID_Records();
2152 }
2153 };
2154
2155 IMPLEMENT_DYNAMIC_CLASS(wxXmlResourceModule, wxModule)
2156
2157
2158 // When wxXml is loaded dynamically after the application is already running
2159 // then the built-in module system won't pick this one up. Add it manually.
2160 void wxXmlInitResourceModule()
2161 {
2162 wxModule* module = new wxXmlResourceModule;
2163 module->Init();
2164 wxModule::RegisterModule(module);
2165 }
2166
2167 #endif // wxUSE_XRC