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