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