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