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