added wxXmlResource::FindXRCIDById() (#10026)
[wxWidgets.git] / src / xrc / xmlres.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/xrc/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 // For compilers that support precompilation, includes "wx.h".
12 #include "wx/wxprec.h"
13
14 #ifdef __BORLANDC__
15 #pragma hdrstop
16 #endif
17
18 #if wxUSE_XRC
19
20 #include "wx/xrc/xmlres.h"
21
22 #ifndef WX_PRECOMP
23 #include "wx/intl.h"
24 #include "wx/log.h"
25 #include "wx/panel.h"
26 #include "wx/frame.h"
27 #include "wx/dialog.h"
28 #include "wx/settings.h"
29 #include "wx/bitmap.h"
30 #include "wx/image.h"
31 #include "wx/module.h"
32 #include "wx/wxcrtvararg.h"
33 #endif
34
35 #ifndef __WXWINCE__
36 #include <locale.h>
37 #endif
38
39 #include "wx/vector.h"
40 #include "wx/wfstream.h"
41 #include "wx/filesys.h"
42 #include "wx/filename.h"
43 #include "wx/tokenzr.h"
44 #include "wx/fontenum.h"
45 #include "wx/fontmap.h"
46 #include "wx/artprov.h"
47
48 #include "wx/xml/xml.h"
49
50
51 class wxXmlResourceDataRecord
52 {
53 public:
54 wxXmlResourceDataRecord() : Doc(NULL) {
55 #if wxUSE_DATETIME
56 Time = wxDateTime::Now();
57 #endif
58 }
59 ~wxXmlResourceDataRecord() {delete Doc;}
60
61 wxString File;
62 wxXmlDocument *Doc;
63 #if wxUSE_DATETIME
64 wxDateTime Time;
65 #endif
66 };
67
68 class wxXmlResourceDataRecords : public wxVector<wxXmlResourceDataRecord*>
69 {
70 // this is a class so that it can be forward-declared
71 };
72
73
74 wxXmlResource *wxXmlResource::ms_instance = NULL;
75
76 /*static*/ wxXmlResource *wxXmlResource::Get()
77 {
78 if ( !ms_instance )
79 ms_instance = new wxXmlResource;
80 return ms_instance;
81 }
82
83 /*static*/ wxXmlResource *wxXmlResource::Set(wxXmlResource *res)
84 {
85 wxXmlResource *old = ms_instance;
86 ms_instance = res;
87 return old;
88 }
89
90 wxXmlResource::wxXmlResource(int flags, const wxString& domain)
91 {
92 m_flags = flags;
93 m_version = -1;
94 m_data = new wxXmlResourceDataRecords;
95 SetDomain(domain);
96 }
97
98 wxXmlResource::wxXmlResource(const wxString& filemask, int flags, const wxString& domain)
99 {
100 m_flags = flags;
101 m_version = -1;
102 m_data = new wxXmlResourceDataRecords;
103 SetDomain(domain);
104 Load(filemask);
105 }
106
107 wxXmlResource::~wxXmlResource()
108 {
109 ClearHandlers();
110
111 for ( wxXmlResourceDataRecords::iterator i = m_data->begin();
112 i != m_data->end(); ++i )
113 {
114 delete *i;
115 }
116 delete m_data;
117 }
118
119 void wxXmlResource::SetDomain(const wxString& domain)
120 {
121 m_domain = domain;
122 }
123
124
125 /* static */
126 wxString wxXmlResource::ConvertFileNameToURL(const wxString& filename)
127 {
128 wxString fnd(filename);
129
130 // NB: as Load() and Unload() accept both filenames and URLs (should
131 // probably be changed to filenames only, but embedded resources
132 // currently rely on its ability to handle URLs - FIXME) we need to
133 // determine whether found name is filename and not URL and this is the
134 // fastest/simplest way to do it
135 if (wxFileName::FileExists(fnd))
136 {
137 // Make the name absolute filename, because the app may
138 // change working directory later:
139 wxFileName fn(fnd);
140 if (fn.IsRelative())
141 {
142 fn.MakeAbsolute();
143 fnd = fn.GetFullPath();
144 }
145 #if wxUSE_FILESYSTEM
146 fnd = wxFileSystem::FileNameToURL(fnd);
147 #endif
148 }
149
150 return fnd;
151 }
152
153 #if wxUSE_FILESYSTEM
154
155 /* static */
156 bool wxXmlResource::IsArchive(const wxString& filename)
157 {
158 const wxString fnd = filename.Lower();
159
160 return fnd.Matches(wxT("*.zip")) || fnd.Matches(wxT("*.xrs"));
161 }
162
163 #endif // wxUSE_FILESYSTEM
164
165 bool wxXmlResource::Load(const wxString& filemask)
166 {
167 #if wxUSE_FILESYSTEM
168 wxFileSystem fsys;
169 # define wxXmlFindFirst fsys.FindFirst(filemask, wxFILE)
170 # define wxXmlFindNext fsys.FindNext()
171 #else
172 # define wxXmlFindFirst wxFindFirstFile(filemask, wxFILE)
173 # define wxXmlFindNext wxFindNextFile()
174 #endif
175 wxString fnd = wxXmlFindFirst;
176 if ( fnd.empty() )
177 {
178 wxLogError(_("Cannot load resources from '%s'."), filemask);
179 return false;
180 }
181
182 while (!fnd.empty())
183 {
184 fnd = ConvertFileNameToURL(fnd);
185
186 #if wxUSE_FILESYSTEM
187 if ( IsArchive(fnd) )
188 {
189 if ( !Load(fnd + wxT("#zip:*.xrc")) )
190 return false;
191 }
192 else // a single resource URL
193 #endif // wxUSE_FILESYSTEM
194 {
195 wxXmlResourceDataRecord *drec = new wxXmlResourceDataRecord;
196 drec->File = fnd;
197 Data().push_back(drec);
198 }
199
200 fnd = wxXmlFindNext;
201 }
202 # undef wxXmlFindFirst
203 # undef wxXmlFindNext
204
205 return UpdateResources();
206 }
207
208 bool wxXmlResource::Unload(const wxString& filename)
209 {
210 wxASSERT_MSG( !wxIsWild(filename),
211 _T("wildcards not supported by wxXmlResource::Unload()") );
212
213 wxString fnd = ConvertFileNameToURL(filename);
214 #if wxUSE_FILESYSTEM
215 const bool isArchive = IsArchive(fnd);
216 if ( isArchive )
217 fnd += _T("#zip:");
218 #endif // wxUSE_FILESYSTEM
219
220 bool unloaded = false;
221 for ( wxXmlResourceDataRecords::iterator i = Data().begin();
222 i != Data().end(); ++i )
223 {
224 #if wxUSE_FILESYSTEM
225 if ( isArchive )
226 {
227 if ( (*i)->File.StartsWith(fnd) )
228 unloaded = true;
229 // don't break from the loop, we can have other matching files
230 }
231 else // a single resource URL
232 #endif // wxUSE_FILESYSTEM
233 {
234 if ( (*i)->File == fnd )
235 {
236 delete *i;
237 Data().erase(i);
238 unloaded = true;
239
240 // no sense in continuing, there is only one file with this URL
241 break;
242 }
243 }
244 }
245
246 return unloaded;
247 }
248
249
250 IMPLEMENT_ABSTRACT_CLASS(wxXmlResourceHandler, wxObject)
251
252 void wxXmlResource::AddHandler(wxXmlResourceHandler *handler)
253 {
254 m_handlers.push_back(handler);
255 handler->SetParentResource(this);
256 }
257
258 void wxXmlResource::InsertHandler(wxXmlResourceHandler *handler)
259 {
260 m_handlers.insert(m_handlers.begin(), handler);
261 handler->SetParentResource(this);
262 }
263
264
265
266 void wxXmlResource::ClearHandlers()
267 {
268 for ( wxVector<wxXmlResourceHandler*>::iterator i = m_handlers.begin();
269 i != m_handlers.end(); ++i )
270 delete *i;
271 m_handlers.clear();
272 }
273
274
275 wxMenu *wxXmlResource::LoadMenu(const wxString& name)
276 {
277 return (wxMenu*)CreateResFromNode(FindResource(name, wxT("wxMenu")), NULL, NULL);
278 }
279
280
281
282 wxMenuBar *wxXmlResource::LoadMenuBar(wxWindow *parent, const wxString& name)
283 {
284 return (wxMenuBar*)CreateResFromNode(FindResource(name, wxT("wxMenuBar")), parent, NULL);
285 }
286
287
288
289 #if wxUSE_TOOLBAR
290 wxToolBar *wxXmlResource::LoadToolBar(wxWindow *parent, const wxString& name)
291 {
292 return (wxToolBar*)CreateResFromNode(FindResource(name, wxT("wxToolBar")), parent, NULL);
293 }
294 #endif
295
296
297 wxDialog *wxXmlResource::LoadDialog(wxWindow *parent, const wxString& name)
298 {
299 return (wxDialog*)CreateResFromNode(FindResource(name, wxT("wxDialog")), parent, NULL);
300 }
301
302 bool wxXmlResource::LoadDialog(wxDialog *dlg, wxWindow *parent, const wxString& name)
303 {
304 return CreateResFromNode(FindResource(name, wxT("wxDialog")), parent, dlg) != NULL;
305 }
306
307
308
309 wxPanel *wxXmlResource::LoadPanel(wxWindow *parent, const wxString& name)
310 {
311 return (wxPanel*)CreateResFromNode(FindResource(name, wxT("wxPanel")), parent, NULL);
312 }
313
314 bool wxXmlResource::LoadPanel(wxPanel *panel, wxWindow *parent, const wxString& name)
315 {
316 return CreateResFromNode(FindResource(name, wxT("wxPanel")), parent, panel) != NULL;
317 }
318
319 wxFrame *wxXmlResource::LoadFrame(wxWindow* parent, const wxString& name)
320 {
321 return (wxFrame*)CreateResFromNode(FindResource(name, wxT("wxFrame")), parent, NULL);
322 }
323
324 bool wxXmlResource::LoadFrame(wxFrame* frame, wxWindow *parent, const wxString& name)
325 {
326 return CreateResFromNode(FindResource(name, wxT("wxFrame")), parent, frame) != NULL;
327 }
328
329 wxBitmap wxXmlResource::LoadBitmap(const wxString& name)
330 {
331 wxBitmap *bmp = (wxBitmap*)CreateResFromNode(
332 FindResource(name, wxT("wxBitmap")), NULL, NULL);
333 wxBitmap rt;
334
335 if (bmp) { rt = *bmp; delete bmp; }
336 return rt;
337 }
338
339 wxIcon wxXmlResource::LoadIcon(const wxString& name)
340 {
341 wxIcon *icon = (wxIcon*)CreateResFromNode(
342 FindResource(name, wxT("wxIcon")), NULL, NULL);
343 wxIcon rt;
344
345 if (icon) { rt = *icon; delete icon; }
346 return rt;
347 }
348
349
350 wxObject *wxXmlResource::LoadObject(wxWindow *parent, const wxString& name, const wxString& classname)
351 {
352 return CreateResFromNode(FindResource(name, classname), parent, NULL);
353 }
354
355 bool wxXmlResource::LoadObject(wxObject *instance, wxWindow *parent, const wxString& name, const wxString& classname)
356 {
357 return CreateResFromNode(FindResource(name, classname), parent, instance) != NULL;
358 }
359
360
361 bool wxXmlResource::AttachUnknownControl(const wxString& name,
362 wxWindow *control, wxWindow *parent)
363 {
364 if (parent == NULL)
365 parent = control->GetParent();
366 wxWindow *container = parent->FindWindow(name + wxT("_container"));
367 if (!container)
368 {
369 wxLogError(_("Cannot find container for unknown control '%s'."), name.c_str());
370 return false;
371 }
372 return control->Reparent(container);
373 }
374
375
376 static void ProcessPlatformProperty(wxXmlNode *node)
377 {
378 wxString s;
379 bool isok;
380
381 wxXmlNode *c = node->GetChildren();
382 while (c)
383 {
384 isok = false;
385 if (!c->GetAttribute(wxT("platform"), &s))
386 isok = true;
387 else
388 {
389 wxStringTokenizer tkn(s, wxT(" |"));
390
391 while (tkn.HasMoreTokens())
392 {
393 s = tkn.GetNextToken();
394 #ifdef __WINDOWS__
395 if (s == wxT("win")) isok = true;
396 #endif
397 #if defined(__MAC__) || defined(__APPLE__)
398 if (s == wxT("mac")) isok = true;
399 #elif defined(__UNIX__)
400 if (s == wxT("unix")) isok = true;
401 #endif
402 #ifdef __OS2__
403 if (s == wxT("os2")) isok = true;
404 #endif
405
406 if (isok)
407 break;
408 }
409 }
410
411 if (isok)
412 {
413 ProcessPlatformProperty(c);
414 c = c->GetNext();
415 }
416 else
417 {
418 wxXmlNode *c2 = c->GetNext();
419 node->RemoveChild(c);
420 delete c;
421 c = c2;
422 }
423 }
424 }
425
426
427
428 bool wxXmlResource::UpdateResources()
429 {
430 bool rt = true;
431 bool modif;
432 # if wxUSE_FILESYSTEM
433 wxFSFile *file = NULL;
434 wxUnusedVar(file);
435 wxFileSystem fsys;
436 # endif
437
438 wxString encoding(wxT("UTF-8"));
439 #if !wxUSE_UNICODE && wxUSE_INTL
440 if ( (GetFlags() & wxXRC_USE_LOCALE) == 0 )
441 {
442 // In case we are not using wxLocale to translate strings, convert the
443 // strings GUI's charset. This must not be done when wxXRC_USE_LOCALE
444 // is on, because it could break wxGetTranslation lookup.
445 encoding = wxLocale::GetSystemEncodingName();
446 }
447 #endif
448
449 for ( wxXmlResourceDataRecords::iterator i = Data().begin();
450 i != Data().end(); ++i )
451 {
452 wxXmlResourceDataRecord* const rec = *i;
453
454 modif = (rec->Doc == NULL);
455
456 if (!modif && !(m_flags & wxXRC_NO_RELOADING))
457 {
458 # if wxUSE_FILESYSTEM
459 file = fsys.OpenFile(rec->File);
460 # if wxUSE_DATETIME
461 modif = file && file->GetModificationTime() > rec->Time;
462 # else // wxUSE_DATETIME
463 modif = true;
464 # endif // wxUSE_DATETIME
465 if (!file)
466 {
467 wxLogError(_("Cannot open file '%s'."), rec->File);
468 rt = false;
469 }
470 wxDELETE(file);
471 wxUnusedVar(file);
472 # else // wxUSE_FILESYSTEM
473 # if wxUSE_DATETIME
474 modif = wxDateTime(wxFileModificationTime(rec->File)) > rec->Time;
475 # else // wxUSE_DATETIME
476 modif = true;
477 # endif // wxUSE_DATETIME
478 # endif // wxUSE_FILESYSTEM
479 }
480
481 if (modif)
482 {
483 wxLogTrace(_T("xrc"), _T("opening file '%s'"), rec->File);
484
485 wxInputStream *stream = NULL;
486
487 # if wxUSE_FILESYSTEM
488 file = fsys.OpenFile(rec->File);
489 if (file)
490 stream = file->GetStream();
491 # else
492 stream = new wxFileInputStream(rec->File);
493 # endif
494
495 if (stream)
496 {
497 delete rec->Doc;
498 rec->Doc = new wxXmlDocument;
499 }
500 if (!stream || !rec->Doc->Load(*stream, encoding))
501 {
502 wxLogError(_("Cannot load resources from file '%s'."),
503 rec->File);
504 wxDELETE(rec->Doc);
505 rt = false;
506 }
507 else if (rec->Doc->GetRoot()->GetName() != wxT("resource"))
508 {
509 wxLogError(_("Invalid XRC resource '%s': doesn't have root node 'resource'."), rec->File);
510 wxDELETE(rec->Doc);
511 rt = false;
512 }
513 else
514 {
515 long version;
516 int v1, v2, v3, v4;
517 wxString verstr = rec->Doc->GetRoot()->GetAttribute(
518 wxT("version"), wxT("0.0.0.0"));
519 if (wxSscanf(verstr.c_str(), wxT("%i.%i.%i.%i"),
520 &v1, &v2, &v3, &v4) == 4)
521 version = v1*256*256*256+v2*256*256+v3*256+v4;
522 else
523 version = 0;
524 if (m_version == -1)
525 m_version = version;
526 if (m_version != version)
527 {
528 wxLogError(_("Resource files must have same version number!"));
529 rt = false;
530 }
531
532 ProcessPlatformProperty(rec->Doc->GetRoot());
533 #if wxUSE_DATETIME
534 #if wxUSE_FILESYSTEM
535 rec->Time = file->GetModificationTime();
536 #else // wxUSE_FILESYSTEM
537 rec->Time = wxDateTime(wxFileModificationTime(rec->File));
538 #endif // wxUSE_FILESYSTEM
539 #endif // wxUSE_DATETIME
540 }
541
542 # if wxUSE_FILESYSTEM
543 wxDELETE(file);
544 wxUnusedVar(file);
545 # else
546 wxDELETE(stream);
547 # endif
548 }
549 }
550
551 return rt;
552 }
553
554
555 wxXmlNode *wxXmlResource::DoFindResource(wxXmlNode *parent,
556 const wxString& name,
557 const wxString& classname,
558 bool recursive)
559 {
560 wxString dummy;
561 wxXmlNode *node;
562
563 // first search for match at the top-level nodes (as this is
564 // where the resource is most commonly looked for):
565 for (node = parent->GetChildren(); node; node = node->GetNext())
566 {
567 if ( node->GetType() == wxXML_ELEMENT_NODE &&
568 (node->GetName() == wxT("object") ||
569 node->GetName() == wxT("object_ref")) &&
570 node->GetAttribute(wxT("name"), &dummy) && dummy == name )
571 {
572 wxString cls(node->GetAttribute(wxT("class"), wxEmptyString));
573 if (!classname || cls == classname)
574 return node;
575 // object_ref may not have 'class' attribute:
576 if (cls.empty() && node->GetName() == wxT("object_ref"))
577 {
578 wxString refName = node->GetAttribute(wxT("ref"), wxEmptyString);
579 if (refName.empty())
580 continue;
581 wxXmlNode* refNode = FindResource(refName, wxEmptyString, true);
582 if (refNode &&
583 refNode->GetAttribute(wxT("class"), wxEmptyString) == classname)
584 {
585 return node;
586 }
587 }
588 }
589 }
590
591 if ( recursive )
592 for (node = parent->GetChildren(); node; node = node->GetNext())
593 {
594 if ( node->GetType() == wxXML_ELEMENT_NODE &&
595 (node->GetName() == wxT("object") ||
596 node->GetName() == wxT("object_ref")) )
597 {
598 wxXmlNode* found = DoFindResource(node, name, classname, true);
599 if ( found )
600 return found;
601 }
602 }
603
604 return NULL;
605 }
606
607 wxXmlNode *wxXmlResource::FindResource(const wxString& name,
608 const wxString& classname,
609 bool recursive)
610 {
611 UpdateResources(); //ensure everything is up-to-date
612
613 wxString dummy;
614 for ( wxXmlResourceDataRecords::const_iterator f = Data().begin();
615 f != Data().end(); ++f )
616 {
617 wxXmlResourceDataRecord* const rec = *f;
618 if ( rec->Doc == NULL || rec->Doc->GetRoot() == NULL )
619 continue;
620
621 wxXmlNode* found = DoFindResource(rec->Doc->GetRoot(),
622 name, classname, recursive);
623 if ( found )
624 {
625 #if wxUSE_FILESYSTEM
626 m_curFileSystem.ChangePathTo(rec->File);
627 #endif
628 return found;
629 }
630 }
631
632 wxLogError(_("XRC resource '%s' (class '%s') not found!"),
633 name.c_str(), classname.c_str());
634 return NULL;
635 }
636
637 static void MergeNodes(wxXmlNode& dest, wxXmlNode& with)
638 {
639 // Merge attributes:
640 for ( wxXmlAttribute *attr = with.GetAttributes();
641 attr; attr = attr->GetNext() )
642 {
643 wxXmlAttribute *dattr;
644 for (dattr = dest.GetAttributes(); dattr; dattr = dattr->GetNext())
645 {
646
647 if ( dattr->GetName() == attr->GetName() )
648 {
649 dattr->SetValue(attr->GetValue());
650 break;
651 }
652 }
653
654 if ( !dattr )
655 dest.AddAttribute(attr->GetName(), attr->GetValue());
656 }
657
658 // Merge child nodes:
659 for (wxXmlNode* node = with.GetChildren(); node; node = node->GetNext())
660 {
661 wxString name = node->GetAttribute(wxT("name"), wxEmptyString);
662 wxXmlNode *dnode;
663
664 for (dnode = dest.GetChildren(); dnode; dnode = dnode->GetNext() )
665 {
666 if ( dnode->GetName() == node->GetName() &&
667 dnode->GetAttribute(wxT("name"), wxEmptyString) == name &&
668 dnode->GetType() == node->GetType() )
669 {
670 MergeNodes(*dnode, *node);
671 break;
672 }
673 }
674
675 if ( !dnode )
676 {
677 static const wxChar *AT_END = wxT("end");
678 wxString insert_pos = node->GetAttribute(wxT("insert_at"), AT_END);
679 if ( insert_pos == AT_END )
680 {
681 dest.AddChild(new wxXmlNode(*node));
682 }
683 else if ( insert_pos == wxT("begin") )
684 {
685 dest.InsertChild(new wxXmlNode(*node), dest.GetChildren());
686 }
687 }
688 }
689
690 if ( dest.GetType() == wxXML_TEXT_NODE && with.GetContent().length() )
691 dest.SetContent(with.GetContent());
692 }
693
694 wxObject *wxXmlResource::CreateResFromNode(wxXmlNode *node, wxObject *parent,
695 wxObject *instance,
696 wxXmlResourceHandler *handlerToUse)
697 {
698 if (node == NULL) return NULL;
699
700 // handling of referenced resource
701 if ( node->GetName() == wxT("object_ref") )
702 {
703 wxString refName = node->GetAttribute(wxT("ref"), wxEmptyString);
704 wxXmlNode* refNode = FindResource(refName, wxEmptyString, true);
705
706 if ( !refNode )
707 {
708 wxLogError(_("Referenced object node with ref=\"%s\" not found!"),
709 refName.c_str());
710 return NULL;
711 }
712
713 wxXmlNode copy(*refNode);
714 MergeNodes(copy, *node);
715
716 return CreateResFromNode(&copy, parent, instance);
717 }
718
719 if (handlerToUse)
720 {
721 if (handlerToUse->CanHandle(node))
722 {
723 return handlerToUse->CreateResource(node, parent, instance);
724 }
725 }
726 else if (node->GetName() == wxT("object"))
727 {
728 for ( wxVector<wxXmlResourceHandler*>::iterator h = m_handlers.begin();
729 h != m_handlers.end(); ++h )
730 {
731 wxXmlResourceHandler *handler = *h;
732 if (handler->CanHandle(node))
733 return handler->CreateResource(node, parent, instance);
734 }
735 }
736
737 wxLogError(_("No handler found for XML node '%s', class '%s'!"),
738 node->GetName().c_str(),
739 node->GetAttribute(wxT("class"), wxEmptyString).c_str());
740 return NULL;
741 }
742
743
744 class wxXmlSubclassFactories : public wxVector<wxXmlSubclassFactory*>
745 {
746 // this is a class so that it can be forward-declared
747 };
748
749 wxXmlSubclassFactories *wxXmlResource::ms_subclassFactories = NULL;
750
751 /*static*/ void wxXmlResource::AddSubclassFactory(wxXmlSubclassFactory *factory)
752 {
753 if (!ms_subclassFactories)
754 {
755 ms_subclassFactories = new wxXmlSubclassFactories;
756 }
757 ms_subclassFactories->push_back(factory);
758 }
759
760 class wxXmlSubclassFactoryCXX : public wxXmlSubclassFactory
761 {
762 public:
763 ~wxXmlSubclassFactoryCXX() {}
764
765 wxObject *Create(const wxString& className)
766 {
767 wxClassInfo* classInfo = wxClassInfo::FindClass(className);
768
769 if (classInfo)
770 return classInfo->CreateObject();
771 else
772 return NULL;
773 }
774 };
775
776
777
778
779 wxXmlResourceHandler::wxXmlResourceHandler()
780 : m_node(NULL), m_parent(NULL), m_instance(NULL),
781 m_parentAsWindow(NULL)
782 {}
783
784
785
786 wxObject *wxXmlResourceHandler::CreateResource(wxXmlNode *node, wxObject *parent, wxObject *instance)
787 {
788 wxXmlNode *myNode = m_node;
789 wxString myClass = m_class;
790 wxObject *myParent = m_parent, *myInstance = m_instance;
791 wxWindow *myParentAW = m_parentAsWindow;
792
793 m_instance = instance;
794 if (!m_instance && node->HasAttribute(wxT("subclass")) &&
795 !(m_resource->GetFlags() & wxXRC_NO_SUBCLASSING))
796 {
797 wxString subclass = node->GetAttribute(wxT("subclass"), wxEmptyString);
798 if (!subclass.empty())
799 {
800 for (wxXmlSubclassFactories::iterator i = wxXmlResource::ms_subclassFactories->begin();
801 i != wxXmlResource::ms_subclassFactories->end(); ++i)
802 {
803 m_instance = (*i)->Create(subclass);
804 if (m_instance)
805 break;
806 }
807
808 if (!m_instance)
809 {
810 wxString name = node->GetAttribute(wxT("name"), wxEmptyString);
811 wxLogError(_("Subclass '%s' not found for resource '%s', not subclassing!"),
812 subclass.c_str(), name.c_str());
813 }
814 }
815 }
816
817 m_node = node;
818 m_class = node->GetAttribute(wxT("class"), wxEmptyString);
819 m_parent = parent;
820 m_parentAsWindow = wxDynamicCast(m_parent, wxWindow);
821
822 wxObject *returned = DoCreateResource();
823
824 m_node = myNode;
825 m_class = myClass;
826 m_parent = myParent; m_parentAsWindow = myParentAW;
827 m_instance = myInstance;
828
829 return returned;
830 }
831
832
833 void wxXmlResourceHandler::AddStyle(const wxString& name, int value)
834 {
835 m_styleNames.Add(name);
836 m_styleValues.Add(value);
837 }
838
839
840
841 void wxXmlResourceHandler::AddWindowStyles()
842 {
843 XRC_ADD_STYLE(wxCLIP_CHILDREN);
844
845 // the border styles all have the old and new names, recognize both for now
846 XRC_ADD_STYLE(wxSIMPLE_BORDER); XRC_ADD_STYLE(wxBORDER_SIMPLE);
847 XRC_ADD_STYLE(wxSUNKEN_BORDER); XRC_ADD_STYLE(wxBORDER_SUNKEN);
848 XRC_ADD_STYLE(wxDOUBLE_BORDER); XRC_ADD_STYLE(wxBORDER_DOUBLE);
849 XRC_ADD_STYLE(wxRAISED_BORDER); XRC_ADD_STYLE(wxBORDER_RAISED);
850 XRC_ADD_STYLE(wxSTATIC_BORDER); XRC_ADD_STYLE(wxBORDER_STATIC);
851 XRC_ADD_STYLE(wxNO_BORDER); XRC_ADD_STYLE(wxBORDER_NONE);
852
853 XRC_ADD_STYLE(wxTRANSPARENT_WINDOW);
854 XRC_ADD_STYLE(wxWANTS_CHARS);
855 XRC_ADD_STYLE(wxTAB_TRAVERSAL);
856 XRC_ADD_STYLE(wxNO_FULL_REPAINT_ON_RESIZE);
857 XRC_ADD_STYLE(wxFULL_REPAINT_ON_RESIZE);
858 XRC_ADD_STYLE(wxALWAYS_SHOW_SB);
859 XRC_ADD_STYLE(wxWS_EX_BLOCK_EVENTS);
860 XRC_ADD_STYLE(wxWS_EX_VALIDATE_RECURSIVELY);
861 }
862
863
864
865 bool wxXmlResourceHandler::HasParam(const wxString& param)
866 {
867 return (GetParamNode(param) != NULL);
868 }
869
870
871 int wxXmlResourceHandler::GetStyle(const wxString& param, int defaults)
872 {
873 wxString s = GetParamValue(param);
874
875 if (!s) return defaults;
876
877 wxStringTokenizer tkn(s, wxT("| \t\n"), wxTOKEN_STRTOK);
878 int style = 0;
879 int index;
880 wxString fl;
881 while (tkn.HasMoreTokens())
882 {
883 fl = tkn.GetNextToken();
884 index = m_styleNames.Index(fl);
885 if (index != wxNOT_FOUND)
886 style |= m_styleValues[index];
887 else
888 wxLogError(_("Unknown style flag ") + fl);
889 }
890 return style;
891 }
892
893
894
895 wxString wxXmlResourceHandler::GetText(const wxString& param, bool translate)
896 {
897 wxXmlNode *parNode = GetParamNode(param);
898 wxString str1(GetNodeContent(parNode));
899 wxString str2;
900
901 // "\\" wasn't translated to "\" prior to 2.5.3.0:
902 const bool escapeBackslash = (m_resource->CompareVersion(2,5,3,0) >= 0);
903
904 // VS: First version of XRC resources used $ instead of & (which is
905 // illegal in XML), but later I realized that '_' fits this purpose
906 // much better (because &File means "File with F underlined").
907 const wxChar amp_char = (m_resource->CompareVersion(2,3,0,1) < 0)
908 ? '$' : '_';
909
910 for ( wxString::const_iterator dt = str1.begin(); dt != str1.end(); ++dt )
911 {
912 // Remap amp_char to &, map double amp_char to amp_char (for things
913 // like "&File..." -- this is illegal in XML, so we use "_File..."):
914 if ( *dt == amp_char )
915 {
916 if ( *(++dt) == amp_char )
917 str2 << amp_char;
918 else
919 str2 << wxT('&') << *dt;
920 }
921 // Remap \n to CR, \r to LF, \t to TAB, \\ to \:
922 else if ( *dt == wxT('\\') )
923 {
924 switch ( (*(++dt)).GetValue() )
925 {
926 case wxT('n'):
927 str2 << wxT('\n');
928 break;
929
930 case wxT('t'):
931 str2 << wxT('\t');
932 break;
933
934 case wxT('r'):
935 str2 << wxT('\r');
936 break;
937
938 case wxT('\\') :
939 // "\\" wasn't translated to "\" prior to 2.5.3.0:
940 if ( escapeBackslash )
941 {
942 str2 << wxT('\\');
943 break;
944 }
945 // else fall-through to default: branch below
946
947 default:
948 str2 << wxT('\\') << *dt;
949 break;
950 }
951 }
952 else
953 {
954 str2 << *dt;
955 }
956 }
957
958 if (m_resource->GetFlags() & wxXRC_USE_LOCALE)
959 {
960 if (translate && parNode &&
961 parNode->GetAttribute(wxT("translate"), wxEmptyString) != wxT("0"))
962 {
963 return wxGetTranslation(str2, m_resource->GetDomain());
964 }
965 else
966 {
967 #if wxUSE_UNICODE
968 return str2;
969 #else
970 // The string is internally stored as UTF-8, we have to convert
971 // it into system's default encoding so that it can be displayed:
972 return wxString(str2.wc_str(wxConvUTF8), wxConvLocal);
973 #endif
974 }
975 }
976
977 // If wxXRC_USE_LOCALE is not set, then the string is already in
978 // system's default encoding in ANSI build, so we don't have to
979 // do anything special here.
980 return str2;
981 }
982
983
984
985 long wxXmlResourceHandler::GetLong(const wxString& param, long defaultv)
986 {
987 long value;
988 wxString str1 = GetParamValue(param);
989
990 if (!str1.ToLong(&value))
991 value = defaultv;
992
993 return value;
994 }
995
996 float wxXmlResourceHandler::GetFloat(const wxString& param, float defaultv)
997 {
998 wxString str = GetParamValue(param);
999
1000 #if wxUSE_INTL
1001 // strings in XRC always use C locale but wxString::ToDouble() uses the
1002 // current one, so transform the string to it supposing that the only
1003 // difference between them is the decimal separator
1004 //
1005 // TODO: use wxString::ToCDouble() when we have it
1006 str.Replace(wxT("."), wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT,
1007 wxLOCALE_CAT_NUMBER));
1008 #endif // wxUSE_INTL
1009
1010 double value;
1011 if (!str.ToDouble(&value))
1012 value = defaultv;
1013
1014 return wx_truncate_cast(float, value);
1015 }
1016
1017
1018 int wxXmlResourceHandler::GetID()
1019 {
1020 return wxXmlResource::GetXRCID(GetName());
1021 }
1022
1023
1024
1025 wxString wxXmlResourceHandler::GetName()
1026 {
1027 return m_node->GetAttribute(wxT("name"), wxT("-1"));
1028 }
1029
1030
1031
1032 bool wxXmlResourceHandler::GetBoolAttr(const wxString& attr, bool defaultv)
1033 {
1034 wxString v;
1035 return m_node->GetAttribute(attr, &v) ? v == '1' : defaultv;
1036 }
1037
1038 bool wxXmlResourceHandler::GetBool(const wxString& param, bool defaultv)
1039 {
1040 const wxString v = GetParamValue(param);
1041
1042 return v.empty() ? defaultv : (v == '1');
1043 }
1044
1045
1046 static wxColour GetSystemColour(const wxString& name)
1047 {
1048 if (!name.empty())
1049 {
1050 #define SYSCLR(clr) \
1051 if (name == _T(#clr)) return wxSystemSettings::GetColour(clr);
1052 SYSCLR(wxSYS_COLOUR_SCROLLBAR)
1053 SYSCLR(wxSYS_COLOUR_BACKGROUND)
1054 SYSCLR(wxSYS_COLOUR_DESKTOP)
1055 SYSCLR(wxSYS_COLOUR_ACTIVECAPTION)
1056 SYSCLR(wxSYS_COLOUR_INACTIVECAPTION)
1057 SYSCLR(wxSYS_COLOUR_MENU)
1058 SYSCLR(wxSYS_COLOUR_WINDOW)
1059 SYSCLR(wxSYS_COLOUR_WINDOWFRAME)
1060 SYSCLR(wxSYS_COLOUR_MENUTEXT)
1061 SYSCLR(wxSYS_COLOUR_WINDOWTEXT)
1062 SYSCLR(wxSYS_COLOUR_CAPTIONTEXT)
1063 SYSCLR(wxSYS_COLOUR_ACTIVEBORDER)
1064 SYSCLR(wxSYS_COLOUR_INACTIVEBORDER)
1065 SYSCLR(wxSYS_COLOUR_APPWORKSPACE)
1066 SYSCLR(wxSYS_COLOUR_HIGHLIGHT)
1067 SYSCLR(wxSYS_COLOUR_HIGHLIGHTTEXT)
1068 SYSCLR(wxSYS_COLOUR_BTNFACE)
1069 SYSCLR(wxSYS_COLOUR_3DFACE)
1070 SYSCLR(wxSYS_COLOUR_BTNSHADOW)
1071 SYSCLR(wxSYS_COLOUR_3DSHADOW)
1072 SYSCLR(wxSYS_COLOUR_GRAYTEXT)
1073 SYSCLR(wxSYS_COLOUR_BTNTEXT)
1074 SYSCLR(wxSYS_COLOUR_INACTIVECAPTIONTEXT)
1075 SYSCLR(wxSYS_COLOUR_BTNHIGHLIGHT)
1076 SYSCLR(wxSYS_COLOUR_BTNHILIGHT)
1077 SYSCLR(wxSYS_COLOUR_3DHIGHLIGHT)
1078 SYSCLR(wxSYS_COLOUR_3DHILIGHT)
1079 SYSCLR(wxSYS_COLOUR_3DDKSHADOW)
1080 SYSCLR(wxSYS_COLOUR_3DLIGHT)
1081 SYSCLR(wxSYS_COLOUR_INFOTEXT)
1082 SYSCLR(wxSYS_COLOUR_INFOBK)
1083 SYSCLR(wxSYS_COLOUR_LISTBOX)
1084 SYSCLR(wxSYS_COLOUR_HOTLIGHT)
1085 SYSCLR(wxSYS_COLOUR_GRADIENTACTIVECAPTION)
1086 SYSCLR(wxSYS_COLOUR_GRADIENTINACTIVECAPTION)
1087 SYSCLR(wxSYS_COLOUR_MENUHILIGHT)
1088 SYSCLR(wxSYS_COLOUR_MENUBAR)
1089 #undef SYSCLR
1090 }
1091
1092 return wxNullColour;
1093 }
1094
1095 wxColour wxXmlResourceHandler::GetColour(const wxString& param, const wxColour& defaultv)
1096 {
1097 wxString v = GetParamValue(param);
1098
1099 if ( v.empty() )
1100 return defaultv;
1101
1102 wxColour clr;
1103
1104 // wxString -> wxColour conversion
1105 if (!clr.Set(v))
1106 {
1107 // the colour doesn't use #RRGGBB format, check if it is symbolic
1108 // colour name:
1109 clr = GetSystemColour(v);
1110 if (clr.Ok())
1111 return clr;
1112
1113 wxLogError(_("XRC resource: Incorrect colour specification '%s' for attribute '%s'."),
1114 v.c_str(), param.c_str());
1115 return wxNullColour;
1116 }
1117
1118 return clr;
1119 }
1120
1121
1122
1123 wxBitmap wxXmlResourceHandler::GetBitmap(const wxString& param,
1124 const wxArtClient& defaultArtClient,
1125 wxSize size)
1126 {
1127 /* If the bitmap is specified as stock item, query wxArtProvider for it: */
1128 wxXmlNode *bmpNode = GetParamNode(param);
1129 if ( bmpNode )
1130 {
1131 wxString sid = bmpNode->GetAttribute(wxT("stock_id"), wxEmptyString);
1132 if ( !sid.empty() )
1133 {
1134 wxString scl = bmpNode->GetAttribute(wxT("stock_client"), wxEmptyString);
1135 if (scl.empty())
1136 scl = defaultArtClient;
1137 else
1138 scl = wxART_MAKE_CLIENT_ID_FROM_STR(scl);
1139
1140 wxBitmap stockArt =
1141 wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(sid),
1142 scl, size);
1143 if ( stockArt.Ok() )
1144 return stockArt;
1145 }
1146 }
1147
1148 /* ...or load the bitmap from file: */
1149 wxString name = GetParamValue(param);
1150 if (name.empty()) return wxNullBitmap;
1151 #if wxUSE_FILESYSTEM
1152 wxFSFile *fsfile = GetCurFileSystem().OpenFile(name, wxFS_READ | wxFS_SEEKABLE);
1153 if (fsfile == NULL)
1154 {
1155 wxLogError(_("XRC resource: Cannot create bitmap from '%s'."),
1156 name.c_str());
1157 return wxNullBitmap;
1158 }
1159 wxImage img(*(fsfile->GetStream()));
1160 delete fsfile;
1161 #else
1162 wxImage img(name);
1163 #endif
1164
1165 if (!img.Ok())
1166 {
1167 wxLogError(_("XRC resource: Cannot create bitmap from '%s'."),
1168 name.c_str());
1169 return wxNullBitmap;
1170 }
1171 if (!(size == wxDefaultSize)) img.Rescale(size.x, size.y);
1172 return wxBitmap(img);
1173 }
1174
1175
1176 wxIcon wxXmlResourceHandler::GetIcon(const wxString& param,
1177 const wxArtClient& defaultArtClient,
1178 wxSize size)
1179 {
1180 wxIcon icon;
1181 icon.CopyFromBitmap(GetBitmap(param, defaultArtClient, size));
1182 return icon;
1183 }
1184
1185
1186
1187 wxXmlNode *wxXmlResourceHandler::GetParamNode(const wxString& param)
1188 {
1189 wxCHECK_MSG(m_node, NULL, wxT("You can't access handler data before it was initialized!"));
1190
1191 wxXmlNode *n = m_node->GetChildren();
1192
1193 while (n)
1194 {
1195 if (n->GetType() == wxXML_ELEMENT_NODE && n->GetName() == param)
1196 return n;
1197 n = n->GetNext();
1198 }
1199 return NULL;
1200 }
1201
1202
1203
1204 bool wxXmlResourceHandler::IsOfClass(wxXmlNode *node, const wxString& classname)
1205 {
1206 return node->GetAttribute(wxT("class"), wxEmptyString) == classname;
1207 }
1208
1209
1210
1211 wxString wxXmlResourceHandler::GetNodeContent(wxXmlNode *node)
1212 {
1213 wxXmlNode *n = node;
1214 if (n == NULL) return wxEmptyString;
1215 n = n->GetChildren();
1216
1217 while (n)
1218 {
1219 if (n->GetType() == wxXML_TEXT_NODE ||
1220 n->GetType() == wxXML_CDATA_SECTION_NODE)
1221 return n->GetContent();
1222 n = n->GetNext();
1223 }
1224 return wxEmptyString;
1225 }
1226
1227
1228
1229 wxString wxXmlResourceHandler::GetParamValue(const wxString& param)
1230 {
1231 if (param.empty())
1232 return GetNodeContent(m_node);
1233 else
1234 return GetNodeContent(GetParamNode(param));
1235 }
1236
1237
1238
1239 wxSize wxXmlResourceHandler::GetSize(const wxString& param,
1240 wxWindow *windowToUse)
1241 {
1242 wxString s = GetParamValue(param);
1243 if (s.empty()) s = wxT("-1,-1");
1244 bool is_dlg;
1245 long sx, sy = 0;
1246
1247 is_dlg = s[s.length()-1] == wxT('d');
1248 if (is_dlg) s.RemoveLast();
1249
1250 if (!s.BeforeFirst(wxT(',')).ToLong(&sx) ||
1251 !s.AfterLast(wxT(',')).ToLong(&sy))
1252 {
1253 wxLogError(_("Cannot parse coordinates from '%s'."), s.c_str());
1254 return wxDefaultSize;
1255 }
1256
1257 if (is_dlg)
1258 {
1259 if (windowToUse)
1260 {
1261 return wxDLG_UNIT(windowToUse, wxSize(sx, sy));
1262 }
1263 else if (m_parentAsWindow)
1264 {
1265 return wxDLG_UNIT(m_parentAsWindow, wxSize(sx, sy));
1266 }
1267 else
1268 {
1269 wxLogError(_("Cannot convert dialog units: dialog unknown."));
1270 return wxDefaultSize;
1271 }
1272 }
1273
1274 return wxSize(sx, sy);
1275 }
1276
1277
1278
1279 wxPoint wxXmlResourceHandler::GetPosition(const wxString& param)
1280 {
1281 wxSize sz = GetSize(param);
1282 return wxPoint(sz.x, sz.y);
1283 }
1284
1285
1286
1287 wxCoord wxXmlResourceHandler::GetDimension(const wxString& param,
1288 wxCoord defaultv,
1289 wxWindow *windowToUse)
1290 {
1291 wxString s = GetParamValue(param);
1292 if (s.empty()) return defaultv;
1293 bool is_dlg;
1294 long sx;
1295
1296 is_dlg = s[s.length()-1] == wxT('d');
1297 if (is_dlg) s.RemoveLast();
1298
1299 if (!s.ToLong(&sx))
1300 {
1301 wxLogError(_("Cannot parse dimension from '%s'."), s.c_str());
1302 return defaultv;
1303 }
1304
1305 if (is_dlg)
1306 {
1307 if (windowToUse)
1308 {
1309 return wxDLG_UNIT(windowToUse, wxSize(sx, 0)).x;
1310 }
1311 else if (m_parentAsWindow)
1312 {
1313 return wxDLG_UNIT(m_parentAsWindow, wxSize(sx, 0)).x;
1314 }
1315 else
1316 {
1317 wxLogError(_("Cannot convert dialog units: dialog unknown."));
1318 return defaultv;
1319 }
1320 }
1321
1322 return sx;
1323 }
1324
1325
1326 // Get system font index using indexname
1327 static wxFont GetSystemFont(const wxString& name)
1328 {
1329 if (!name.empty())
1330 {
1331 #define SYSFNT(fnt) \
1332 if (name == _T(#fnt)) return wxSystemSettings::GetFont(fnt);
1333 SYSFNT(wxSYS_OEM_FIXED_FONT)
1334 SYSFNT(wxSYS_ANSI_FIXED_FONT)
1335 SYSFNT(wxSYS_ANSI_VAR_FONT)
1336 SYSFNT(wxSYS_SYSTEM_FONT)
1337 SYSFNT(wxSYS_DEVICE_DEFAULT_FONT)
1338 SYSFNT(wxSYS_DEFAULT_PALETTE)
1339 SYSFNT(wxSYS_SYSTEM_FIXED_FONT)
1340 SYSFNT(wxSYS_DEFAULT_GUI_FONT)
1341 #undef SYSFNT
1342 }
1343
1344 return wxNullFont;
1345 }
1346
1347 wxFont wxXmlResourceHandler::GetFont(const wxString& param)
1348 {
1349 wxXmlNode *font_node = GetParamNode(param);
1350 if (font_node == NULL)
1351 {
1352 wxLogError(_("Cannot find font node '%s'."), param.c_str());
1353 return wxNullFont;
1354 }
1355
1356 wxXmlNode *oldnode = m_node;
1357 m_node = font_node;
1358
1359 // font attributes:
1360
1361 // size
1362 int isize = -1;
1363 bool hasSize = HasParam(wxT("size"));
1364 if (hasSize)
1365 isize = GetLong(wxT("size"), -1);
1366
1367 // style
1368 int istyle = wxNORMAL;
1369 bool hasStyle = HasParam(wxT("style"));
1370 if (hasStyle)
1371 {
1372 wxString style = GetParamValue(wxT("style"));
1373 if (style == wxT("italic"))
1374 istyle = wxITALIC;
1375 else if (style == wxT("slant"))
1376 istyle = wxSLANT;
1377 }
1378
1379 // weight
1380 int iweight = wxNORMAL;
1381 bool hasWeight = HasParam(wxT("weight"));
1382 if (hasWeight)
1383 {
1384 wxString weight = GetParamValue(wxT("weight"));
1385 if (weight == wxT("bold"))
1386 iweight = wxBOLD;
1387 else if (weight == wxT("light"))
1388 iweight = wxLIGHT;
1389 }
1390
1391 // underline
1392 bool hasUnderlined = HasParam(wxT("underlined"));
1393 bool underlined = hasUnderlined ? GetBool(wxT("underlined"), false) : false;
1394
1395 // family and facename
1396 int ifamily = wxDEFAULT;
1397 bool hasFamily = HasParam(wxT("family"));
1398 if (hasFamily)
1399 {
1400 wxString family = GetParamValue(wxT("family"));
1401 if (family == wxT("decorative")) ifamily = wxDECORATIVE;
1402 else if (family == wxT("roman")) ifamily = wxROMAN;
1403 else if (family == wxT("script")) ifamily = wxSCRIPT;
1404 else if (family == wxT("swiss")) ifamily = wxSWISS;
1405 else if (family == wxT("modern")) ifamily = wxMODERN;
1406 else if (family == wxT("teletype")) ifamily = wxTELETYPE;
1407 }
1408
1409
1410 wxString facename;
1411 bool hasFacename = HasParam(wxT("face"));
1412 if (hasFacename)
1413 {
1414 wxString faces = GetParamValue(wxT("face"));
1415 wxStringTokenizer tk(faces, wxT(","));
1416 #if wxUSE_FONTENUM
1417 wxArrayString facenames(wxFontEnumerator::GetFacenames());
1418 while (tk.HasMoreTokens())
1419 {
1420 int index = facenames.Index(tk.GetNextToken(), false);
1421 if (index != wxNOT_FOUND)
1422 {
1423 facename = facenames[index];
1424 break;
1425 }
1426 }
1427 #else // !wxUSE_FONTENUM
1428 // just use the first face name if we can't check its availability:
1429 if (tk.HasMoreTokens())
1430 facename = tk.GetNextToken();
1431 #endif // wxUSE_FONTENUM/!wxUSE_FONTENUM
1432 }
1433
1434 // encoding
1435 wxFontEncoding enc = wxFONTENCODING_DEFAULT;
1436 bool hasEncoding = HasParam(wxT("encoding"));
1437 if (hasEncoding)
1438 {
1439 wxString encoding = GetParamValue(wxT("encoding"));
1440 wxFontMapper mapper;
1441 if (!encoding.empty())
1442 enc = mapper.CharsetToEncoding(encoding);
1443 if (enc == wxFONTENCODING_SYSTEM)
1444 enc = wxFONTENCODING_DEFAULT;
1445 }
1446
1447 // is this font based on a system font?
1448 wxFont font = GetSystemFont(GetParamValue(wxT("sysfont")));
1449
1450 if (font.Ok())
1451 {
1452 if (hasSize && isize != -1)
1453 font.SetPointSize(isize);
1454 else if (HasParam(wxT("relativesize")))
1455 font.SetPointSize(int(font.GetPointSize() *
1456 GetFloat(wxT("relativesize"))));
1457
1458 if (hasStyle)
1459 font.SetStyle(istyle);
1460 if (hasWeight)
1461 font.SetWeight(iweight);
1462 if (hasUnderlined)
1463 font.SetUnderlined(underlined);
1464 if (hasFamily)
1465 font.SetFamily(ifamily);
1466 if (hasFacename)
1467 font.SetFaceName(facename);
1468 if (hasEncoding)
1469 font.SetDefaultEncoding(enc);
1470 }
1471 else // not based on system font
1472 {
1473 font = wxFont(isize == -1 ? wxNORMAL_FONT->GetPointSize() : isize,
1474 ifamily, istyle, iweight,
1475 underlined, facename, enc);
1476 }
1477
1478 m_node = oldnode;
1479 return font;
1480 }
1481
1482
1483 void wxXmlResourceHandler::SetupWindow(wxWindow *wnd)
1484 {
1485 //FIXME : add cursor
1486
1487 if (HasParam(wxT("exstyle")))
1488 // Have to OR it with existing style, since
1489 // some implementations (e.g. wxGTK) use the extra style
1490 // during creation
1491 wnd->SetExtraStyle(wnd->GetExtraStyle() | GetStyle(wxT("exstyle")));
1492 if (HasParam(wxT("bg")))
1493 wnd->SetBackgroundColour(GetColour(wxT("bg")));
1494 if (HasParam(wxT("fg")))
1495 wnd->SetForegroundColour(GetColour(wxT("fg")));
1496 if (GetBool(wxT("enabled"), 1) == 0)
1497 wnd->Enable(false);
1498 if (GetBool(wxT("focused"), 0) == 1)
1499 wnd->SetFocus();
1500 if (GetBool(wxT("hidden"), 0) == 1)
1501 wnd->Show(false);
1502 #if wxUSE_TOOLTIPS
1503 if (HasParam(wxT("tooltip")))
1504 wnd->SetToolTip(GetText(wxT("tooltip")));
1505 #endif
1506 if (HasParam(wxT("font")))
1507 wnd->SetFont(GetFont());
1508 if (HasParam(wxT("help")))
1509 wnd->SetHelpText(GetText(wxT("help")));
1510 }
1511
1512
1513 void wxXmlResourceHandler::CreateChildren(wxObject *parent, bool this_hnd_only)
1514 {
1515 wxXmlNode *n = m_node->GetChildren();
1516
1517 while (n)
1518 {
1519 if (n->GetType() == wxXML_ELEMENT_NODE &&
1520 (n->GetName() == wxT("object") || n->GetName() == wxT("object_ref")))
1521 {
1522 m_resource->CreateResFromNode(n, parent, NULL,
1523 this_hnd_only ? this : NULL);
1524 }
1525 n = n->GetNext();
1526 }
1527 }
1528
1529
1530 void wxXmlResourceHandler::CreateChildrenPrivately(wxObject *parent, wxXmlNode *rootnode)
1531 {
1532 wxXmlNode *root;
1533 if (rootnode == NULL) root = m_node; else root = rootnode;
1534 wxXmlNode *n = root->GetChildren();
1535
1536 while (n)
1537 {
1538 if (n->GetType() == wxXML_ELEMENT_NODE && CanHandle(n))
1539 {
1540 CreateResource(n, parent, NULL);
1541 }
1542 n = n->GetNext();
1543 }
1544 }
1545
1546
1547
1548
1549
1550
1551
1552 // --------------- XRCID implementation -----------------------------
1553
1554 #define XRCID_TABLE_SIZE 1024
1555
1556
1557 struct XRCID_record
1558 {
1559 /* Hold the id so that once an id is allocated for a name, it
1560 does not get created again by NewControlId at least
1561 until we are done with it */
1562 wxWindowIDRef id;
1563 char *key;
1564 XRCID_record *next;
1565 };
1566
1567 static XRCID_record *XRCID_Records[XRCID_TABLE_SIZE] = {NULL};
1568
1569 static int XRCID_Lookup(const char *str_id, int value_if_not_found = wxID_NONE)
1570 {
1571 int index = 0;
1572
1573 for (const char *c = str_id; *c != '\0'; c++) index += (int)*c;
1574 index %= XRCID_TABLE_SIZE;
1575
1576 XRCID_record *oldrec = NULL;
1577 for (XRCID_record *rec = XRCID_Records[index]; rec; rec = rec->next)
1578 {
1579 if (wxStrcmp(rec->key, str_id) == 0)
1580 {
1581 return rec->id;
1582 }
1583 oldrec = rec;
1584 }
1585
1586 XRCID_record **rec_var = (oldrec == NULL) ?
1587 &XRCID_Records[index] : &oldrec->next;
1588 *rec_var = new XRCID_record;
1589 (*rec_var)->key = wxStrdup(str_id);
1590 (*rec_var)->next = NULL;
1591
1592 char *end;
1593 if (value_if_not_found != wxID_NONE)
1594 (*rec_var)->id = value_if_not_found;
1595 else
1596 {
1597 int asint = wxStrtol(str_id, &end, 10);
1598 if (*str_id && *end == 0)
1599 {
1600 // if str_id was integer, keep it verbosely:
1601 (*rec_var)->id = asint;
1602 }
1603 else
1604 {
1605 (*rec_var)->id = wxWindowBase::NewControlId();
1606 }
1607 }
1608
1609 return (*rec_var)->id;
1610 }
1611
1612 static void AddStdXRCID_Records();
1613
1614 /*static*/
1615 int wxXmlResource::DoGetXRCID(const char *str_id, int value_if_not_found)
1616 {
1617 static bool s_stdIDsAdded = false;
1618
1619 if ( !s_stdIDsAdded )
1620 {
1621 s_stdIDsAdded = true;
1622 AddStdXRCID_Records();
1623 }
1624
1625 return XRCID_Lookup(str_id, value_if_not_found);
1626 }
1627
1628 /* static */
1629 wxString wxXmlResource::FindXRCIDById(int numId)
1630 {
1631 for ( int i = 0; i < XRCID_TABLE_SIZE; i++ )
1632 {
1633 for ( XRCID_record *rec = XRCID_Records[i]; rec; rec = rec->next )
1634 {
1635 if ( rec->id == numId )
1636 return wxString(rec->key);
1637 }
1638 }
1639
1640 return wxString();
1641 }
1642
1643 static void CleanXRCID_Record(XRCID_record *rec)
1644 {
1645 if (rec)
1646 {
1647 CleanXRCID_Record(rec->next);
1648
1649 free(rec->key);
1650 delete rec;
1651 }
1652 }
1653
1654 static void CleanXRCID_Records()
1655 {
1656 for (int i = 0; i < XRCID_TABLE_SIZE; i++)
1657 {
1658 CleanXRCID_Record(XRCID_Records[i]);
1659 XRCID_Records[i] = NULL;
1660 }
1661 }
1662
1663 static void AddStdXRCID_Records()
1664 {
1665 #define stdID(id) XRCID_Lookup(#id, id)
1666 stdID(-1);
1667
1668 stdID(wxID_ANY);
1669 stdID(wxID_SEPARATOR);
1670
1671 stdID(wxID_OPEN);
1672 stdID(wxID_CLOSE);
1673 stdID(wxID_NEW);
1674 stdID(wxID_SAVE);
1675 stdID(wxID_SAVEAS);
1676 stdID(wxID_REVERT);
1677 stdID(wxID_EXIT);
1678 stdID(wxID_UNDO);
1679 stdID(wxID_REDO);
1680 stdID(wxID_HELP);
1681 stdID(wxID_PRINT);
1682 stdID(wxID_PRINT_SETUP);
1683 stdID(wxID_PAGE_SETUP);
1684 stdID(wxID_PREVIEW);
1685 stdID(wxID_ABOUT);
1686 stdID(wxID_HELP_CONTENTS);
1687 stdID(wxID_HELP_COMMANDS);
1688 stdID(wxID_HELP_PROCEDURES);
1689 stdID(wxID_HELP_CONTEXT);
1690 stdID(wxID_CLOSE_ALL);
1691 stdID(wxID_PREFERENCES);
1692 stdID(wxID_EDIT);
1693 stdID(wxID_CUT);
1694 stdID(wxID_COPY);
1695 stdID(wxID_PASTE);
1696 stdID(wxID_CLEAR);
1697 stdID(wxID_FIND);
1698 stdID(wxID_DUPLICATE);
1699 stdID(wxID_SELECTALL);
1700 stdID(wxID_DELETE);
1701 stdID(wxID_REPLACE);
1702 stdID(wxID_REPLACE_ALL);
1703 stdID(wxID_PROPERTIES);
1704 stdID(wxID_VIEW_DETAILS);
1705 stdID(wxID_VIEW_LARGEICONS);
1706 stdID(wxID_VIEW_SMALLICONS);
1707 stdID(wxID_VIEW_LIST);
1708 stdID(wxID_VIEW_SORTDATE);
1709 stdID(wxID_VIEW_SORTNAME);
1710 stdID(wxID_VIEW_SORTSIZE);
1711 stdID(wxID_VIEW_SORTTYPE);
1712 stdID(wxID_FILE1);
1713 stdID(wxID_FILE2);
1714 stdID(wxID_FILE3);
1715 stdID(wxID_FILE4);
1716 stdID(wxID_FILE5);
1717 stdID(wxID_FILE6);
1718 stdID(wxID_FILE7);
1719 stdID(wxID_FILE8);
1720 stdID(wxID_FILE9);
1721 stdID(wxID_OK);
1722 stdID(wxID_CANCEL);
1723 stdID(wxID_APPLY);
1724 stdID(wxID_YES);
1725 stdID(wxID_NO);
1726 stdID(wxID_STATIC);
1727 stdID(wxID_FORWARD);
1728 stdID(wxID_BACKWARD);
1729 stdID(wxID_DEFAULT);
1730 stdID(wxID_MORE);
1731 stdID(wxID_SETUP);
1732 stdID(wxID_RESET);
1733 stdID(wxID_CONTEXT_HELP);
1734 stdID(wxID_YESTOALL);
1735 stdID(wxID_NOTOALL);
1736 stdID(wxID_ABORT);
1737 stdID(wxID_RETRY);
1738 stdID(wxID_IGNORE);
1739 stdID(wxID_ADD);
1740 stdID(wxID_REMOVE);
1741 stdID(wxID_UP);
1742 stdID(wxID_DOWN);
1743 stdID(wxID_HOME);
1744 stdID(wxID_REFRESH);
1745 stdID(wxID_STOP);
1746 stdID(wxID_INDEX);
1747 stdID(wxID_BOLD);
1748 stdID(wxID_ITALIC);
1749 stdID(wxID_JUSTIFY_CENTER);
1750 stdID(wxID_JUSTIFY_FILL);
1751 stdID(wxID_JUSTIFY_RIGHT);
1752 stdID(wxID_JUSTIFY_LEFT);
1753 stdID(wxID_UNDERLINE);
1754 stdID(wxID_INDENT);
1755 stdID(wxID_UNINDENT);
1756 stdID(wxID_ZOOM_100);
1757 stdID(wxID_ZOOM_FIT);
1758 stdID(wxID_ZOOM_IN);
1759 stdID(wxID_ZOOM_OUT);
1760 stdID(wxID_UNDELETE);
1761 stdID(wxID_REVERT_TO_SAVED);
1762 stdID(wxID_SYSTEM_MENU);
1763 stdID(wxID_CLOSE_FRAME);
1764 stdID(wxID_MOVE_FRAME);
1765 stdID(wxID_RESIZE_FRAME);
1766 stdID(wxID_MAXIMIZE_FRAME);
1767 stdID(wxID_ICONIZE_FRAME);
1768 stdID(wxID_RESTORE_FRAME);
1769 stdID(wxID_CDROM);
1770 stdID(wxID_CONVERT);
1771 stdID(wxID_EXECUTE);
1772 stdID(wxID_FLOPPY);
1773 stdID(wxID_HARDDISK);
1774 stdID(wxID_BOTTOM);
1775 stdID(wxID_FIRST);
1776 stdID(wxID_LAST);
1777 stdID(wxID_TOP);
1778 stdID(wxID_INFO);
1779 stdID(wxID_JUMP_TO);
1780 stdID(wxID_NETWORK);
1781 stdID(wxID_SELECT_COLOR);
1782 stdID(wxID_SELECT_FONT);
1783 stdID(wxID_SORT_ASCENDING);
1784 stdID(wxID_SORT_DESCENDING);
1785 stdID(wxID_SPELL_CHECK);
1786 stdID(wxID_STRIKETHROUGH);
1787
1788 #undef stdID
1789 }
1790
1791
1792
1793
1794
1795 // --------------- module and globals -----------------------------
1796
1797 // normally we would do the cleanup from wxXmlResourceModule::OnExit() but it
1798 // can happen that some XRC records have been created because of the use of
1799 // XRCID() in event tables, which happens during static objects initialization,
1800 // but then the application initialization failed and so the wx modules were
1801 // neither initialized nor cleaned up -- this static object does the cleanup in
1802 // this case
1803 static struct wxXRCStaticCleanup
1804 {
1805 ~wxXRCStaticCleanup() { CleanXRCID_Records(); }
1806 } s_staticCleanup;
1807
1808 class wxXmlResourceModule: public wxModule
1809 {
1810 DECLARE_DYNAMIC_CLASS(wxXmlResourceModule)
1811 public:
1812 wxXmlResourceModule() {}
1813 bool OnInit()
1814 {
1815 wxXmlResource::AddSubclassFactory(new wxXmlSubclassFactoryCXX);
1816 return true;
1817 }
1818 void OnExit()
1819 {
1820 delete wxXmlResource::Set(NULL);
1821 if(wxXmlResource::ms_subclassFactories)
1822 {
1823 for ( wxXmlSubclassFactories::iterator i = wxXmlResource::ms_subclassFactories->begin();
1824 i != wxXmlResource::ms_subclassFactories->end(); ++i )
1825 {
1826 delete *i;
1827 }
1828 wxDELETE(wxXmlResource::ms_subclassFactories);
1829 }
1830 CleanXRCID_Records();
1831 }
1832 };
1833
1834 IMPLEMENT_DYNAMIC_CLASS(wxXmlResourceModule, wxModule)
1835
1836
1837 // When wxXml is loaded dynamically after the application is already running
1838 // then the built-in module system won't pick this one up. Add it manually.
1839 void wxXmlInitResourceModule()
1840 {
1841 wxModule* module = new wxXmlResourceModule;
1842 module->Init();
1843 wxModule::RegisterModule(module);
1844 }
1845
1846 #endif // wxUSE_XRC