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