return false from wxXmlResource::Load if the resource is corrupted
[wxWidgets.git] / src / xrc / xmlres.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: 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 #ifdef __GNUG__
12 #pragma implementation "xmlres.h"
13 #endif
14
15 // For compilers that support precompilation, includes "wx.h".
16 #include "wx/wxprec.h"
17
18 #ifdef __BORLANDC__
19 #pragma hdrstop
20 #endif
21
22 #include "wx/dialog.h"
23 #include "wx/panel.h"
24 #include "wx/frame.h"
25 #include "wx/wfstream.h"
26 #include "wx/filesys.h"
27 #include "wx/filename.h"
28 #include "wx/log.h"
29 #include "wx/intl.h"
30 #include "wx/tokenzr.h"
31 #include "wx/fontenum.h"
32 #include "wx/module.h"
33 #include "wx/bitmap.h"
34 #include "wx/image.h"
35 #include "wx/fontmap.h"
36 #include "wx/artprov.h"
37
38 #include "wx/xml/xml.h"
39 #include "wx/xrc/xmlres.h"
40
41 #include "wx/arrimpl.cpp"
42 WX_DEFINE_OBJARRAY(wxXmlResourceDataRecords);
43
44
45 wxXmlResource *wxXmlResource::ms_instance = NULL;
46
47 /*static*/ wxXmlResource *wxXmlResource::Get()
48 {
49 if ( !ms_instance )
50 ms_instance = new wxXmlResource;
51 return ms_instance;
52 }
53
54 /*static*/ wxXmlResource *wxXmlResource::Set(wxXmlResource *res)
55 {
56 wxXmlResource *old = ms_instance;
57 ms_instance = res;
58 return old;
59 }
60
61 wxXmlResource::wxXmlResource(int flags)
62 {
63 m_handlers.DeleteContents(TRUE);
64 m_flags = flags;
65 m_version = -1;
66 }
67
68 wxXmlResource::wxXmlResource(const wxString& filemask, int flags)
69 {
70 m_flags = flags;
71 m_version = -1;
72 m_handlers.DeleteContents(TRUE);
73 Load(filemask);
74 }
75
76 wxXmlResource::~wxXmlResource()
77 {
78 ClearHandlers();
79 }
80
81
82 bool wxXmlResource::Load(const wxString& filemask)
83 {
84 wxString fnd;
85 wxXmlResourceDataRecord *drec;
86 bool iswild = wxIsWild(filemask);
87 bool rt = TRUE;
88
89 #if wxUSE_FILESYSTEM
90 wxFileSystem fsys;
91 # define wxXmlFindFirst fsys.FindFirst(filemask, wxFILE)
92 # define wxXmlFindNext fsys.FindNext()
93 #else
94 # define wxXmlFindFirst wxFindFirstFile(filemask, wxFILE)
95 # define wxXmlFindNext wxFindNextFile()
96 #endif
97 if (iswild)
98 fnd = wxXmlFindFirst;
99 else
100 fnd = filemask;
101 while (!!fnd)
102 {
103 // NB: Load() accepts both filenames and URLs (should probably be
104 // changed to filenames only, but embedded resources currently
105 // rely on its ability to handle URLs - FIXME). This check
106 // serves as a quick way to determine whether found name is
107 // filename and not URL:
108 if (wxFileName::FileExists(fnd))
109 {
110 // Make the name absolute filename, because the app may
111 // change working directory later:
112 wxFileName fn(fnd);
113 if (fn.IsRelative())
114 {
115 fn.MakeAbsolute();
116 fnd = fn.GetFullPath();
117 }
118 #if wxUSE_FILESYSTEM
119 fnd = wxFileSystem::FileNameToURL(fnd);
120 #endif
121 }
122
123 #if wxUSE_FILESYSTEM
124 if (fnd.Lower().Matches(wxT("*.zip")) ||
125 fnd.Lower().Matches(wxT("*.xrs")))
126 {
127 wxString url(wxFileSystem::FileNameToURL(fnd));
128 rt = rt && Load(url + wxT("#zip:*.xrc"));
129 }
130 else
131 #endif
132 {
133 drec = new wxXmlResourceDataRecord;
134 drec->File = fnd;
135 m_data.Add(drec);
136 }
137
138 if (iswild)
139 fnd = wxXmlFindNext;
140 else
141 fnd = wxEmptyString;
142 }
143 # undef wxXmlFindFirst
144 # undef wxXmlFindNext
145 return rt && UpdateResources();
146 }
147
148
149 IMPLEMENT_ABSTRACT_CLASS(wxXmlResourceHandler, wxObject)
150
151 void wxXmlResource::AddHandler(wxXmlResourceHandler *handler)
152 {
153 m_handlers.Append(handler);
154 handler->SetParentResource(this);
155 }
156
157 void wxXmlResource::InsertHandler(wxXmlResourceHandler *handler)
158 {
159 m_handlers.Insert(handler);
160 handler->SetParentResource(this);
161 }
162
163
164
165 void wxXmlResource::ClearHandlers()
166 {
167 m_handlers.Clear();
168 }
169
170
171 wxMenu *wxXmlResource::LoadMenu(const wxString& name)
172 {
173 return (wxMenu*)CreateResFromNode(FindResource(name, wxT("wxMenu")), NULL, NULL);
174 }
175
176
177
178 wxMenuBar *wxXmlResource::LoadMenuBar(wxWindow *parent, const wxString& name)
179 {
180 return (wxMenuBar*)CreateResFromNode(FindResource(name, wxT("wxMenuBar")), parent, NULL);
181 }
182
183
184
185 #if wxUSE_TOOLBAR
186 wxToolBar *wxXmlResource::LoadToolBar(wxWindow *parent, const wxString& name)
187 {
188 return (wxToolBar*)CreateResFromNode(FindResource(name, wxT("wxToolBar")), parent, NULL);
189 }
190 #endif
191
192
193 wxDialog *wxXmlResource::LoadDialog(wxWindow *parent, const wxString& name)
194 {
195 return (wxDialog*)CreateResFromNode(FindResource(name, wxT("wxDialog")), parent, NULL);
196 }
197
198 bool wxXmlResource::LoadDialog(wxDialog *dlg, wxWindow *parent, const wxString& name)
199 {
200 return CreateResFromNode(FindResource(name, wxT("wxDialog")), parent, dlg) != NULL;
201 }
202
203
204
205 wxPanel *wxXmlResource::LoadPanel(wxWindow *parent, const wxString& name)
206 {
207 return (wxPanel*)CreateResFromNode(FindResource(name, wxT("wxPanel")), parent, NULL);
208 }
209
210 bool wxXmlResource::LoadPanel(wxPanel *panel, wxWindow *parent, const wxString& name)
211 {
212 return CreateResFromNode(FindResource(name, wxT("wxPanel")), parent, panel) != NULL;
213 }
214
215 wxFrame *wxXmlResource::LoadFrame(wxWindow* parent, const wxString& name)
216 {
217 return (wxFrame*)CreateResFromNode(FindResource(name, wxT("wxFrame")), parent, NULL);
218 }
219
220 bool wxXmlResource::LoadFrame(wxFrame* frame, wxWindow *parent, const wxString& name)
221 {
222 return CreateResFromNode(FindResource(name, wxT("wxFrame")), parent, frame) != NULL;
223 }
224
225 wxBitmap wxXmlResource::LoadBitmap(const wxString& name)
226 {
227 wxBitmap *bmp = (wxBitmap*)CreateResFromNode(
228 FindResource(name, wxT("wxBitmap")), NULL, NULL);
229 wxBitmap rt;
230
231 if (bmp) { rt = *bmp; delete bmp; }
232 return rt;
233 }
234
235 wxIcon wxXmlResource::LoadIcon(const wxString& name)
236 {
237 wxIcon *icon = (wxIcon*)CreateResFromNode(
238 FindResource(name, wxT("wxIcon")), NULL, NULL);
239 wxIcon rt;
240
241 if (icon) { rt = *icon; delete icon; }
242 return rt;
243 }
244
245
246 wxObject *wxXmlResource::LoadObject(wxWindow *parent, const wxString& name, const wxString& classname)
247 {
248 return CreateResFromNode(FindResource(name, classname), parent, NULL);
249 }
250
251 bool wxXmlResource::LoadObject(wxObject *instance, wxWindow *parent, const wxString& name, const wxString& classname)
252 {
253 return CreateResFromNode(FindResource(name, classname), parent, instance) != NULL;
254 }
255
256
257 bool wxXmlResource::AttachUnknownControl(const wxString& name,
258 wxWindow *control, wxWindow *parent)
259 {
260 if (parent == NULL)
261 parent = control->GetParent();
262 wxWindow *container = parent->FindWindow(name + wxT("_container"));
263 if (!container)
264 {
265 wxLogError(_("Cannot find container for unknown control '%s'."), name.c_str());
266 return FALSE;
267 }
268 return control->Reparent(container);
269 }
270
271
272 static void ProcessPlatformProperty(wxXmlNode *node)
273 {
274 wxString s;
275 bool isok;
276
277 wxXmlNode *c = node->GetChildren();
278 while (c)
279 {
280 isok = FALSE;
281 if (!c->GetPropVal(wxT("platform"), &s))
282 isok = TRUE;
283 else
284 {
285 wxStringTokenizer tkn(s, wxT(" |"));
286
287 while (tkn.HasMoreTokens())
288 {
289 s = tkn.GetNextToken();
290 #ifdef __WINDOWS__
291 if (s == wxT("win")) isok = true;
292 #endif
293 #if defined(__MAC__) || defined(__APPLE__)
294 if (s == wxT("mac")) isok = true;
295 #elif defined(__UNIX__)
296 if (s == wxT("unix")) isok = true;
297 #endif
298 #ifdef __OS2__
299 if (s == wxT("os2")) isok = true;
300 #endif
301
302 if (isok)
303 break;
304 }
305 }
306
307 if (isok)
308 {
309 ProcessPlatformProperty(c);
310 c = c->GetNext();
311 }
312 else
313 {
314 wxXmlNode *c2 = c->GetNext();
315 node->RemoveChild(c);
316 delete c;
317 c = c2;
318 }
319 }
320 }
321
322
323
324 bool wxXmlResource::UpdateResources()
325 {
326 bool rt = true;
327 bool modif;
328 # if wxUSE_FILESYSTEM
329 wxFSFile *file = NULL;
330 wxFileSystem fsys;
331 # endif
332
333 wxString encoding(wxT("UTF-8"));
334 #if !wxUSE_UNICODE && wxUSE_INTL
335 if ( (GetFlags() & wxXRC_USE_LOCALE) == 0 )
336 {
337 // In case we are not using wxLocale to translate strings, convert the
338 // strings GUI's charset. This must not be done when wxXRC_USE_LOCALE
339 // is on, because it could break wxGetTranslation lookup.
340 encoding = wxLocale::GetSystemEncodingName();
341 }
342 #endif
343
344 for (size_t i = 0; i < m_data.GetCount(); i++)
345 {
346 modif = (m_data[i].Doc == NULL);
347
348 if (!modif)
349 {
350 # if wxUSE_FILESYSTEM
351 file = fsys.OpenFile(m_data[i].File);
352 modif = file && file->GetModificationTime() > m_data[i].Time;
353 if (!file)
354 {
355 wxLogError(_("Cannot open file '%s'."), m_data[i].File.c_str());
356 rt = false;
357 }
358 wxDELETE(file);
359 # else
360 modif = wxDateTime(wxFileModificationTime(m_data[i].File)) > m_data[i].Time;
361 # endif
362 }
363
364 if (modif)
365 {
366 wxInputStream *stream = NULL;
367
368 # if wxUSE_FILESYSTEM
369 file = fsys.OpenFile(m_data[i].File);
370 if (file)
371 stream = file->GetStream();
372 # else
373 stream = new wxFileInputStream(m_data[i].File);
374 # endif
375
376 if (stream)
377 {
378 delete m_data[i].Doc;
379 m_data[i].Doc = new wxXmlDocument;
380 }
381 if (!stream || !m_data[i].Doc->Load(*stream, encoding))
382 {
383 wxLogError(_("Cannot load resources from file '%s'."),
384 m_data[i].File.c_str());
385 wxDELETE(m_data[i].Doc);
386 rt = false;
387 }
388 else if (m_data[i].Doc->GetRoot()->GetName() != wxT("resource"))
389 {
390 wxLogError(_("Invalid XRC resource '%s': doesn't have root node 'resource'."), m_data[i].File.c_str());
391 wxDELETE(m_data[i].Doc);
392 rt = false;
393 }
394 else
395 {
396 long version;
397 int v1, v2, v3, v4;
398 wxString verstr = m_data[i].Doc->GetRoot()->GetPropVal(
399 wxT("version"), wxT("0.0.0.0"));
400 if (wxSscanf(verstr.c_str(), wxT("%i.%i.%i.%i"),
401 &v1, &v2, &v3, &v4) == 4)
402 version = v1*256*256*256+v2*256*256+v3*256+v4;
403 else
404 version = 0;
405 if (m_version == -1)
406 m_version = version;
407 if (m_version != version)
408 {
409 wxLogError(_("Resource files must have same version number!"));
410 rt = false;
411 }
412
413 ProcessPlatformProperty(m_data[i].Doc->GetRoot());
414 m_data[i].Time = file->GetModificationTime();
415 }
416
417 # if wxUSE_FILESYSTEM
418 wxDELETE(file);
419 # else
420 wxDELETE(stream);
421 # endif
422 }
423 }
424
425 return rt;
426 }
427
428
429 wxXmlNode *wxXmlResource::DoFindResource(wxXmlNode *parent,
430 const wxString& name,
431 const wxString& classname,
432 bool recursive)
433 {
434 wxString dummy;
435 wxXmlNode *node;
436
437 // first search for match at the top-level nodes (as this is
438 // where the resource is most commonly looked for):
439 for (node = parent->GetChildren(); node; node = node->GetNext())
440 {
441 if ( node->GetType() == wxXML_ELEMENT_NODE &&
442 (node->GetName() == wxT("object") ||
443 node->GetName() == wxT("object_ref")) &&
444 node->GetPropVal(wxT("name"), &dummy) && dummy == name )
445 {
446 wxString cls(node->GetPropVal(wxT("class"), wxEmptyString));
447 if (!classname || cls == classname)
448 return node;
449 // object_ref may not have 'class' property:
450 if (cls.empty() && node->GetName() == wxT("object_ref"))
451 {
452 wxString refName = node->GetPropVal(wxT("ref"), wxEmptyString);
453 if (refName.empty())
454 continue;
455 wxXmlNode* refNode = FindResource(refName, wxEmptyString, TRUE);
456 if (refNode &&
457 refNode->GetPropVal(wxT("class"), wxEmptyString) == classname)
458 {
459 return node;
460 }
461 }
462 }
463 }
464
465 if ( recursive )
466 for (node = parent->GetChildren(); node; node = node->GetNext())
467 {
468 if ( node->GetType() == wxXML_ELEMENT_NODE &&
469 (node->GetName() == wxT("object") ||
470 node->GetName() == wxT("object_ref")) )
471 {
472 wxXmlNode* found = DoFindResource(node, name, classname, TRUE);
473 if ( found )
474 return found;
475 }
476 }
477
478 return NULL;
479 }
480
481 wxXmlNode *wxXmlResource::FindResource(const wxString& name,
482 const wxString& classname,
483 bool recursive)
484 {
485 UpdateResources(); //ensure everything is up-to-date
486
487 wxString dummy;
488 for (size_t f = 0; f < m_data.GetCount(); f++)
489 {
490 if ( m_data[f].Doc == NULL || m_data[f].Doc->GetRoot() == NULL )
491 continue;
492
493 wxXmlNode* found = DoFindResource(m_data[f].Doc->GetRoot(),
494 name, classname, recursive);
495 if ( found )
496 {
497 #if wxUSE_FILESYSTEM
498 m_curFileSystem.ChangePathTo(m_data[f].File);
499 #endif
500 return found;
501 }
502 }
503
504 wxLogError(_("XRC resource '%s' (class '%s') not found!"),
505 name.c_str(), classname.c_str());
506 return NULL;
507 }
508
509 static void MergeNodes(wxXmlNode& dest, wxXmlNode& with)
510 {
511 // Merge properties:
512 for (wxXmlProperty *prop = with.GetProperties(); prop; prop = prop->GetNext())
513 {
514 wxXmlProperty *dprop;
515 for (dprop = dest.GetProperties(); dprop; dprop = dprop->GetNext())
516 {
517
518 if ( dprop->GetName() == prop->GetName() )
519 {
520 dprop->SetValue(prop->GetValue());
521 break;
522 }
523 }
524
525 if ( !dprop )
526 dest.AddProperty(prop->GetName(), prop->GetValue());
527 }
528
529 // Merge child nodes:
530 for (wxXmlNode* node = with.GetChildren(); node; node = node->GetNext())
531 {
532 wxString name = node->GetPropVal(wxT("name"), wxEmptyString);
533 wxXmlNode *dnode;
534
535 for (dnode = dest.GetChildren(); dnode; dnode = dnode->GetNext() )
536 {
537 if ( dnode->GetName() == node->GetName() &&
538 dnode->GetPropVal(wxT("name"), wxEmptyString) == name &&
539 dnode->GetType() == node->GetType() )
540 {
541 MergeNodes(*dnode, *node);
542 break;
543 }
544 }
545
546 if ( !dnode )
547 dest.AddChild(new wxXmlNode(*node));
548 }
549
550 if ( dest.GetType() == wxXML_TEXT_NODE && with.GetContent().Length() )
551 dest.SetContent(with.GetContent());
552 }
553
554 wxObject *wxXmlResource::CreateResFromNode(wxXmlNode *node, wxObject *parent,
555 wxObject *instance,
556 wxXmlResourceHandler *handlerToUse)
557 {
558 if (node == NULL) return NULL;
559
560 // handling of referenced resource
561 if ( node->GetName() == wxT("object_ref") )
562 {
563 wxString refName = node->GetPropVal(wxT("ref"), wxEmptyString);
564 wxXmlNode* refNode = FindResource(refName, wxEmptyString, TRUE);
565
566 if ( !refNode )
567 {
568 wxLogError(_("Referenced object node with ref=\"%s\" not found!"),
569 refName.c_str());
570 return NULL;
571 }
572
573 wxXmlNode copy(*refNode);
574 MergeNodes(copy, *node);
575
576 return CreateResFromNode(&copy, parent, instance);
577 }
578
579 wxXmlResourceHandler *handler;
580
581 if (handlerToUse)
582 {
583 if (handlerToUse->CanHandle(node))
584 {
585 return handlerToUse->CreateResource(node, parent, instance);
586 }
587 }
588 else if (node->GetName() == wxT("object"))
589 {
590 wxNode *ND = m_handlers.GetFirst();
591 while (ND)
592 {
593 handler = (wxXmlResourceHandler*)ND->GetData();
594 if (handler->CanHandle(node))
595 {
596 return handler->CreateResource(node, parent, instance);
597 }
598 ND = ND->GetNext();
599 }
600 }
601
602 wxLogError(_("No handler found for XML node '%s', class '%s'!"),
603 node->GetName().c_str(),
604 node->GetPropVal(wxT("class"), wxEmptyString).c_str());
605 return NULL;
606 }
607
608
609 #include "wx/listimpl.cpp"
610 WX_DECLARE_LIST(wxXmlSubclassFactory, wxXmlSubclassFactoriesList);
611 WX_DEFINE_LIST(wxXmlSubclassFactoriesList);
612
613 wxXmlSubclassFactoriesList *wxXmlResource::ms_subclassFactories = NULL;
614
615 /*static*/ void wxXmlResource::AddSubclassFactory(wxXmlSubclassFactory *factory)
616 {
617 if (!ms_subclassFactories)
618 {
619 ms_subclassFactories = new wxXmlSubclassFactoriesList;
620 ms_subclassFactories->DeleteContents(TRUE);
621 }
622 ms_subclassFactories->Append(factory);
623 }
624
625 class wxXmlSubclassFactoryCXX : public wxXmlSubclassFactory
626 {
627 public:
628 ~wxXmlSubclassFactoryCXX() {}
629
630 wxObject *Create(const wxString& className)
631 {
632 wxClassInfo* classInfo = wxClassInfo::FindClass(className);
633
634 if (classInfo)
635 return classInfo->CreateObject();
636 else
637 return NULL;
638 }
639 };
640
641
642
643
644
645 wxXmlResourceHandler::wxXmlResourceHandler()
646 : m_node(NULL), m_parent(NULL), m_instance(NULL),
647 m_parentAsWindow(NULL), m_instanceAsWindow(NULL)
648 {}
649
650
651
652 wxObject *wxXmlResourceHandler::CreateResource(wxXmlNode *node, wxObject *parent, wxObject *instance)
653 {
654 wxXmlNode *myNode = m_node;
655 wxString myClass = m_class;
656 wxObject *myParent = m_parent, *myInstance = m_instance;
657 wxWindow *myParentAW = m_parentAsWindow, *myInstanceAW = m_instanceAsWindow;
658
659 m_instance = instance;
660 if (!m_instance && node->HasProp(wxT("subclass")) &&
661 !(m_resource->GetFlags() & wxXRC_NO_SUBCLASSING))
662 {
663 wxString subclass = node->GetPropVal(wxT("subclass"), wxEmptyString);
664 if (!subclass.empty())
665 {
666 for (wxXmlSubclassFactoriesList::Node *i = wxXmlResource::ms_subclassFactories->GetFirst();
667 i; i = i->GetNext())
668 {
669 m_instance = i->GetData()->Create(subclass);
670 if (m_instance)
671 break;
672 }
673
674 if (!m_instance)
675 {
676 wxString name = node->GetPropVal(wxT("name"), wxEmptyString);
677 wxLogError(_("Subclass '%s' not found for resource '%s', not subclassing!"),
678 subclass.c_str(), name.c_str());
679 }
680 }
681 }
682
683 m_node = node;
684 m_class = node->GetPropVal(wxT("class"), wxEmptyString);
685 m_parent = parent;
686 m_parentAsWindow = wxDynamicCast(m_parent, wxWindow);
687 m_instanceAsWindow = wxDynamicCast(m_instance, wxWindow);
688
689 wxObject *returned = DoCreateResource();
690
691 m_node = myNode;
692 m_class = myClass;
693 m_parent = myParent; m_parentAsWindow = myParentAW;
694 m_instance = myInstance; m_instanceAsWindow = myInstanceAW;
695
696 return returned;
697 }
698
699
700 void wxXmlResourceHandler::AddStyle(const wxString& name, int value)
701 {
702 m_styleNames.Add(name);
703 m_styleValues.Add(value);
704 }
705
706
707
708 void wxXmlResourceHandler::AddWindowStyles()
709 {
710 XRC_ADD_STYLE(wxSIMPLE_BORDER);
711 XRC_ADD_STYLE(wxSUNKEN_BORDER);
712 XRC_ADD_STYLE(wxDOUBLE_BORDER);
713 XRC_ADD_STYLE(wxRAISED_BORDER);
714 XRC_ADD_STYLE(wxSTATIC_BORDER);
715 XRC_ADD_STYLE(wxNO_BORDER);
716 XRC_ADD_STYLE(wxTRANSPARENT_WINDOW);
717 XRC_ADD_STYLE(wxWANTS_CHARS);
718 XRC_ADD_STYLE(wxNO_FULL_REPAINT_ON_RESIZE);
719 }
720
721
722
723 bool wxXmlResourceHandler::HasParam(const wxString& param)
724 {
725 return (GetParamNode(param) != NULL);
726 }
727
728
729 int wxXmlResourceHandler::GetStyle(const wxString& param, int defaults)
730 {
731 wxString s = GetParamValue(param);
732
733 if (!s) return defaults;
734
735 wxStringTokenizer tkn(s, wxT("| \t\n"), wxTOKEN_STRTOK);
736 int style = 0;
737 int index;
738 wxString fl;
739 while (tkn.HasMoreTokens())
740 {
741 fl = tkn.GetNextToken();
742 index = m_styleNames.Index(fl);
743 if (index != wxNOT_FOUND)
744 style |= m_styleValues[index];
745 else
746 wxLogError(_("Unknown style flag ") + fl);
747 }
748 return style;
749 }
750
751
752
753 wxString wxXmlResourceHandler::GetText(const wxString& param, bool translate)
754 {
755 wxString str1(GetParamValue(param));
756 wxString str2;
757 const wxChar *dt;
758 wxChar amp_char;
759
760 // VS: First version of XRC resources used $ instead of & (which is
761 // illegal in XML), but later I realized that '_' fits this purpose
762 // much better (because &File means "File with F underlined").
763 if (m_resource->CompareVersion(2,3,0,1) < 0)
764 amp_char = wxT('$');
765 else
766 amp_char = wxT('_');
767
768 for (dt = str1.c_str(); *dt; dt++)
769 {
770 // Remap amp_char to &, map double amp_char to amp_char (for things
771 // like "&File..." -- this is illegal in XML, so we use "_File..."):
772 if (*dt == amp_char)
773 {
774 if ( *(++dt) == amp_char )
775 str2 << amp_char;
776 else
777 str2 << wxT('&') << *dt;
778 }
779 // Remap \n to CR, \r to LF, \t to TAB:
780 else if (*dt == wxT('\\'))
781 switch (*(++dt))
782 {
783 case wxT('n') : str2 << wxT('\n'); break;
784 case wxT('t') : str2 << wxT('\t'); break;
785 case wxT('r') : str2 << wxT('\r'); break;
786 default : str2 << wxT('\\') << *dt; break;
787 }
788 else str2 << *dt;
789 }
790
791 if (translate && m_resource->GetFlags() & wxXRC_USE_LOCALE)
792 return wxGetTranslation(str2);
793 else
794 return str2;
795
796 }
797
798
799
800 long wxXmlResourceHandler::GetLong(const wxString& param, long defaultv)
801 {
802 long value;
803 wxString str1 = GetParamValue(param);
804
805 if (!str1.ToLong(&value))
806 value = defaultv;
807
808 return value;
809 }
810
811
812
813 int wxXmlResourceHandler::GetID()
814 {
815 return wxXmlResource::GetXRCID(GetName());
816 }
817
818
819
820 wxString wxXmlResourceHandler::GetName()
821 {
822 return m_node->GetPropVal(wxT("name"), wxT("-1"));
823 }
824
825
826
827 bool wxXmlResourceHandler::GetBool(const wxString& param, bool defaultv)
828 {
829 wxString v = GetParamValue(param);
830 v.MakeLower();
831 if (!v) return defaultv;
832 else return (v == wxT("1"));
833 }
834
835
836
837 wxColour wxXmlResourceHandler::GetColour(const wxString& param)
838 {
839 wxString v = GetParamValue(param);
840 unsigned long tmp = 0;
841
842 if (v.Length() != 7 || v[0u] != wxT('#') ||
843 wxSscanf(v.c_str(), wxT("#%lX"), &tmp) != 1)
844 {
845 wxLogError(_("XRC resource: Incorrect colour specification '%s' for property '%s'."),
846 v.c_str(), param.c_str());
847 return wxNullColour;
848 }
849
850 return wxColour((unsigned char) ((tmp & 0xFF0000) >> 16) ,
851 (unsigned char) ((tmp & 0x00FF00) >> 8),
852 (unsigned char) ((tmp & 0x0000FF)));
853 }
854
855
856
857 wxBitmap wxXmlResourceHandler::GetBitmap(const wxString& param,
858 const wxArtClient& defaultArtClient,
859 wxSize size)
860 {
861 /* If the bitmap is specified as stock item, query wxArtProvider for it: */
862 wxXmlNode *bmpNode = GetParamNode(param);
863 if ( bmpNode )
864 {
865 wxString sid = bmpNode->GetPropVal(wxT("stock_id"), wxEmptyString);
866 if ( !sid.empty() )
867 {
868 wxString scl = bmpNode->GetPropVal(wxT("stock_client"), defaultArtClient);
869 wxBitmap stockArt =
870 wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(sid),
871 wxART_MAKE_CLIENT_ID_FROM_STR(scl),
872 size);
873 if ( stockArt.Ok() )
874 return stockArt;
875 }
876 }
877
878 /* ...or load the bitmap from file: */
879 wxString name = GetParamValue(param);
880 if (name.IsEmpty()) return wxNullBitmap;
881 #if wxUSE_FILESYSTEM
882 wxFSFile *fsfile = GetCurFileSystem().OpenFile(name);
883 if (fsfile == NULL)
884 {
885 wxLogError(_("XRC resource: Cannot create bitmap from '%s'."),
886 name.c_str());
887 return wxNullBitmap;
888 }
889 wxImage img(*(fsfile->GetStream()));
890 delete fsfile;
891 #else
892 wxImage img(GetParamValue(wxT("bitmap")));
893 #endif
894
895 if (!img.Ok())
896 {
897 wxLogError(_("XRC resource: Cannot create bitmap from '%s'."), param.c_str());
898 return wxNullBitmap;
899 }
900 if (!(size == wxDefaultSize)) img.Rescale(size.x, size.y);
901 return wxBitmap(img);
902
903 }
904
905
906
907 wxIcon wxXmlResourceHandler::GetIcon(const wxString& param,
908 const wxArtClient& defaultArtClient,
909 wxSize size)
910 {
911 wxIcon icon;
912 icon.CopyFromBitmap(GetBitmap(param, defaultArtClient, size));
913 return icon;
914 }
915
916
917
918 wxXmlNode *wxXmlResourceHandler::GetParamNode(const wxString& param)
919 {
920 wxCHECK_MSG(m_node, NULL, wxT("You can't access handler data before it was initialized!"));
921
922 wxXmlNode *n = m_node->GetChildren();
923
924 while (n)
925 {
926 if (n->GetType() == wxXML_ELEMENT_NODE && n->GetName() == param)
927 return n;
928 n = n->GetNext();
929 }
930 return NULL;
931 }
932
933
934 wxString wxXmlResourceHandler::GetNodeContent(wxXmlNode *node)
935 {
936 wxXmlNode *n = node;
937 if (n == NULL) return wxEmptyString;
938 n = n->GetChildren();
939
940 while (n)
941 {
942 if (n->GetType() == wxXML_TEXT_NODE ||
943 n->GetType() == wxXML_CDATA_SECTION_NODE)
944 return n->GetContent();
945 n = n->GetNext();
946 }
947 return wxEmptyString;
948 }
949
950
951
952 wxString wxXmlResourceHandler::GetParamValue(const wxString& param)
953 {
954 if (param.IsEmpty())
955 return GetNodeContent(m_node);
956 else
957 return GetNodeContent(GetParamNode(param));
958 }
959
960
961
962 wxSize wxXmlResourceHandler::GetSize(const wxString& param)
963 {
964 wxString s = GetParamValue(param);
965 if (s.IsEmpty()) s = wxT("-1,-1");
966 bool is_dlg;
967 long sx, sy;
968
969 is_dlg = s[s.Length()-1] == wxT('d');
970 if (is_dlg) s.RemoveLast();
971
972 if (!s.BeforeFirst(wxT(',')).ToLong(&sx) ||
973 !s.AfterLast(wxT(',')).ToLong(&sy))
974 {
975 wxLogError(_("Cannot parse coordinates from '%s'."), s.c_str());
976 return wxDefaultSize;
977 }
978
979 if (is_dlg)
980 {
981 if (m_instanceAsWindow)
982 return wxDLG_UNIT(m_instanceAsWindow, wxSize(sx, sy));
983 else if (m_parentAsWindow)
984 return wxDLG_UNIT(m_parentAsWindow, wxSize(sx, sy));
985 else
986 {
987 wxLogError(_("Cannot convert dialog units: dialog unknown."));
988 return wxDefaultSize;
989 }
990 }
991 else return wxSize(sx, sy);
992 }
993
994
995
996 wxPoint wxXmlResourceHandler::GetPosition(const wxString& param)
997 {
998 wxSize sz = GetSize(param);
999 return wxPoint(sz.x, sz.y);
1000 }
1001
1002
1003
1004 wxCoord wxXmlResourceHandler::GetDimension(const wxString& param, wxCoord defaultv)
1005 {
1006 wxString s = GetParamValue(param);
1007 if (s.IsEmpty()) return defaultv;
1008 bool is_dlg;
1009 long sx;
1010
1011 is_dlg = s[s.Length()-1] == wxT('d');
1012 if (is_dlg) s.RemoveLast();
1013
1014 if (!s.ToLong(&sx))
1015 {
1016 wxLogError(_("Cannot parse dimension from '%s'."), s.c_str());
1017 return defaultv;
1018 }
1019
1020 if (is_dlg)
1021 {
1022 if (m_instanceAsWindow)
1023 return wxDLG_UNIT(m_instanceAsWindow, wxSize(sx, 0)).x;
1024 else if (m_parentAsWindow)
1025 return wxDLG_UNIT(m_parentAsWindow, wxSize(sx, 0)).x;
1026 else
1027 {
1028 wxLogError(_("Cannot convert dialog units: dialog unknown."));
1029 return defaultv;
1030 }
1031 }
1032 else return sx;
1033 }
1034
1035
1036
1037 wxFont wxXmlResourceHandler::GetFont(const wxString& param)
1038 {
1039 wxXmlNode *font_node = GetParamNode(param);
1040 if (font_node == NULL)
1041 {
1042 wxLogError(_("Cannot find font node '%s'."), param.c_str());
1043 return wxNullFont;
1044 }
1045
1046 wxXmlNode *oldnode = m_node;
1047 m_node = font_node;
1048
1049 long size = GetLong(wxT("size"), 12);
1050
1051 wxString style = GetParamValue(wxT("style"));
1052 wxString weight = GetParamValue(wxT("weight"));
1053 int istyle = wxNORMAL, iweight = wxNORMAL;
1054 if (style == wxT("italic")) istyle = wxITALIC;
1055 else if (style == wxT("slant")) istyle = wxSLANT;
1056 if (weight == wxT("bold")) iweight = wxBOLD;
1057 else if (weight == wxT("light")) iweight = wxLIGHT;
1058
1059 wxString family = GetParamValue(wxT("family"));
1060 int ifamily = wxDEFAULT;
1061 if (family == wxT("decorative")) ifamily = wxDECORATIVE;
1062 else if (family == wxT("roman")) ifamily = wxROMAN;
1063 else if (family == wxT("script")) ifamily = wxSCRIPT;
1064 else if (family == wxT("swiss")) ifamily = wxSWISS;
1065 else if (family == wxT("modern")) ifamily = wxMODERN;
1066
1067 bool underlined = GetBool(wxT("underlined"), FALSE);
1068
1069 wxString encoding = GetParamValue(wxT("encoding"));
1070 wxFontMapper mapper;
1071 wxFontEncoding enc = wxFONTENCODING_DEFAULT;
1072 if (!encoding.IsEmpty())
1073 enc = mapper.CharsetToEncoding(encoding);
1074 if (enc == wxFONTENCODING_SYSTEM)
1075 enc = wxFONTENCODING_DEFAULT;
1076
1077 wxString faces = GetParamValue(wxT("face"));
1078 wxString facename = wxEmptyString;
1079 wxFontEnumerator enu;
1080 enu.EnumerateFacenames();
1081 wxStringTokenizer tk(faces, wxT(","));
1082 while (tk.HasMoreTokens())
1083 {
1084 int index = enu.GetFacenames()->Index(tk.GetNextToken(), FALSE);
1085 if (index != wxNOT_FOUND)
1086 {
1087 facename = (*enu.GetFacenames())[index];
1088 break;
1089 }
1090 }
1091
1092 m_node = oldnode;
1093
1094 wxFont font(size, ifamily, istyle, iweight, underlined, facename, enc);
1095 return font;
1096 }
1097
1098
1099 void wxXmlResourceHandler::SetupWindow(wxWindow *wnd)
1100 {
1101 //FIXME : add cursor
1102
1103 if (HasParam(wxT("exstyle")))
1104 wnd->SetExtraStyle(GetStyle(wxT("exstyle")));
1105 if (HasParam(wxT("bg")))
1106 wnd->SetBackgroundColour(GetColour(wxT("bg")));
1107 if (HasParam(wxT("fg")))
1108 wnd->SetForegroundColour(GetColour(wxT("fg")));
1109 if (GetBool(wxT("enabled"), 1) == 0)
1110 wnd->Enable(FALSE);
1111 if (GetBool(wxT("focused"), 0) == 1)
1112 wnd->SetFocus();
1113 if (GetBool(wxT("hidden"), 0) == 1)
1114 wnd->Show(FALSE);
1115 #if wxUSE_TOOLTIPS
1116 if (HasParam(wxT("tooltip")))
1117 wnd->SetToolTip(GetText(wxT("tooltip")));
1118 #endif
1119 if (HasParam(wxT("font")))
1120 wnd->SetFont(GetFont());
1121 }
1122
1123
1124 void wxXmlResourceHandler::CreateChildren(wxObject *parent, bool this_hnd_only)
1125 {
1126 wxXmlNode *n = m_node->GetChildren();
1127
1128 while (n)
1129 {
1130 if (n->GetType() == wxXML_ELEMENT_NODE &&
1131 (n->GetName() == wxT("object") || n->GetName() == wxT("object_ref")))
1132 {
1133 m_resource->CreateResFromNode(n, parent, NULL,
1134 this_hnd_only ? this : NULL);
1135 }
1136 n = n->GetNext();
1137 }
1138 }
1139
1140
1141 void wxXmlResourceHandler::CreateChildrenPrivately(wxObject *parent, wxXmlNode *rootnode)
1142 {
1143 wxXmlNode *root;
1144 if (rootnode == NULL) root = m_node; else root = rootnode;
1145 wxXmlNode *n = root->GetChildren();
1146
1147 while (n)
1148 {
1149 if (n->GetType() == wxXML_ELEMENT_NODE && CanHandle(n))
1150 {
1151 CreateResource(n, parent, NULL);
1152 }
1153 n = n->GetNext();
1154 }
1155 }
1156
1157
1158
1159
1160
1161
1162
1163 // --------------- XRCID implementation -----------------------------
1164
1165 #define XRCID_TABLE_SIZE 1024
1166
1167
1168 struct XRCID_record
1169 {
1170 int id;
1171 wxChar *key;
1172 XRCID_record *next;
1173 };
1174
1175 static XRCID_record *XRCID_Records[XRCID_TABLE_SIZE] = {NULL};
1176
1177 static int XRCID_Lookup(const wxChar *str_id, int value_if_not_found = -2)
1178 {
1179 static int XRCID_LastID = wxID_HIGHEST;
1180
1181 int index = 0;
1182
1183 for (const wxChar *c = str_id; *c != wxT('\0'); c++) index += (int)*c;
1184 index %= XRCID_TABLE_SIZE;
1185
1186 XRCID_record *oldrec = NULL;
1187 int matchcnt = 0;
1188 for (XRCID_record *rec = XRCID_Records[index]; rec; rec = rec->next)
1189 {
1190 if (wxStrcmp(rec->key, str_id) == 0)
1191 {
1192 return rec->id;
1193 }
1194 matchcnt++;
1195 oldrec = rec;
1196 }
1197
1198 XRCID_record **rec_var = (oldrec == NULL) ?
1199 &XRCID_Records[index] : &oldrec->next;
1200 *rec_var = new XRCID_record;
1201 (*rec_var)->key = wxStrdup(str_id);
1202 (*rec_var)->next = NULL;
1203
1204 wxChar *end;
1205 if (value_if_not_found != -2)
1206 (*rec_var)->id = value_if_not_found;
1207 else
1208 {
1209 int asint = wxStrtol(str_id, &end, 10);
1210 if (*str_id && *end == 0)
1211 {
1212 // if str_id was integer, keep it verbosely:
1213 (*rec_var)->id = asint;
1214 }
1215 else
1216 {
1217 (*rec_var)->id = ++XRCID_LastID;
1218 }
1219 }
1220
1221 return (*rec_var)->id;
1222 }
1223
1224 /*static*/ int wxXmlResource::GetXRCID(const wxChar *str_id)
1225 {
1226 return XRCID_Lookup(str_id);
1227 }
1228
1229
1230 static void CleanXRCID_Record(XRCID_record *rec)
1231 {
1232 if (rec)
1233 {
1234 CleanXRCID_Record(rec->next);
1235 free(rec->key);
1236 delete rec;
1237 }
1238 }
1239
1240 static void CleanXRCID_Records()
1241 {
1242 for (int i = 0; i < XRCID_TABLE_SIZE; i++)
1243 {
1244 CleanXRCID_Record(XRCID_Records[i]);
1245 XRCID_Records[i] = NULL;
1246 }
1247 }
1248
1249 static void AddStdXRCID_Records()
1250 {
1251 #define stdID(id) XRCID_Lookup(wxT(#id), id)
1252 stdID(-1);
1253 stdID(wxID_OPEN); stdID(wxID_CLOSE); stdID(wxID_NEW);
1254 stdID(wxID_SAVE); stdID(wxID_SAVEAS); stdID(wxID_REVERT);
1255 stdID(wxID_EXIT); stdID(wxID_UNDO); stdID(wxID_REDO);
1256 stdID(wxID_HELP); stdID(wxID_PRINT); stdID(wxID_PRINT_SETUP);
1257 stdID(wxID_PREVIEW); stdID(wxID_ABOUT); stdID(wxID_HELP_CONTENTS);
1258 stdID(wxID_HELP_COMMANDS); stdID(wxID_HELP_PROCEDURES);
1259 stdID(wxID_CUT); stdID(wxID_COPY); stdID(wxID_PASTE);
1260 stdID(wxID_CLEAR); stdID(wxID_FIND); stdID(wxID_DUPLICATE);
1261 stdID(wxID_SELECTALL); stdID(wxID_OK); stdID(wxID_CANCEL);
1262 stdID(wxID_APPLY); stdID(wxID_YES); stdID(wxID_NO);
1263 stdID(wxID_STATIC); stdID(wxID_FORWARD); stdID(wxID_BACKWARD);
1264 stdID(wxID_DEFAULT); stdID(wxID_MORE); stdID(wxID_SETUP);
1265 stdID(wxID_RESET); stdID(wxID_HELP_CONTEXT);
1266 stdID(wxID_CLOSE_ALL);
1267 #undef stdID
1268 }
1269
1270
1271
1272
1273
1274 // --------------- module and globals -----------------------------
1275
1276 class wxXmlResourceModule: public wxModule
1277 {
1278 DECLARE_DYNAMIC_CLASS(wxXmlResourceModule)
1279 public:
1280 wxXmlResourceModule() {}
1281 bool OnInit()
1282 {
1283 AddStdXRCID_Records();
1284 wxXmlResource::AddSubclassFactory(new wxXmlSubclassFactoryCXX);
1285 return TRUE;
1286 }
1287 void OnExit()
1288 {
1289 delete wxXmlResource::Set(NULL);
1290 wxDELETE(wxXmlResource::ms_subclassFactories);
1291 CleanXRCID_Records();
1292 }
1293 };
1294
1295 IMPLEMENT_DYNAMIC_CLASS(wxXmlResourceModule, wxModule)
1296
1297
1298 // When wxXml is loaded dynamically after the application is already running
1299 // then the built-in module system won't pick this one up. Add it manually.
1300 void wxXmlInitResourceModule()
1301 {
1302 wxModule* module = new wxXmlResourceModule;
1303 module->Init();
1304 wxModule::RegisterModule(module);
1305 }