]> git.saurik.com Git - wxWidgets.git/blob - src/xrc/xmlres.cpp
Rename delegates to try and stop name clashes, probably with wxWebKitCtrl.
[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 #include "wx/imaglist.h"
48 #include "wx/dir.h"
49 #include "wx/xml/xml.h"
50 #include "wx/hashset.h"
51 #include "wx/scopedptr.h"
52
53 namespace
54 {
55
56 // Helper function to get modification time of either a wxFileSystem URI or
57 // just a normal file name, depending on the build.
58 #if wxUSE_DATETIME
59
60 wxDateTime GetXRCFileModTime(const wxString& filename)
61 {
62 #if wxUSE_FILESYSTEM
63 wxFileSystem fsys;
64 wxScopedPtr<wxFSFile> file(fsys.OpenFile(filename));
65
66 return file ? file->GetModificationTime() : wxDateTime();
67 #else // wxUSE_FILESYSTEM
68 return wxDateTime(wxFileModificationTime(filename));
69 #endif // wxUSE_FILESYSTEM
70 }
71
72 #endif // wxUSE_DATETIME
73
74 } // anonymous namespace
75
76 class wxXmlResourceDataRecord
77 {
78 public:
79 // Ctor takes ownership of the document pointer.
80 wxXmlResourceDataRecord(const wxString& File_,
81 wxXmlDocument *Doc_
82 )
83 : File(File_), Doc(Doc_)
84 {
85 #if wxUSE_DATETIME
86 Time = GetXRCFileModTime(File);
87 #endif
88 }
89
90 ~wxXmlResourceDataRecord() {delete Doc;}
91
92 wxString File;
93 wxXmlDocument *Doc;
94 #if wxUSE_DATETIME
95 wxDateTime Time;
96 #endif
97
98 wxDECLARE_NO_COPY_CLASS(wxXmlResourceDataRecord);
99 };
100
101 class wxXmlResourceDataRecords : public wxVector<wxXmlResourceDataRecord*>
102 {
103 // this is a class so that it can be forward-declared
104 };
105
106 WX_DECLARE_HASH_SET(int, wxIntegerHash, wxIntegerEqual, wxHashSetInt);
107
108 class wxIdRange // Holds data for a particular rangename
109 {
110 protected:
111 wxIdRange(const wxXmlNode* node,
112 const wxString& rname,
113 const wxString& startno,
114 const wxString& rsize);
115
116 // Note the existence of an item within the range
117 void NoteItem(const wxXmlNode* node, const wxString& item);
118
119 // The manager is telling us that it's finished adding items
120 void Finalise(const wxXmlNode* node);
121
122 wxString GetName() const { return m_name; }
123 bool IsFinalised() const { return m_finalised; }
124
125 const wxString m_name;
126 int m_start;
127 int m_end;
128 unsigned int m_size;
129 bool m_item_end_found;
130 bool m_finalised;
131 wxHashSetInt m_indices;
132
133 friend class wxIdRangeManager;
134 };
135
136 class wxIdRangeManager
137 {
138 public:
139 ~wxIdRangeManager();
140 // Gets the global resources object or creates one if none exists.
141 static wxIdRangeManager *Get();
142
143 // Sets the global resources object and returns a pointer to the previous
144 // one (may be NULL).
145 static wxIdRangeManager *Set(wxIdRangeManager *res);
146
147 // Create a new IDrange from this node
148 void AddRange(const wxXmlNode* node);
149 // Tell the IdRange that this item exists, and should be pre-allocated an ID
150 void NotifyRangeOfItem(const wxXmlNode* node, const wxString& item) const;
151 // Tells all IDranges that they're now complete, and can create their IDs
152 void FinaliseRanges(const wxXmlNode* node) const;
153 // Searches for a known IdRange matching 'name', returning its index or -1
154 int Find(const wxString& rangename) const;
155 // Removes, if it exists, an entry from the XRCID table. Used in id-ranges
156 // to replace defunct or statically-initialised entries with current values
157 static void RemoveXRCIDEntry(const wxString& idstr);
158
159 protected:
160 wxIdRange* FindRangeForItem(const wxXmlNode* node,
161 const wxString& item,
162 wxString& value) const;
163 wxVector<wxIdRange*> m_IdRanges;
164
165 private:
166 static wxIdRangeManager *ms_instance;
167 };
168
169 namespace
170 {
171
172 // helper used by DoFindResource() and elsewhere: returns true if this is an
173 // object or object_ref node
174 //
175 // node must be non-NULL
176 inline bool IsObjectNode(wxXmlNode *node)
177 {
178 return node->GetType() == wxXML_ELEMENT_NODE &&
179 (node->GetName() == wxS("object") ||
180 node->GetName() == wxS("object_ref"));
181 }
182
183 // special XML attribute with name of input file, see GetFileNameFromNode()
184 const char *ATTR_INPUT_FILENAME = "__wx:filename";
185
186 // helper to get filename corresponding to an XML node
187 wxString
188 GetFileNameFromNode(const wxXmlNode *node, const wxXmlResourceDataRecords& files)
189 {
190 // this loop does two things: it looks for ATTR_INPUT_FILENAME among
191 // parents and if it isn't used, it finds the root of the XML tree 'node'
192 // is in
193 for ( ;; )
194 {
195 // in some rare cases (specifically, when an <object_ref> is used, see
196 // wxXmlResource::CreateResFromNode() and MergeNodesOver()), we work
197 // with XML nodes that are not rooted in any document from 'files'
198 // (because a new node was created by CreateResFromNode() to merge the
199 // content of <object_ref> and the referenced <object>); in that case,
200 // we hack around the problem by putting the information about input
201 // file into a custom attribute
202 if ( node->HasAttribute(ATTR_INPUT_FILENAME) )
203 return node->GetAttribute(ATTR_INPUT_FILENAME);
204
205 if ( !node->GetParent() )
206 break; // we found the root of this XML tree
207
208 node = node->GetParent();
209 }
210
211 // NB: 'node' now points to the root of XML document
212
213 for ( wxXmlResourceDataRecords::const_iterator i = files.begin();
214 i != files.end(); ++i )
215 {
216 if ( (*i)->Doc->GetRoot() == node )
217 {
218 return (*i)->File;
219 }
220 }
221
222 return wxEmptyString; // not found
223 }
224
225 } // anonymous namespace
226
227
228 wxXmlResource *wxXmlResource::ms_instance = NULL;
229
230 /*static*/ wxXmlResource *wxXmlResource::Get()
231 {
232 if ( !ms_instance )
233 ms_instance = new wxXmlResource;
234 return ms_instance;
235 }
236
237 /*static*/ wxXmlResource *wxXmlResource::Set(wxXmlResource *res)
238 {
239 wxXmlResource *old = ms_instance;
240 ms_instance = res;
241 return old;
242 }
243
244 wxXmlResource::wxXmlResource(int flags, const wxString& domain)
245 {
246 m_flags = flags;
247 m_version = -1;
248 m_data = new wxXmlResourceDataRecords;
249 SetDomain(domain);
250 }
251
252 wxXmlResource::wxXmlResource(const wxString& filemask, int flags, const wxString& domain)
253 {
254 m_flags = flags;
255 m_version = -1;
256 m_data = new wxXmlResourceDataRecords;
257 SetDomain(domain);
258 Load(filemask);
259 }
260
261 wxXmlResource::~wxXmlResource()
262 {
263 ClearHandlers();
264
265 for ( wxXmlResourceDataRecords::iterator i = m_data->begin();
266 i != m_data->end(); ++i )
267 {
268 delete *i;
269 }
270 delete m_data;
271 }
272
273 void wxXmlResource::SetDomain(const wxString& domain)
274 {
275 m_domain = domain;
276 }
277
278
279 /* static */
280 wxString wxXmlResource::ConvertFileNameToURL(const wxString& filename)
281 {
282 wxString fnd(filename);
283
284 // NB: as Load() and Unload() accept both filenames and URLs (should
285 // probably be changed to filenames only, but embedded resources
286 // currently rely on its ability to handle URLs - FIXME) we need to
287 // determine whether found name is filename and not URL and this is the
288 // fastest/simplest way to do it
289 if (wxFileName::FileExists(fnd))
290 {
291 // Make the name absolute filename, because the app may
292 // change working directory later:
293 wxFileName fn(fnd);
294 if (fn.IsRelative())
295 {
296 fn.MakeAbsolute();
297 fnd = fn.GetFullPath();
298 }
299 #if wxUSE_FILESYSTEM
300 fnd = wxFileSystem::FileNameToURL(fnd);
301 #endif
302 }
303
304 return fnd;
305 }
306
307 #if wxUSE_FILESYSTEM
308
309 /* static */
310 bool wxXmlResource::IsArchive(const wxString& filename)
311 {
312 const wxString fnd = filename.Lower();
313
314 return fnd.Matches(wxT("*.zip")) || fnd.Matches(wxT("*.xrs"));
315 }
316
317 #endif // wxUSE_FILESYSTEM
318
319 bool wxXmlResource::LoadFile(const wxFileName& file)
320 {
321 #if wxUSE_FILESYSTEM
322 return Load(wxFileSystem::FileNameToURL(file));
323 #else
324 return Load(file.GetFullPath());
325 #endif
326 }
327
328 bool wxXmlResource::LoadAllFiles(const wxString& dirname)
329 {
330 bool ok = true;
331 wxArrayString files;
332
333 wxDir::GetAllFiles(dirname, &files, "*.xrc");
334
335 for ( wxArrayString::const_iterator i = files.begin(); i != files.end(); ++i )
336 {
337 if ( !LoadFile(*i) )
338 ok = false;
339 }
340
341 return ok;
342 }
343
344 bool wxXmlResource::Load(const wxString& filemask_)
345 {
346 wxString filemask = ConvertFileNameToURL(filemask_);
347
348 bool allOK = true;
349
350 #if wxUSE_FILESYSTEM
351 wxFileSystem fsys;
352 # define wxXmlFindFirst fsys.FindFirst(filemask, wxFILE)
353 # define wxXmlFindNext fsys.FindNext()
354 #else
355 # define wxXmlFindFirst wxFindFirstFile(filemask, wxFILE)
356 # define wxXmlFindNext wxFindNextFile()
357 #endif
358 wxString fnd = wxXmlFindFirst;
359 if ( fnd.empty() )
360 {
361 wxLogError(_("Cannot load resources from '%s'."), filemask);
362 return false;
363 }
364
365 while (!fnd.empty())
366 {
367 #if wxUSE_FILESYSTEM
368 if ( IsArchive(fnd) )
369 {
370 if ( !Load(fnd + wxT("#zip:*.xrc")) )
371 allOK = false;
372 }
373 else // a single resource URL
374 #endif // wxUSE_FILESYSTEM
375 {
376 wxXmlDocument * const doc = DoLoadFile(fnd);
377 if ( !doc )
378 allOK = false;
379 else
380 Data().push_back(new wxXmlResourceDataRecord(fnd, doc));
381 }
382
383 fnd = wxXmlFindNext;
384 }
385 # undef wxXmlFindFirst
386 # undef wxXmlFindNext
387
388 return allOK;
389 }
390
391 bool wxXmlResource::Unload(const wxString& filename)
392 {
393 wxASSERT_MSG( !wxIsWild(filename),
394 wxT("wildcards not supported by wxXmlResource::Unload()") );
395
396 wxString fnd = ConvertFileNameToURL(filename);
397 #if wxUSE_FILESYSTEM
398 const bool isArchive = IsArchive(fnd);
399 if ( isArchive )
400 fnd += wxT("#zip:");
401 #endif // wxUSE_FILESYSTEM
402
403 bool unloaded = false;
404 for ( wxXmlResourceDataRecords::iterator i = Data().begin();
405 i != Data().end(); ++i )
406 {
407 #if wxUSE_FILESYSTEM
408 if ( isArchive )
409 {
410 if ( (*i)->File.StartsWith(fnd) )
411 unloaded = true;
412 // don't break from the loop, we can have other matching files
413 }
414 else // a single resource URL
415 #endif // wxUSE_FILESYSTEM
416 {
417 if ( (*i)->File == fnd )
418 {
419 delete *i;
420 Data().erase(i);
421 unloaded = true;
422
423 // no sense in continuing, there is only one file with this URL
424 break;
425 }
426 }
427 }
428
429 return unloaded;
430 }
431
432
433 IMPLEMENT_ABSTRACT_CLASS(wxXmlResourceHandler, wxObject)
434
435 void wxXmlResource::AddHandler(wxXmlResourceHandler *handler)
436 {
437 m_handlers.push_back(handler);
438 handler->SetParentResource(this);
439 }
440
441 void wxXmlResource::InsertHandler(wxXmlResourceHandler *handler)
442 {
443 m_handlers.insert(m_handlers.begin(), handler);
444 handler->SetParentResource(this);
445 }
446
447
448
449 void wxXmlResource::ClearHandlers()
450 {
451 for ( wxVector<wxXmlResourceHandler*>::iterator i = m_handlers.begin();
452 i != m_handlers.end(); ++i )
453 delete *i;
454 m_handlers.clear();
455 }
456
457
458 wxMenu *wxXmlResource::LoadMenu(const wxString& name)
459 {
460 return (wxMenu*)CreateResFromNode(FindResource(name, wxT("wxMenu")), NULL, NULL);
461 }
462
463
464
465 wxMenuBar *wxXmlResource::LoadMenuBar(wxWindow *parent, const wxString& name)
466 {
467 return (wxMenuBar*)CreateResFromNode(FindResource(name, wxT("wxMenuBar")), parent, NULL);
468 }
469
470
471
472 #if wxUSE_TOOLBAR
473 wxToolBar *wxXmlResource::LoadToolBar(wxWindow *parent, const wxString& name)
474 {
475 return (wxToolBar*)CreateResFromNode(FindResource(name, wxT("wxToolBar")), parent, NULL);
476 }
477 #endif
478
479
480 wxDialog *wxXmlResource::LoadDialog(wxWindow *parent, const wxString& name)
481 {
482 return (wxDialog*)CreateResFromNode(FindResource(name, wxT("wxDialog")), parent, NULL);
483 }
484
485 bool wxXmlResource::LoadDialog(wxDialog *dlg, wxWindow *parent, const wxString& name)
486 {
487 return CreateResFromNode(FindResource(name, wxT("wxDialog")), parent, dlg) != NULL;
488 }
489
490
491
492 wxPanel *wxXmlResource::LoadPanel(wxWindow *parent, const wxString& name)
493 {
494 return (wxPanel*)CreateResFromNode(FindResource(name, wxT("wxPanel")), parent, NULL);
495 }
496
497 bool wxXmlResource::LoadPanel(wxPanel *panel, wxWindow *parent, const wxString& name)
498 {
499 return CreateResFromNode(FindResource(name, wxT("wxPanel")), parent, panel) != NULL;
500 }
501
502 wxFrame *wxXmlResource::LoadFrame(wxWindow* parent, const wxString& name)
503 {
504 return (wxFrame*)CreateResFromNode(FindResource(name, wxT("wxFrame")), parent, NULL);
505 }
506
507 bool wxXmlResource::LoadFrame(wxFrame* frame, wxWindow *parent, const wxString& name)
508 {
509 return CreateResFromNode(FindResource(name, wxT("wxFrame")), parent, frame) != NULL;
510 }
511
512 wxBitmap wxXmlResource::LoadBitmap(const wxString& name)
513 {
514 wxBitmap *bmp = (wxBitmap*)CreateResFromNode(
515 FindResource(name, wxT("wxBitmap")), NULL, NULL);
516 wxBitmap rt;
517
518 if (bmp) { rt = *bmp; delete bmp; }
519 return rt;
520 }
521
522 wxIcon wxXmlResource::LoadIcon(const wxString& name)
523 {
524 wxIcon *icon = (wxIcon*)CreateResFromNode(
525 FindResource(name, wxT("wxIcon")), NULL, NULL);
526 wxIcon rt;
527
528 if (icon) { rt = *icon; delete icon; }
529 return rt;
530 }
531
532
533 wxObject *
534 wxXmlResource::DoLoadObject(wxWindow *parent,
535 const wxString& name,
536 const wxString& classname,
537 bool recursive)
538 {
539 wxXmlNode * const node = FindResource(name, classname, recursive);
540
541 return node ? DoCreateResFromNode(*node, parent, NULL) : NULL;
542 }
543
544 bool
545 wxXmlResource::DoLoadObject(wxObject *instance,
546 wxWindow *parent,
547 const wxString& name,
548 const wxString& classname,
549 bool recursive)
550 {
551 wxXmlNode * const node = FindResource(name, classname, recursive);
552
553 return node && DoCreateResFromNode(*node, parent, instance) != NULL;
554 }
555
556
557 bool wxXmlResource::AttachUnknownControl(const wxString& name,
558 wxWindow *control, wxWindow *parent)
559 {
560 if (parent == NULL)
561 parent = control->GetParent();
562 wxWindow *container = parent->FindWindow(name + wxT("_container"));
563 if (!container)
564 {
565 wxLogError("Cannot find container for unknown control '%s'.", name);
566 return false;
567 }
568 return control->Reparent(container);
569 }
570
571
572 static void ProcessPlatformProperty(wxXmlNode *node)
573 {
574 wxString s;
575 bool isok;
576
577 wxXmlNode *c = node->GetChildren();
578 while (c)
579 {
580 isok = false;
581 if (!c->GetAttribute(wxT("platform"), &s))
582 isok = true;
583 else
584 {
585 wxStringTokenizer tkn(s, wxT(" |"));
586
587 while (tkn.HasMoreTokens())
588 {
589 s = tkn.GetNextToken();
590 #ifdef __WINDOWS__
591 if (s == wxT("win")) isok = true;
592 #endif
593 #if defined(__MAC__) || defined(__APPLE__)
594 if (s == wxT("mac")) isok = true;
595 #elif defined(__UNIX__)
596 if (s == wxT("unix")) isok = true;
597 #endif
598 #ifdef __OS2__
599 if (s == wxT("os2")) isok = true;
600 #endif
601
602 if (isok)
603 break;
604 }
605 }
606
607 if (isok)
608 {
609 ProcessPlatformProperty(c);
610 c = c->GetNext();
611 }
612 else
613 {
614 wxXmlNode *c2 = c->GetNext();
615 node->RemoveChild(c);
616 delete c;
617 c = c2;
618 }
619 }
620 }
621
622 static void PreprocessForIdRanges(wxXmlNode *rootnode)
623 {
624 // First go through the top level, looking for the names of ID ranges
625 // as processing items is a lot easier if names are already known
626 wxXmlNode *c = rootnode->GetChildren();
627 while (c)
628 {
629 if (c->GetName() == wxT("ids-range"))
630 wxIdRangeManager::Get()->AddRange(c);
631 c = c->GetNext();
632 }
633
634 // Next, examine every 'name' for the '[' that denotes an ID in a range
635 c = rootnode->GetChildren();
636 while (c)
637 {
638 wxString name = c->GetAttribute(wxT("name"));
639 if (name.find('[') != wxString::npos)
640 wxIdRangeManager::Get()->NotifyRangeOfItem(rootnode, name);
641
642 // Do any children by recursion, then proceed to the next sibling
643 PreprocessForIdRanges(c);
644 c = c->GetNext();
645 }
646 }
647
648 bool wxXmlResource::UpdateResources()
649 {
650 bool rt = true;
651
652 for ( wxXmlResourceDataRecords::iterator i = Data().begin();
653 i != Data().end(); ++i )
654 {
655 wxXmlResourceDataRecord* const rec = *i;
656
657 // Check if we need to reload this one.
658
659 // We never do it if this flag is specified.
660 if ( m_flags & wxXRC_NO_RELOADING )
661 continue;
662
663 // Otherwise check its modification time if we can.
664 #if wxUSE_DATETIME
665 const wxDateTime lastModTime = GetXRCFileModTime(rec->File);
666
667 if ( lastModTime.IsValid() && lastModTime <= rec->Time )
668 #else // !wxUSE_DATETIME
669 // Never reload the file contents: we can't know whether it changed or
670 // not in this build configuration and it would be unexpected and
671 // counter-productive to get a performance hit (due to constant
672 // reloading of XRC files) in a minimal wx build which is presumably
673 // used because of resource constraints of the current platform.
674 #endif // wxUSE_DATETIME/!wxUSE_DATETIME
675 {
676 // No need to reload, the file wasn't modified since we did it
677 // last.
678 continue;
679 }
680
681 wxXmlDocument * const doc = DoLoadFile(rec->File);
682 if ( !doc )
683 {
684 // Notice that we keep the old XML document: it seems better to
685 // preserve it instead of throwing it away if we have nothing to
686 // replace it with.
687 rt = false;
688 continue;
689 }
690
691 // Replace the old resource contents with the new one.
692 delete rec->Doc;
693 rec->Doc = doc;
694
695 // And, now that we loaded it successfully, update the last load time.
696 #if wxUSE_DATETIME
697 rec->Time = lastModTime.IsValid() ? lastModTime : wxDateTime::Now();
698 #endif // wxUSE_DATETIME
699 }
700
701 return rt;
702 }
703
704 wxXmlDocument *wxXmlResource::DoLoadFile(const wxString& filename)
705 {
706 wxLogTrace(wxT("xrc"), wxT("opening file '%s'"), filename);
707
708 wxInputStream *stream = NULL;
709
710 #if wxUSE_FILESYSTEM
711 wxFileSystem fsys;
712 wxScopedPtr<wxFSFile> file(fsys.OpenFile(filename));
713 if (file)
714 {
715 // Notice that we don't have ownership of the stream in this case, it
716 // remains owned by wxFSFile.
717 stream = file->GetStream();
718 }
719 #else // !wxUSE_FILESYSTEM
720 wxFileInputStream fstream(filename);
721 stream = &fstream;
722 #endif // wxUSE_FILESYSTEM/!wxUSE_FILESYSTEM
723
724 if ( !stream || !stream->IsOk() )
725 {
726 wxLogError(_("Cannot open resources file '%s'."), filename);
727 return NULL;
728 }
729
730 wxString encoding(wxT("UTF-8"));
731 #if !wxUSE_UNICODE && wxUSE_INTL
732 if ( (GetFlags() & wxXRC_USE_LOCALE) == 0 )
733 {
734 // In case we are not using wxLocale to translate strings, convert the
735 // strings GUI's charset. This must not be done when wxXRC_USE_LOCALE
736 // is on, because it could break wxGetTranslation lookup.
737 encoding = wxLocale::GetSystemEncodingName();
738 }
739 #endif
740
741 wxScopedPtr<wxXmlDocument> doc(new wxXmlDocument);
742 if (!doc->Load(*stream, encoding))
743 {
744 wxLogError(_("Cannot load resources from file '%s'."), filename);
745 return NULL;
746 }
747
748 wxXmlNode * const root = doc->GetRoot();
749 if (root->GetName() != wxT("resource"))
750 {
751 ReportError
752 (
753 root,
754 "invalid XRC resource, doesn't have root node <resource>"
755 );
756 return NULL;
757 }
758
759 long version;
760 int v1, v2, v3, v4;
761 wxString verstr = root->GetAttribute(wxT("version"), wxT("0.0.0.0"));
762 if (wxSscanf(verstr, wxT("%i.%i.%i.%i"), &v1, &v2, &v3, &v4) == 4)
763 version = v1*256*256*256+v2*256*256+v3*256+v4;
764 else
765 version = 0;
766 if (m_version == -1)
767 m_version = version;
768 if (m_version != version)
769 {
770 wxLogWarning("Resource files must have same version number.");
771 }
772
773 ProcessPlatformProperty(root);
774 PreprocessForIdRanges(root);
775 wxIdRangeManager::Get()->FinaliseRanges(root);
776
777 return doc.release();
778 }
779
780 wxXmlNode *wxXmlResource::DoFindResource(wxXmlNode *parent,
781 const wxString& name,
782 const wxString& classname,
783 bool recursive) const
784 {
785 wxXmlNode *node;
786
787 // first search for match at the top-level nodes (as this is
788 // where the resource is most commonly looked for):
789 for (node = parent->GetChildren(); node; node = node->GetNext())
790 {
791 if ( IsObjectNode(node) && node->GetAttribute(wxS("name")) == name )
792 {
793 // empty class name matches everything
794 if ( classname.empty() )
795 return node;
796
797 wxString cls(node->GetAttribute(wxS("class")));
798
799 // object_ref may not have 'class' attribute:
800 if (cls.empty() && node->GetName() == wxS("object_ref"))
801 {
802 wxString refName = node->GetAttribute(wxS("ref"));
803 if (refName.empty())
804 continue;
805
806 const wxXmlNode * const refNode = GetResourceNode(refName);
807 if ( refNode )
808 cls = refNode->GetAttribute(wxS("class"));
809 }
810
811 if ( cls == classname )
812 return node;
813 }
814 }
815
816 // then recurse in child nodes
817 if ( recursive )
818 {
819 for (node = parent->GetChildren(); node; node = node->GetNext())
820 {
821 if ( IsObjectNode(node) )
822 {
823 wxXmlNode* found = DoFindResource(node, name, classname, true);
824 if ( found )
825 return found;
826 }
827 }
828 }
829
830 return NULL;
831 }
832
833 wxXmlNode *wxXmlResource::FindResource(const wxString& name,
834 const wxString& classname,
835 bool recursive)
836 {
837 wxString path;
838 wxXmlNode * const
839 node = GetResourceNodeAndLocation(name, classname, recursive, &path);
840
841 if ( !node )
842 {
843 ReportError
844 (
845 NULL,
846 wxString::Format
847 (
848 "XRC resource \"%s\" (class \"%s\") not found",
849 name, classname
850 )
851 );
852 }
853 #if wxUSE_FILESYSTEM
854 else // node was found
855 {
856 // ensure that relative paths work correctly when loading this node
857 // (which should happen as soon as we return as FindResource() result
858 // is always passed to CreateResFromNode())
859 m_curFileSystem.ChangePathTo(path);
860 }
861 #endif // wxUSE_FILESYSTEM
862
863 return node;
864 }
865
866 wxXmlNode *
867 wxXmlResource::GetResourceNodeAndLocation(const wxString& name,
868 const wxString& classname,
869 bool recursive,
870 wxString *path) const
871 {
872 // ensure everything is up-to-date: this is needed to support on-demand
873 // reloading of XRC files
874 const_cast<wxXmlResource *>(this)->UpdateResources();
875
876 for ( wxXmlResourceDataRecords::const_iterator f = Data().begin();
877 f != Data().end(); ++f )
878 {
879 wxXmlResourceDataRecord *const rec = *f;
880 wxXmlDocument * const doc = rec->Doc;
881 if ( !doc || !doc->GetRoot() )
882 continue;
883
884 wxXmlNode * const
885 found = DoFindResource(doc->GetRoot(), name, classname, recursive);
886 if ( found )
887 {
888 if ( path )
889 *path = rec->File;
890
891 return found;
892 }
893 }
894
895 return NULL;
896 }
897
898 static void MergeNodesOver(wxXmlNode& dest, wxXmlNode& overwriteWith,
899 const wxString& overwriteFilename)
900 {
901 // Merge attributes:
902 for ( wxXmlAttribute *attr = overwriteWith.GetAttributes();
903 attr; attr = attr->GetNext() )
904 {
905 wxXmlAttribute *dattr;
906 for (dattr = dest.GetAttributes(); dattr; dattr = dattr->GetNext())
907 {
908
909 if ( dattr->GetName() == attr->GetName() )
910 {
911 dattr->SetValue(attr->GetValue());
912 break;
913 }
914 }
915
916 if ( !dattr )
917 dest.AddAttribute(attr->GetName(), attr->GetValue());
918 }
919
920 // Merge child nodes:
921 for (wxXmlNode* node = overwriteWith.GetChildren(); node; node = node->GetNext())
922 {
923 wxString name = node->GetAttribute(wxT("name"), wxEmptyString);
924 wxXmlNode *dnode;
925
926 for (dnode = dest.GetChildren(); dnode; dnode = dnode->GetNext() )
927 {
928 if ( dnode->GetName() == node->GetName() &&
929 dnode->GetAttribute(wxT("name"), wxEmptyString) == name &&
930 dnode->GetType() == node->GetType() )
931 {
932 MergeNodesOver(*dnode, *node, overwriteFilename);
933 break;
934 }
935 }
936
937 if ( !dnode )
938 {
939 wxXmlNode *copyOfNode = new wxXmlNode(*node);
940 // remember referenced object's file, see GetFileNameFromNode()
941 copyOfNode->AddAttribute(ATTR_INPUT_FILENAME, overwriteFilename);
942
943 static const wxChar *AT_END = wxT("end");
944 wxString insert_pos = node->GetAttribute(wxT("insert_at"), AT_END);
945 if ( insert_pos == AT_END )
946 {
947 dest.AddChild(copyOfNode);
948 }
949 else if ( insert_pos == wxT("begin") )
950 {
951 dest.InsertChild(copyOfNode, dest.GetChildren());
952 }
953 }
954 }
955
956 if ( dest.GetType() == wxXML_TEXT_NODE && overwriteWith.GetContent().length() )
957 dest.SetContent(overwriteWith.GetContent());
958 }
959
960 wxObject *
961 wxXmlResource::DoCreateResFromNode(wxXmlNode& node,
962 wxObject *parent,
963 wxObject *instance,
964 wxXmlResourceHandler *handlerToUse)
965 {
966 // handling of referenced resource
967 if ( node.GetName() == wxT("object_ref") )
968 {
969 wxString refName = node.GetAttribute(wxT("ref"), wxEmptyString);
970 wxXmlNode* refNode = FindResource(refName, wxEmptyString, true);
971
972 if ( !refNode )
973 {
974 ReportError
975 (
976 &node,
977 wxString::Format
978 (
979 "referenced object node with ref=\"%s\" not found",
980 refName
981 )
982 );
983 return NULL;
984 }
985
986 const bool hasOnlyRefAttr = node.GetAttributes() != NULL &&
987 node.GetAttributes()->GetNext() == NULL;
988
989 if ( hasOnlyRefAttr && !node.GetChildren() )
990 {
991 // In the typical, simple case, <object_ref> is used to link
992 // to another node and doesn't have any content of its own that
993 // would overwrite linked object's properties. In this case,
994 // we can simply create the resource from linked node.
995
996 return DoCreateResFromNode(*refNode, parent, instance);
997 }
998 else
999 {
1000 // In the more complicated (but rare) case, <object_ref> has
1001 // subnodes that partially overwrite content of the referenced
1002 // object. In this case, we need to merge both XML trees and
1003 // load the resource from result of the merge.
1004
1005 wxXmlNode copy(*refNode);
1006 MergeNodesOver(copy, node, GetFileNameFromNode(&node, Data()));
1007
1008 // remember referenced object's file, see GetFileNameFromNode()
1009 copy.AddAttribute(ATTR_INPUT_FILENAME,
1010 GetFileNameFromNode(refNode, Data()));
1011
1012 return DoCreateResFromNode(copy, parent, instance);
1013 }
1014 }
1015
1016 if (handlerToUse)
1017 {
1018 if (handlerToUse->CanHandle(&node))
1019 {
1020 return handlerToUse->CreateResource(&node, parent, instance);
1021 }
1022 }
1023 else if (node.GetName() == wxT("object"))
1024 {
1025 for ( wxVector<wxXmlResourceHandler*>::iterator h = m_handlers.begin();
1026 h != m_handlers.end(); ++h )
1027 {
1028 wxXmlResourceHandler *handler = *h;
1029 if (handler->CanHandle(&node))
1030 return handler->CreateResource(&node, parent, instance);
1031 }
1032 }
1033
1034 ReportError
1035 (
1036 &node,
1037 wxString::Format
1038 (
1039 "no handler found for XML node \"%s\" (class \"%s\")",
1040 node.GetName(),
1041 node.GetAttribute("class", wxEmptyString)
1042 )
1043 );
1044 return NULL;
1045 }
1046
1047 wxIdRange::wxIdRange(const wxXmlNode* node,
1048 const wxString& rname,
1049 const wxString& startno,
1050 const wxString& rsize)
1051 : m_name(rname),
1052 m_start(0),
1053 m_size(0),
1054 m_item_end_found(0),
1055 m_finalised(0)
1056 {
1057 long l;
1058 if ( startno.ToLong(&l) )
1059 {
1060 if ( l >= 0 )
1061 {
1062 m_start = l;
1063 }
1064 else
1065 {
1066 wxXmlResource::Get()->ReportError
1067 (
1068 node,
1069 "a negative id-range start parameter was given"
1070 );
1071 }
1072 }
1073 else
1074 {
1075 wxXmlResource::Get()->ReportError
1076 (
1077 node,
1078 "the id-range start parameter was malformed"
1079 );
1080 }
1081
1082 unsigned long ul;
1083 if ( rsize.ToULong(&ul) )
1084 {
1085 m_size = ul;
1086 }
1087 else
1088 {
1089 wxXmlResource::Get()->ReportError
1090 (
1091 node,
1092 "the id-range size parameter was malformed"
1093 );
1094 }
1095 }
1096
1097 void wxIdRange::NoteItem(const wxXmlNode* node, const wxString& item)
1098 {
1099 // Nothing gets added here, but the existence of each item is noted
1100 // thus getting an accurate count. 'item' will be either an integer e.g.
1101 // [0] [123]: will eventually create an XRCID as start+integer or [start]
1102 // or [end] which are synonyms for [0] or [range_size-1] respectively.
1103 wxString content(item.Mid(1, item.length()-2));
1104
1105 // Check that basename+item wasn't foo[]
1106 if (content.empty())
1107 {
1108 wxXmlResource::Get()->ReportError(node, "an empty id-range item found");
1109 return;
1110 }
1111
1112 if (content=="start")
1113 {
1114 // "start" means [0], so store that in the set
1115 if (m_indices.count(0) == 0)
1116 {
1117 m_indices.insert(0);
1118 }
1119 else
1120 {
1121 wxXmlResource::Get()->ReportError
1122 (
1123 node,
1124 "duplicate id-range item found"
1125 );
1126 }
1127 }
1128 else if (content=="end")
1129 {
1130 // We can't yet be certain which XRCID this will be equivalent to, so
1131 // just note that there's an item with this name, in case we need to
1132 // inc the range size
1133 m_item_end_found = true;
1134 }
1135 else
1136 {
1137 // Anything else will be an integer, or rubbish
1138 unsigned long l;
1139 if ( content.ToULong(&l) )
1140 {
1141 if (m_indices.count(l) == 0)
1142 {
1143 m_indices.insert(l);
1144 // Check that this item wouldn't fall outside the current range
1145 // extent
1146 if (l >= m_size)
1147 {
1148 m_size = l + 1;
1149 }
1150 }
1151 else
1152 {
1153 wxXmlResource::Get()->ReportError
1154 (
1155 node,
1156 "duplicate id-range item found"
1157 );
1158 }
1159
1160 }
1161 else
1162 {
1163 wxXmlResource::Get()->ReportError
1164 (
1165 node,
1166 "an id-range item had a malformed index"
1167 );
1168 }
1169 }
1170 }
1171
1172 void wxIdRange::Finalise(const wxXmlNode* node)
1173 {
1174 wxCHECK_RET( !IsFinalised(),
1175 "Trying to finalise an already-finalised range" );
1176
1177 // Now we know about all the items, we can get an accurate range size
1178 // Expand any requested range-size if there were more items than would fit
1179 m_size = wxMax(m_size, m_indices.size());
1180
1181 // If an item is explicitly called foo[end], ensure it won't clash with
1182 // another item
1183 if ( m_item_end_found && m_indices.count(m_size-1) )
1184 ++m_size;
1185 if (m_size == 0)
1186 {
1187 // This will happen if someone creates a range but no items in this xrc
1188 // file Report the error and abort, but don't finalise, in case items
1189 // appear later
1190 wxXmlResource::Get()->ReportError
1191 (
1192 node,
1193 "trying to create an empty id-range"
1194 );
1195 return;
1196 }
1197
1198 if (m_start==0)
1199 {
1200 // This is the usual case, where the user didn't specify a start ID
1201 // So get the range using NewControlId().
1202 //
1203 // NB: negative numbers, but NewControlId already returns the most
1204 // negative
1205 m_start = wxWindow::NewControlId(m_size);
1206 wxCHECK_RET( m_start != wxID_NONE,
1207 "insufficient IDs available to create range" );
1208 m_end = m_start + m_size - 1;
1209 }
1210 else
1211 {
1212 // The user already specified a start value, which must be positive
1213 m_end = m_start + m_size - 1;
1214 }
1215
1216 // Create the XRCIDs
1217 for (int i=m_start; i <= m_end; ++i)
1218 {
1219 // First clear any pre-existing XRCID
1220 // Necessary for wxXmlResource::Unload() followed by Load()
1221 wxIdRangeManager::RemoveXRCIDEntry(
1222 m_name + wxString::Format("[%i]", i-m_start));
1223
1224 // Use the second parameter of GetXRCID to force it to take the value i
1225 wxXmlResource::GetXRCID(m_name + wxString::Format("[%i]", i-m_start), i);
1226 wxLogTrace("xrcrange",
1227 "integer = %i %s now returns %i",
1228 i,
1229 m_name + wxString::Format("[%i]", i-m_start),
1230 XRCID((m_name + wxString::Format("[%i]", i-m_start)).mb_str()));
1231 }
1232 // and these special ones
1233 wxIdRangeManager::RemoveXRCIDEntry(m_name + "[start]");
1234 wxXmlResource::GetXRCID(m_name + "[start]", m_start);
1235 wxIdRangeManager::RemoveXRCIDEntry(m_name + "[end]");
1236 wxXmlResource::GetXRCID(m_name + "[end]", m_end);
1237 wxLogTrace("xrcrange","%s[start] = %i %s[end] = %i",
1238 m_name.mb_str(),XRCID(wxString(m_name+"[start]").mb_str()),
1239 m_name.mb_str(),XRCID(wxString(m_name+"[end]").mb_str()));
1240
1241 m_finalised = true;
1242 }
1243
1244 wxIdRangeManager *wxIdRangeManager::ms_instance = NULL;
1245
1246 /*static*/ wxIdRangeManager *wxIdRangeManager::Get()
1247 {
1248 if ( !ms_instance )
1249 ms_instance = new wxIdRangeManager;
1250 return ms_instance;
1251 }
1252
1253 /*static*/ wxIdRangeManager *wxIdRangeManager::Set(wxIdRangeManager *res)
1254 {
1255 wxIdRangeManager *old = ms_instance;
1256 ms_instance = res;
1257 return old;
1258 }
1259
1260 wxIdRangeManager::~wxIdRangeManager()
1261 {
1262 for ( wxVector<wxIdRange*>::iterator i = m_IdRanges.begin();
1263 i != m_IdRanges.end(); ++i )
1264 {
1265 delete *i;
1266 }
1267 m_IdRanges.clear();
1268
1269 delete ms_instance;
1270 }
1271
1272 void wxIdRangeManager::AddRange(const wxXmlNode* node)
1273 {
1274 wxString name = node->GetAttribute("name");
1275 wxString start = node->GetAttribute("start", "0");
1276 wxString size = node->GetAttribute("size", "0");
1277 if (name.empty())
1278 {
1279 wxXmlResource::Get()->ReportError
1280 (
1281 node,
1282 "xrc file contains an id-range without a name"
1283 );
1284 return;
1285 }
1286
1287 int index = Find(name);
1288 if (index == wxNOT_FOUND)
1289 {
1290 wxLogTrace("xrcrange",
1291 "Adding ID range, name=%s start=%s size=%s",
1292 name, start, size);
1293
1294 m_IdRanges.push_back(new wxIdRange(node, name, start, size));
1295 }
1296 else
1297 {
1298 // There was already a range with this name. Let's hope this is
1299 // from an Unload()/(re)Load(), not an unintentional duplication
1300 wxLogTrace("xrcrange",
1301 "Replacing ID range, name=%s start=%s size=%s",
1302 name, start, size);
1303
1304 wxIdRange* oldrange = m_IdRanges.at(index);
1305 m_IdRanges.at(index) = new wxIdRange(node, name, start, size);
1306 delete oldrange;
1307 }
1308 }
1309
1310 wxIdRange *
1311 wxIdRangeManager::FindRangeForItem(const wxXmlNode* node,
1312 const wxString& item,
1313 wxString& value) const
1314 {
1315 wxString basename = item.BeforeFirst('[');
1316 wxCHECK_MSG( !basename.empty(), NULL,
1317 "an id-range item without a range name" );
1318
1319 int index = Find(basename);
1320 if (index == wxNOT_FOUND)
1321 {
1322 // Don't assert just because we've found an unexpected foo[123]
1323 // Someone might just want such a name, nothing to do with ranges
1324 return NULL;
1325 }
1326
1327 value = item.Mid(basename.Len());
1328 if (value.at(value.length()-1)==']')
1329 {
1330 return m_IdRanges.at(index);
1331 }
1332 wxXmlResource::Get()->ReportError(node, "a malformed id-range item");
1333 return NULL;
1334 }
1335
1336 void
1337 wxIdRangeManager::NotifyRangeOfItem(const wxXmlNode* node,
1338 const wxString& item) const
1339 {
1340 wxString value;
1341 wxIdRange* range = FindRangeForItem(node, item, value);
1342 if (range)
1343 range->NoteItem(node, value);
1344 }
1345
1346 int wxIdRangeManager::Find(const wxString& rangename) const
1347 {
1348 for ( int i=0; i < (int)m_IdRanges.size(); ++i )
1349 {
1350 if (m_IdRanges.at(i)->GetName() == rangename)
1351 return i;
1352 }
1353
1354 return wxNOT_FOUND;
1355 }
1356
1357 void wxIdRangeManager::FinaliseRanges(const wxXmlNode* node) const
1358 {
1359 for ( wxVector<wxIdRange*>::const_iterator i = m_IdRanges.begin();
1360 i != m_IdRanges.end(); ++i )
1361 {
1362 // Check if this range has already been finalised. Quite possible,
1363 // as FinaliseRanges() gets called for each .xrc file loaded
1364 if (!(*i)->IsFinalised())
1365 {
1366 wxLogTrace("xrcrange", "Finalising ID range %s", (*i)->GetName());
1367 (*i)->Finalise(node);
1368 }
1369 }
1370 }
1371
1372
1373 class wxXmlSubclassFactories : public wxVector<wxXmlSubclassFactory*>
1374 {
1375 // this is a class so that it can be forward-declared
1376 };
1377
1378 wxXmlSubclassFactories *wxXmlResource::ms_subclassFactories = NULL;
1379
1380 /*static*/ void wxXmlResource::AddSubclassFactory(wxXmlSubclassFactory *factory)
1381 {
1382 if (!ms_subclassFactories)
1383 {
1384 ms_subclassFactories = new wxXmlSubclassFactories;
1385 }
1386 ms_subclassFactories->push_back(factory);
1387 }
1388
1389 class wxXmlSubclassFactoryCXX : public wxXmlSubclassFactory
1390 {
1391 public:
1392 ~wxXmlSubclassFactoryCXX() {}
1393
1394 wxObject *Create(const wxString& className)
1395 {
1396 wxClassInfo* classInfo = wxClassInfo::FindClass(className);
1397
1398 if (classInfo)
1399 return classInfo->CreateObject();
1400 else
1401 return NULL;
1402 }
1403 };
1404
1405
1406
1407
1408 wxXmlResourceHandler::wxXmlResourceHandler()
1409 : m_node(NULL), m_parent(NULL), m_instance(NULL),
1410 m_parentAsWindow(NULL)
1411 {}
1412
1413
1414
1415 wxObject *wxXmlResourceHandler::CreateResource(wxXmlNode *node, wxObject *parent, wxObject *instance)
1416 {
1417 wxXmlNode *myNode = m_node;
1418 wxString myClass = m_class;
1419 wxObject *myParent = m_parent, *myInstance = m_instance;
1420 wxWindow *myParentAW = m_parentAsWindow;
1421
1422 m_instance = instance;
1423 if (!m_instance && node->HasAttribute(wxT("subclass")) &&
1424 !(m_resource->GetFlags() & wxXRC_NO_SUBCLASSING))
1425 {
1426 wxString subclass = node->GetAttribute(wxT("subclass"), wxEmptyString);
1427 if (!subclass.empty())
1428 {
1429 for (wxXmlSubclassFactories::iterator i = wxXmlResource::ms_subclassFactories->begin();
1430 i != wxXmlResource::ms_subclassFactories->end(); ++i)
1431 {
1432 m_instance = (*i)->Create(subclass);
1433 if (m_instance)
1434 break;
1435 }
1436
1437 if (!m_instance)
1438 {
1439 wxString name = node->GetAttribute(wxT("name"), wxEmptyString);
1440 ReportError
1441 (
1442 node,
1443 wxString::Format
1444 (
1445 "subclass \"%s\" not found for resource \"%s\", not subclassing",
1446 subclass, name
1447 )
1448 );
1449 }
1450 }
1451 }
1452
1453 m_node = node;
1454 m_class = node->GetAttribute(wxT("class"), wxEmptyString);
1455 m_parent = parent;
1456 m_parentAsWindow = wxDynamicCast(m_parent, wxWindow);
1457
1458 wxObject *returned = DoCreateResource();
1459
1460 m_node = myNode;
1461 m_class = myClass;
1462 m_parent = myParent; m_parentAsWindow = myParentAW;
1463 m_instance = myInstance;
1464
1465 return returned;
1466 }
1467
1468
1469 void wxXmlResourceHandler::AddStyle(const wxString& name, int value)
1470 {
1471 m_styleNames.Add(name);
1472 m_styleValues.Add(value);
1473 }
1474
1475
1476
1477 void wxXmlResourceHandler::AddWindowStyles()
1478 {
1479 XRC_ADD_STYLE(wxCLIP_CHILDREN);
1480
1481 // the border styles all have the old and new names, recognize both for now
1482 XRC_ADD_STYLE(wxSIMPLE_BORDER); XRC_ADD_STYLE(wxBORDER_SIMPLE);
1483 XRC_ADD_STYLE(wxSUNKEN_BORDER); XRC_ADD_STYLE(wxBORDER_SUNKEN);
1484 XRC_ADD_STYLE(wxDOUBLE_BORDER); XRC_ADD_STYLE(wxBORDER_DOUBLE); // deprecated
1485 XRC_ADD_STYLE(wxBORDER_THEME);
1486 XRC_ADD_STYLE(wxRAISED_BORDER); XRC_ADD_STYLE(wxBORDER_RAISED);
1487 XRC_ADD_STYLE(wxSTATIC_BORDER); XRC_ADD_STYLE(wxBORDER_STATIC);
1488 XRC_ADD_STYLE(wxNO_BORDER); XRC_ADD_STYLE(wxBORDER_NONE);
1489
1490 XRC_ADD_STYLE(wxTRANSPARENT_WINDOW);
1491 XRC_ADD_STYLE(wxWANTS_CHARS);
1492 XRC_ADD_STYLE(wxTAB_TRAVERSAL);
1493 XRC_ADD_STYLE(wxNO_FULL_REPAINT_ON_RESIZE);
1494 XRC_ADD_STYLE(wxFULL_REPAINT_ON_RESIZE);
1495 XRC_ADD_STYLE(wxALWAYS_SHOW_SB);
1496 XRC_ADD_STYLE(wxWS_EX_BLOCK_EVENTS);
1497 XRC_ADD_STYLE(wxWS_EX_VALIDATE_RECURSIVELY);
1498 }
1499
1500
1501
1502 bool wxXmlResourceHandler::HasParam(const wxString& param)
1503 {
1504 return (GetParamNode(param) != NULL);
1505 }
1506
1507
1508 int wxXmlResourceHandler::GetStyle(const wxString& param, int defaults)
1509 {
1510 wxString s = GetParamValue(param);
1511
1512 if (!s) return defaults;
1513
1514 wxStringTokenizer tkn(s, wxT("| \t\n"), wxTOKEN_STRTOK);
1515 int style = 0;
1516 int index;
1517 wxString fl;
1518 while (tkn.HasMoreTokens())
1519 {
1520 fl = tkn.GetNextToken();
1521 index = m_styleNames.Index(fl);
1522 if (index != wxNOT_FOUND)
1523 {
1524 style |= m_styleValues[index];
1525 }
1526 else
1527 {
1528 ReportParamError
1529 (
1530 param,
1531 wxString::Format("unknown style flag \"%s\"", fl)
1532 );
1533 }
1534 }
1535 return style;
1536 }
1537
1538
1539
1540 wxString wxXmlResourceHandler::GetText(const wxString& param, bool translate)
1541 {
1542 wxXmlNode *parNode = GetParamNode(param);
1543 wxString str1(GetNodeContent(parNode));
1544 wxString str2;
1545
1546 // "\\" wasn't translated to "\" prior to 2.5.3.0:
1547 const bool escapeBackslash = (m_resource->CompareVersion(2,5,3,0) >= 0);
1548
1549 // VS: First version of XRC resources used $ instead of & (which is
1550 // illegal in XML), but later I realized that '_' fits this purpose
1551 // much better (because &File means "File with F underlined").
1552 const wxChar amp_char = (m_resource->CompareVersion(2,3,0,1) < 0)
1553 ? '$' : '_';
1554
1555 for ( wxString::const_iterator dt = str1.begin(); dt != str1.end(); ++dt )
1556 {
1557 // Remap amp_char to &, map double amp_char to amp_char (for things
1558 // like "&File..." -- this is illegal in XML, so we use "_File..."):
1559 if ( *dt == amp_char )
1560 {
1561 if ( *(++dt) == amp_char )
1562 str2 << amp_char;
1563 else
1564 str2 << wxT('&') << *dt;
1565 }
1566 // Remap \n to CR, \r to LF, \t to TAB, \\ to \:
1567 else if ( *dt == wxT('\\') )
1568 {
1569 switch ( (*(++dt)).GetValue() )
1570 {
1571 case wxT('n'):
1572 str2 << wxT('\n');
1573 break;
1574
1575 case wxT('t'):
1576 str2 << wxT('\t');
1577 break;
1578
1579 case wxT('r'):
1580 str2 << wxT('\r');
1581 break;
1582
1583 case wxT('\\') :
1584 // "\\" wasn't translated to "\" prior to 2.5.3.0:
1585 if ( escapeBackslash )
1586 {
1587 str2 << wxT('\\');
1588 break;
1589 }
1590 // else fall-through to default: branch below
1591
1592 default:
1593 str2 << wxT('\\') << *dt;
1594 break;
1595 }
1596 }
1597 else
1598 {
1599 str2 << *dt;
1600 }
1601 }
1602
1603 if (m_resource->GetFlags() & wxXRC_USE_LOCALE)
1604 {
1605 if (translate && parNode &&
1606 parNode->GetAttribute(wxT("translate"), wxEmptyString) != wxT("0"))
1607 {
1608 return wxGetTranslation(str2, m_resource->GetDomain());
1609 }
1610 else
1611 {
1612 #if wxUSE_UNICODE
1613 return str2;
1614 #else
1615 // The string is internally stored as UTF-8, we have to convert
1616 // it into system's default encoding so that it can be displayed:
1617 return wxString(str2.wc_str(wxConvUTF8), wxConvLocal);
1618 #endif
1619 }
1620 }
1621
1622 // If wxXRC_USE_LOCALE is not set, then the string is already in
1623 // system's default encoding in ANSI build, so we don't have to
1624 // do anything special here.
1625 return str2;
1626 }
1627
1628
1629
1630 long wxXmlResourceHandler::GetLong(const wxString& param, long defaultv)
1631 {
1632 long value;
1633 wxString str1 = GetParamValue(param);
1634
1635 if (!str1.ToLong(&value))
1636 value = defaultv;
1637
1638 return value;
1639 }
1640
1641 float wxXmlResourceHandler::GetFloat(const wxString& param, float defaultv)
1642 {
1643 wxString str = GetParamValue(param);
1644
1645 // strings in XRC always use C locale so make sure to use the
1646 // locale-independent wxString::ToCDouble() and not ToDouble() which uses
1647 // the current locale with a potentially different decimal point character
1648 double value;
1649 if (!str.ToCDouble(&value))
1650 value = defaultv;
1651
1652 return wx_truncate_cast(float, value);
1653 }
1654
1655
1656 int wxXmlResourceHandler::GetID()
1657 {
1658 return wxXmlResource::GetXRCID(GetName());
1659 }
1660
1661
1662
1663 wxString wxXmlResourceHandler::GetName()
1664 {
1665 return m_node->GetAttribute(wxT("name"), wxT("-1"));
1666 }
1667
1668
1669
1670 bool wxXmlResourceHandler::GetBoolAttr(const wxString& attr, bool defaultv)
1671 {
1672 wxString v;
1673 return m_node->GetAttribute(attr, &v) ? v == '1' : defaultv;
1674 }
1675
1676 bool wxXmlResourceHandler::GetBool(const wxString& param, bool defaultv)
1677 {
1678 const wxString v = GetParamValue(param);
1679
1680 return v.empty() ? defaultv : (v == '1');
1681 }
1682
1683
1684 static wxColour GetSystemColour(const wxString& name)
1685 {
1686 if (!name.empty())
1687 {
1688 #define SYSCLR(clr) \
1689 if (name == wxT(#clr)) return wxSystemSettings::GetColour(clr);
1690 SYSCLR(wxSYS_COLOUR_SCROLLBAR)
1691 SYSCLR(wxSYS_COLOUR_BACKGROUND)
1692 SYSCLR(wxSYS_COLOUR_DESKTOP)
1693 SYSCLR(wxSYS_COLOUR_ACTIVECAPTION)
1694 SYSCLR(wxSYS_COLOUR_INACTIVECAPTION)
1695 SYSCLR(wxSYS_COLOUR_MENU)
1696 SYSCLR(wxSYS_COLOUR_WINDOW)
1697 SYSCLR(wxSYS_COLOUR_WINDOWFRAME)
1698 SYSCLR(wxSYS_COLOUR_MENUTEXT)
1699 SYSCLR(wxSYS_COLOUR_WINDOWTEXT)
1700 SYSCLR(wxSYS_COLOUR_CAPTIONTEXT)
1701 SYSCLR(wxSYS_COLOUR_ACTIVEBORDER)
1702 SYSCLR(wxSYS_COLOUR_INACTIVEBORDER)
1703 SYSCLR(wxSYS_COLOUR_APPWORKSPACE)
1704 SYSCLR(wxSYS_COLOUR_HIGHLIGHT)
1705 SYSCLR(wxSYS_COLOUR_HIGHLIGHTTEXT)
1706 SYSCLR(wxSYS_COLOUR_BTNFACE)
1707 SYSCLR(wxSYS_COLOUR_3DFACE)
1708 SYSCLR(wxSYS_COLOUR_BTNSHADOW)
1709 SYSCLR(wxSYS_COLOUR_3DSHADOW)
1710 SYSCLR(wxSYS_COLOUR_GRAYTEXT)
1711 SYSCLR(wxSYS_COLOUR_BTNTEXT)
1712 SYSCLR(wxSYS_COLOUR_INACTIVECAPTIONTEXT)
1713 SYSCLR(wxSYS_COLOUR_BTNHIGHLIGHT)
1714 SYSCLR(wxSYS_COLOUR_BTNHILIGHT)
1715 SYSCLR(wxSYS_COLOUR_3DHIGHLIGHT)
1716 SYSCLR(wxSYS_COLOUR_3DHILIGHT)
1717 SYSCLR(wxSYS_COLOUR_3DDKSHADOW)
1718 SYSCLR(wxSYS_COLOUR_3DLIGHT)
1719 SYSCLR(wxSYS_COLOUR_INFOTEXT)
1720 SYSCLR(wxSYS_COLOUR_INFOBK)
1721 SYSCLR(wxSYS_COLOUR_LISTBOX)
1722 SYSCLR(wxSYS_COLOUR_HOTLIGHT)
1723 SYSCLR(wxSYS_COLOUR_GRADIENTACTIVECAPTION)
1724 SYSCLR(wxSYS_COLOUR_GRADIENTINACTIVECAPTION)
1725 SYSCLR(wxSYS_COLOUR_MENUHILIGHT)
1726 SYSCLR(wxSYS_COLOUR_MENUBAR)
1727 #undef SYSCLR
1728 }
1729
1730 return wxNullColour;
1731 }
1732
1733 wxColour wxXmlResourceHandler::GetColour(const wxString& param, const wxColour& defaultv)
1734 {
1735 wxString v = GetParamValue(param);
1736
1737 if ( v.empty() )
1738 return defaultv;
1739
1740 wxColour clr;
1741
1742 // wxString -> wxColour conversion
1743 if (!clr.Set(v))
1744 {
1745 // the colour doesn't use #RRGGBB format, check if it is symbolic
1746 // colour name:
1747 clr = GetSystemColour(v);
1748 if (clr.IsOk())
1749 return clr;
1750
1751 ReportParamError
1752 (
1753 param,
1754 wxString::Format("incorrect colour specification \"%s\"", v)
1755 );
1756 return wxNullColour;
1757 }
1758
1759 return clr;
1760 }
1761
1762 namespace
1763 {
1764
1765 // if 'param' has stock_id/stock_client, extracts them and returns true
1766 bool GetStockArtAttrs(const wxXmlNode *paramNode,
1767 const wxString& defaultArtClient,
1768 wxString& art_id, wxString& art_client)
1769 {
1770 if ( paramNode )
1771 {
1772 art_id = paramNode->GetAttribute("stock_id", "");
1773
1774 if ( !art_id.empty() )
1775 {
1776 art_id = wxART_MAKE_ART_ID_FROM_STR(art_id);
1777
1778 art_client = paramNode->GetAttribute("stock_client", "");
1779 if ( art_client.empty() )
1780 art_client = defaultArtClient;
1781 else
1782 art_client = wxART_MAKE_CLIENT_ID_FROM_STR(art_client);
1783
1784 return true;
1785 }
1786 }
1787
1788 return false;
1789 }
1790
1791 } // anonymous namespace
1792
1793 wxBitmap wxXmlResourceHandler::GetBitmap(const wxString& param,
1794 const wxArtClient& defaultArtClient,
1795 wxSize size)
1796 {
1797 // it used to be possible to pass an empty string here to indicate that the
1798 // bitmap name should be read from this node itself but this is not
1799 // supported any more because GetBitmap(m_node) can be used directly
1800 // instead
1801 wxASSERT_MSG( !param.empty(), "bitmap parameter name can't be empty" );
1802
1803 const wxXmlNode* const node = GetParamNode(param);
1804
1805 if ( !node )
1806 {
1807 // this is not an error as bitmap parameter could be optional
1808 return wxNullBitmap;
1809 }
1810
1811 return GetBitmap(node, defaultArtClient, size);
1812 }
1813
1814 wxBitmap wxXmlResourceHandler::GetBitmap(const wxXmlNode* node,
1815 const wxArtClient& defaultArtClient,
1816 wxSize size)
1817 {
1818 wxCHECK_MSG( node, wxNullBitmap, "bitmap node can't be NULL" );
1819
1820 /* If the bitmap is specified as stock item, query wxArtProvider for it: */
1821 wxString art_id, art_client;
1822 if ( GetStockArtAttrs(node, defaultArtClient,
1823 art_id, art_client) )
1824 {
1825 wxBitmap stockArt(wxArtProvider::GetBitmap(art_id, art_client, size));
1826 if ( stockArt.IsOk() )
1827 return stockArt;
1828 }
1829
1830 /* ...or load the bitmap from file: */
1831 wxString name = GetParamValue(node);
1832 if (name.empty()) return wxNullBitmap;
1833 #if wxUSE_FILESYSTEM
1834 wxFSFile *fsfile = GetCurFileSystem().OpenFile(name, wxFS_READ | wxFS_SEEKABLE);
1835 if (fsfile == NULL)
1836 {
1837 ReportParamError
1838 (
1839 node->GetName(),
1840 wxString::Format("cannot open bitmap resource \"%s\"", name)
1841 );
1842 return wxNullBitmap;
1843 }
1844 wxImage img(*(fsfile->GetStream()));
1845 delete fsfile;
1846 #else
1847 wxImage img(name);
1848 #endif
1849
1850 if (!img.IsOk())
1851 {
1852 ReportParamError
1853 (
1854 node->GetName(),
1855 wxString::Format("cannot create bitmap from \"%s\"", name)
1856 );
1857 return wxNullBitmap;
1858 }
1859 if (!(size == wxDefaultSize)) img.Rescale(size.x, size.y);
1860 return wxBitmap(img);
1861 }
1862
1863
1864 wxIcon wxXmlResourceHandler::GetIcon(const wxString& param,
1865 const wxArtClient& defaultArtClient,
1866 wxSize size)
1867 {
1868 // see comment in GetBitmap(wxString) overload
1869 wxASSERT_MSG( !param.empty(), "icon parameter name can't be empty" );
1870
1871 const wxXmlNode* const node = GetParamNode(param);
1872
1873 if ( !node )
1874 {
1875 // this is not an error as icon parameter could be optional
1876 return wxIcon();
1877 }
1878
1879 return GetIcon(node, defaultArtClient, size);
1880 }
1881
1882 wxIcon wxXmlResourceHandler::GetIcon(const wxXmlNode* node,
1883 const wxArtClient& defaultArtClient,
1884 wxSize size)
1885 {
1886 wxIcon icon;
1887 icon.CopyFromBitmap(GetBitmap(node, defaultArtClient, size));
1888 return icon;
1889 }
1890
1891
1892 wxIconBundle wxXmlResourceHandler::GetIconBundle(const wxString& param,
1893 const wxArtClient& defaultArtClient)
1894 {
1895 wxString art_id, art_client;
1896 if ( GetStockArtAttrs(GetParamNode(param), defaultArtClient,
1897 art_id, art_client) )
1898 {
1899 wxIconBundle stockArt(wxArtProvider::GetIconBundle(art_id, art_client));
1900 if ( stockArt.IsOk() )
1901 return stockArt;
1902 }
1903
1904 const wxString name = GetParamValue(param);
1905 if ( name.empty() )
1906 return wxNullIconBundle;
1907
1908 #if wxUSE_FILESYSTEM
1909 wxFSFile *fsfile = GetCurFileSystem().OpenFile(name, wxFS_READ | wxFS_SEEKABLE);
1910 if ( fsfile == NULL )
1911 {
1912 ReportParamError
1913 (
1914 param,
1915 wxString::Format("cannot open icon resource \"%s\"", name)
1916 );
1917 return wxNullIconBundle;
1918 }
1919
1920 wxIconBundle bundle(*(fsfile->GetStream()));
1921 delete fsfile;
1922 #else
1923 wxIconBundle bundle(name);
1924 #endif
1925
1926 if ( !bundle.IsOk() )
1927 {
1928 ReportParamError
1929 (
1930 param,
1931 wxString::Format("cannot create icon from \"%s\"", name)
1932 );
1933 return wxNullIconBundle;
1934 }
1935
1936 return bundle;
1937 }
1938
1939
1940 wxImageList *wxXmlResourceHandler::GetImageList(const wxString& param)
1941 {
1942 wxXmlNode * const imagelist_node = GetParamNode(param);
1943 if ( !imagelist_node )
1944 return NULL;
1945
1946 wxXmlNode * const oldnode = m_node;
1947 m_node = imagelist_node;
1948
1949 // Get the size if we have it, otherwise we will use the size of the first
1950 // list element.
1951 wxSize size = GetSize();
1952
1953 // Start adding images, we'll create the image list when adding the first
1954 // one.
1955 wxImageList * imagelist = NULL;
1956 wxString parambitmap = wxT("bitmap");
1957 if ( HasParam(parambitmap) )
1958 {
1959 wxXmlNode *n = m_node->GetChildren();
1960 while (n)
1961 {
1962 if (n->GetType() == wxXML_ELEMENT_NODE && n->GetName() == parambitmap)
1963 {
1964 wxIcon icon = GetIcon(n, wxART_OTHER, size);
1965 if ( !imagelist )
1966 {
1967 // We need the real image list size to create it.
1968 if ( size == wxDefaultSize )
1969 size = icon.GetSize();
1970
1971 // We use the mask by default.
1972 bool mask = !HasParam(wxS("mask")) || GetBool(wxS("mask"));
1973
1974 imagelist = new wxImageList(size.x, size.y, mask);
1975 }
1976
1977 // add icon instead of bitmap to keep the bitmap mask
1978 imagelist->Add(icon);
1979 }
1980 n = n->GetNext();
1981 }
1982 }
1983
1984 m_node = oldnode;
1985 return imagelist;
1986 }
1987
1988 wxXmlNode *wxXmlResourceHandler::GetParamNode(const wxString& param)
1989 {
1990 wxCHECK_MSG(m_node, NULL, wxT("You can't access handler data before it was initialized!"));
1991
1992 wxXmlNode *n = m_node->GetChildren();
1993
1994 while (n)
1995 {
1996 if (n->GetType() == wxXML_ELEMENT_NODE && n->GetName() == param)
1997 {
1998 // TODO: check that there are no other properties/parameters with
1999 // the same name and log an error if there are (can't do this
2000 // right now as I'm not sure if it's not going to break code
2001 // using this function in unintentional way (i.e. for
2002 // accessing other things than properties), for example
2003 // wxBitmapComboBoxXmlHandler almost surely does
2004 return n;
2005 }
2006 n = n->GetNext();
2007 }
2008 return NULL;
2009 }
2010
2011 /* static */
2012 bool wxXmlResourceHandler::IsOfClass(wxXmlNode *node, const wxString& classname)
2013 {
2014 return node->GetAttribute(wxT("class")) == classname;
2015 }
2016
2017
2018
2019 wxString wxXmlResourceHandler::GetNodeContent(const wxXmlNode *node)
2020 {
2021 const wxXmlNode *n = node;
2022 if (n == NULL) return wxEmptyString;
2023 n = n->GetChildren();
2024
2025 while (n)
2026 {
2027 if (n->GetType() == wxXML_TEXT_NODE ||
2028 n->GetType() == wxXML_CDATA_SECTION_NODE)
2029 return n->GetContent();
2030 n = n->GetNext();
2031 }
2032 return wxEmptyString;
2033 }
2034
2035
2036
2037 wxString wxXmlResourceHandler::GetParamValue(const wxString& param)
2038 {
2039 if (param.empty())
2040 return GetNodeContent(m_node);
2041 else
2042 return GetNodeContent(GetParamNode(param));
2043 }
2044
2045 wxString wxXmlResourceHandler::GetParamValue(const wxXmlNode* node)
2046 {
2047 return GetNodeContent(node);
2048 }
2049
2050
2051 wxSize wxXmlResourceHandler::GetSize(const wxString& param,
2052 wxWindow *windowToUse)
2053 {
2054 wxString s = GetParamValue(param);
2055 if (s.empty()) s = wxT("-1,-1");
2056 bool is_dlg;
2057 long sx, sy = 0;
2058
2059 is_dlg = s[s.length()-1] == wxT('d');
2060 if (is_dlg) s.RemoveLast();
2061
2062 if (!s.BeforeFirst(wxT(',')).ToLong(&sx) ||
2063 !s.AfterLast(wxT(',')).ToLong(&sy))
2064 {
2065 ReportParamError
2066 (
2067 param,
2068 wxString::Format("cannot parse coordinates value \"%s\"", s)
2069 );
2070 return wxDefaultSize;
2071 }
2072
2073 if (is_dlg)
2074 {
2075 if (windowToUse)
2076 {
2077 return wxDLG_UNIT(windowToUse, wxSize(sx, sy));
2078 }
2079 else if (m_parentAsWindow)
2080 {
2081 return wxDLG_UNIT(m_parentAsWindow, wxSize(sx, sy));
2082 }
2083 else
2084 {
2085 ReportParamError
2086 (
2087 param,
2088 "cannot convert dialog units: dialog unknown"
2089 );
2090 return wxDefaultSize;
2091 }
2092 }
2093
2094 return wxSize(sx, sy);
2095 }
2096
2097
2098
2099 wxPoint wxXmlResourceHandler::GetPosition(const wxString& param)
2100 {
2101 wxSize sz = GetSize(param);
2102 return wxPoint(sz.x, sz.y);
2103 }
2104
2105
2106
2107 wxCoord wxXmlResourceHandler::GetDimension(const wxString& param,
2108 wxCoord defaultv,
2109 wxWindow *windowToUse)
2110 {
2111 wxString s = GetParamValue(param);
2112 if (s.empty()) return defaultv;
2113 bool is_dlg;
2114 long sx;
2115
2116 is_dlg = s[s.length()-1] == wxT('d');
2117 if (is_dlg) s.RemoveLast();
2118
2119 if (!s.ToLong(&sx))
2120 {
2121 ReportParamError
2122 (
2123 param,
2124 wxString::Format("cannot parse dimension value \"%s\"", s)
2125 );
2126 return defaultv;
2127 }
2128
2129 if (is_dlg)
2130 {
2131 if (windowToUse)
2132 {
2133 return wxDLG_UNIT(windowToUse, wxSize(sx, 0)).x;
2134 }
2135 else if (m_parentAsWindow)
2136 {
2137 return wxDLG_UNIT(m_parentAsWindow, wxSize(sx, 0)).x;
2138 }
2139 else
2140 {
2141 ReportParamError
2142 (
2143 param,
2144 "cannot convert dialog units: dialog unknown"
2145 );
2146 return defaultv;
2147 }
2148 }
2149
2150 return sx;
2151 }
2152
2153
2154 // Get system font index using indexname
2155 static wxFont GetSystemFont(const wxString& name)
2156 {
2157 if (!name.empty())
2158 {
2159 #define SYSFNT(fnt) \
2160 if (name == wxT(#fnt)) return wxSystemSettings::GetFont(fnt);
2161 SYSFNT(wxSYS_OEM_FIXED_FONT)
2162 SYSFNT(wxSYS_ANSI_FIXED_FONT)
2163 SYSFNT(wxSYS_ANSI_VAR_FONT)
2164 SYSFNT(wxSYS_SYSTEM_FONT)
2165 SYSFNT(wxSYS_DEVICE_DEFAULT_FONT)
2166 SYSFNT(wxSYS_SYSTEM_FIXED_FONT)
2167 SYSFNT(wxSYS_DEFAULT_GUI_FONT)
2168 #undef SYSFNT
2169 }
2170
2171 return wxNullFont;
2172 }
2173
2174 wxFont wxXmlResourceHandler::GetFont(const wxString& param)
2175 {
2176 wxXmlNode *font_node = GetParamNode(param);
2177 if (font_node == NULL)
2178 {
2179 ReportError(
2180 wxString::Format("cannot find font node \"%s\"", param));
2181 return wxNullFont;
2182 }
2183
2184 wxXmlNode *oldnode = m_node;
2185 m_node = font_node;
2186
2187 // font attributes:
2188
2189 // size
2190 int isize = -1;
2191 bool hasSize = HasParam(wxT("size"));
2192 if (hasSize)
2193 isize = GetLong(wxT("size"), -1);
2194
2195 // style
2196 int istyle = wxNORMAL;
2197 bool hasStyle = HasParam(wxT("style"));
2198 if (hasStyle)
2199 {
2200 wxString style = GetParamValue(wxT("style"));
2201 if (style == wxT("italic"))
2202 istyle = wxITALIC;
2203 else if (style == wxT("slant"))
2204 istyle = wxSLANT;
2205 }
2206
2207 // weight
2208 int iweight = wxNORMAL;
2209 bool hasWeight = HasParam(wxT("weight"));
2210 if (hasWeight)
2211 {
2212 wxString weight = GetParamValue(wxT("weight"));
2213 if (weight == wxT("bold"))
2214 iweight = wxBOLD;
2215 else if (weight == wxT("light"))
2216 iweight = wxLIGHT;
2217 }
2218
2219 // underline
2220 bool hasUnderlined = HasParam(wxT("underlined"));
2221 bool underlined = hasUnderlined ? GetBool(wxT("underlined"), false) : false;
2222
2223 // family and facename
2224 int ifamily = wxDEFAULT;
2225 bool hasFamily = HasParam(wxT("family"));
2226 if (hasFamily)
2227 {
2228 wxString family = GetParamValue(wxT("family"));
2229 if (family == wxT("decorative")) ifamily = wxDECORATIVE;
2230 else if (family == wxT("roman")) ifamily = wxROMAN;
2231 else if (family == wxT("script")) ifamily = wxSCRIPT;
2232 else if (family == wxT("swiss")) ifamily = wxSWISS;
2233 else if (family == wxT("modern")) ifamily = wxMODERN;
2234 else if (family == wxT("teletype")) ifamily = wxTELETYPE;
2235 }
2236
2237
2238 wxString facename;
2239 bool hasFacename = HasParam(wxT("face"));
2240 if (hasFacename)
2241 {
2242 wxString faces = GetParamValue(wxT("face"));
2243 wxStringTokenizer tk(faces, wxT(","));
2244 #if wxUSE_FONTENUM
2245 wxArrayString facenames(wxFontEnumerator::GetFacenames());
2246 while (tk.HasMoreTokens())
2247 {
2248 int index = facenames.Index(tk.GetNextToken(), false);
2249 if (index != wxNOT_FOUND)
2250 {
2251 facename = facenames[index];
2252 break;
2253 }
2254 }
2255 #else // !wxUSE_FONTENUM
2256 // just use the first face name if we can't check its availability:
2257 if (tk.HasMoreTokens())
2258 facename = tk.GetNextToken();
2259 #endif // wxUSE_FONTENUM/!wxUSE_FONTENUM
2260 }
2261
2262 // encoding
2263 wxFontEncoding enc = wxFONTENCODING_DEFAULT;
2264 bool hasEncoding = HasParam(wxT("encoding"));
2265 #if wxUSE_FONTMAP
2266 if (hasEncoding)
2267 {
2268 wxString encoding = GetParamValue(wxT("encoding"));
2269 wxFontMapper mapper;
2270 if (!encoding.empty())
2271 enc = mapper.CharsetToEncoding(encoding);
2272 if (enc == wxFONTENCODING_SYSTEM)
2273 enc = wxFONTENCODING_DEFAULT;
2274 }
2275 #endif // wxUSE_FONTMAP
2276
2277 // is this font based on a system font?
2278 wxFont font = GetSystemFont(GetParamValue(wxT("sysfont")));
2279
2280 if (font.IsOk())
2281 {
2282 if (hasSize && isize != -1)
2283 font.SetPointSize(isize);
2284 else if (HasParam(wxT("relativesize")))
2285 font.SetPointSize(int(font.GetPointSize() *
2286 GetFloat(wxT("relativesize"))));
2287
2288 if (hasStyle)
2289 font.SetStyle(istyle);
2290 if (hasWeight)
2291 font.SetWeight(iweight);
2292 if (hasUnderlined)
2293 font.SetUnderlined(underlined);
2294 if (hasFamily)
2295 font.SetFamily(ifamily);
2296 if (hasFacename)
2297 font.SetFaceName(facename);
2298 if (hasEncoding)
2299 font.SetDefaultEncoding(enc);
2300 }
2301 else // not based on system font
2302 {
2303 font = wxFont(isize == -1 ? wxNORMAL_FONT->GetPointSize() : isize,
2304 ifamily, istyle, iweight,
2305 underlined, facename, enc);
2306 }
2307
2308 m_node = oldnode;
2309 return font;
2310 }
2311
2312
2313 void wxXmlResourceHandler::SetupWindow(wxWindow *wnd)
2314 {
2315 //FIXME : add cursor
2316
2317 if (HasParam(wxT("exstyle")))
2318 // Have to OR it with existing style, since
2319 // some implementations (e.g. wxGTK) use the extra style
2320 // during creation
2321 wnd->SetExtraStyle(wnd->GetExtraStyle() | GetStyle(wxT("exstyle")));
2322 if (HasParam(wxT("bg")))
2323 wnd->SetBackgroundColour(GetColour(wxT("bg")));
2324 if (HasParam(wxT("ownbg")))
2325 wnd->SetOwnBackgroundColour(GetColour(wxT("ownbg")));
2326 if (HasParam(wxT("fg")))
2327 wnd->SetForegroundColour(GetColour(wxT("fg")));
2328 if (HasParam(wxT("ownfg")))
2329 wnd->SetOwnForegroundColour(GetColour(wxT("ownfg")));
2330 if (GetBool(wxT("enabled"), 1) == 0)
2331 wnd->Enable(false);
2332 if (GetBool(wxT("focused"), 0) == 1)
2333 wnd->SetFocus();
2334 if (GetBool(wxT("hidden"), 0) == 1)
2335 wnd->Show(false);
2336 #if wxUSE_TOOLTIPS
2337 if (HasParam(wxT("tooltip")))
2338 wnd->SetToolTip(GetText(wxT("tooltip")));
2339 #endif
2340 if (HasParam(wxT("font")))
2341 wnd->SetFont(GetFont(wxT("font")));
2342 if (HasParam(wxT("ownfont")))
2343 wnd->SetOwnFont(GetFont(wxT("ownfont")));
2344 if (HasParam(wxT("help")))
2345 wnd->SetHelpText(GetText(wxT("help")));
2346 }
2347
2348
2349 void wxXmlResourceHandler::CreateChildren(wxObject *parent, bool this_hnd_only)
2350 {
2351 for ( wxXmlNode *n = m_node->GetChildren(); n; n = n->GetNext() )
2352 {
2353 if ( IsObjectNode(n) )
2354 {
2355 m_resource->DoCreateResFromNode(*n, parent, NULL,
2356 this_hnd_only ? this : NULL);
2357 }
2358 }
2359 }
2360
2361
2362 void wxXmlResourceHandler::CreateChildrenPrivately(wxObject *parent, wxXmlNode *rootnode)
2363 {
2364 wxXmlNode *root;
2365 if (rootnode == NULL) root = m_node; else root = rootnode;
2366 wxXmlNode *n = root->GetChildren();
2367
2368 while (n)
2369 {
2370 if (n->GetType() == wxXML_ELEMENT_NODE && CanHandle(n))
2371 {
2372 CreateResource(n, parent, NULL);
2373 }
2374 n = n->GetNext();
2375 }
2376 }
2377
2378
2379 //-----------------------------------------------------------------------------
2380 // errors reporting
2381 //-----------------------------------------------------------------------------
2382
2383 void wxXmlResourceHandler::ReportError(const wxString& message)
2384 {
2385 m_resource->ReportError(m_node, message);
2386 }
2387
2388 void wxXmlResourceHandler::ReportError(wxXmlNode *context,
2389 const wxString& message)
2390 {
2391 m_resource->ReportError(context ? context : m_node, message);
2392 }
2393
2394 void wxXmlResourceHandler::ReportParamError(const wxString& param,
2395 const wxString& message)
2396 {
2397 m_resource->ReportError(GetParamNode(param), message);
2398 }
2399
2400 void wxXmlResource::ReportError(const wxXmlNode *context, const wxString& message)
2401 {
2402 if ( !context )
2403 {
2404 DoReportError("", NULL, message);
2405 return;
2406 }
2407
2408 // We need to find out the file that 'context' is part of. Performance of
2409 // this code is not critical, so we simply find the root XML node and
2410 // compare it with all loaded XRC files.
2411 const wxString filename = GetFileNameFromNode(context, Data());
2412
2413 DoReportError(filename, context, message);
2414 }
2415
2416 void wxXmlResource::DoReportError(const wxString& xrcFile, const wxXmlNode *position,
2417 const wxString& message)
2418 {
2419 const int line = position ? position->GetLineNumber() : -1;
2420
2421 wxString loc;
2422 if ( !xrcFile.empty() )
2423 loc = xrcFile + ':';
2424 if ( line != -1 )
2425 loc += wxString::Format("%d:", line);
2426 if ( !loc.empty() )
2427 loc += ' ';
2428
2429 wxLogError("XRC error: %s%s", loc, message);
2430 }
2431
2432
2433 //-----------------------------------------------------------------------------
2434 // XRCID implementation
2435 //-----------------------------------------------------------------------------
2436
2437 #define XRCID_TABLE_SIZE 1024
2438
2439
2440 struct XRCID_record
2441 {
2442 /* Hold the id so that once an id is allocated for a name, it
2443 does not get created again by NewControlId at least
2444 until we are done with it */
2445 wxWindowIDRef id;
2446 char *key;
2447 XRCID_record *next;
2448 };
2449
2450 static XRCID_record *XRCID_Records[XRCID_TABLE_SIZE] = {NULL};
2451
2452 // Extremely simplistic hash function which probably ought to be replaced with
2453 // wxStringHash::stringHash().
2454 static inline unsigned XRCIdHash(const char *str_id)
2455 {
2456 unsigned index = 0;
2457
2458 for (const char *c = str_id; *c != '\0'; c++) index += (unsigned int)*c;
2459 index %= XRCID_TABLE_SIZE;
2460
2461 return index;
2462 }
2463
2464 static int XRCID_Lookup(const char *str_id, int value_if_not_found = wxID_NONE)
2465 {
2466 const unsigned index = XRCIdHash(str_id);
2467
2468
2469 XRCID_record *oldrec = NULL;
2470 for (XRCID_record *rec = XRCID_Records[index]; rec; rec = rec->next)
2471 {
2472 if (wxStrcmp(rec->key, str_id) == 0)
2473 {
2474 return rec->id;
2475 }
2476 oldrec = rec;
2477 }
2478
2479 XRCID_record **rec_var = (oldrec == NULL) ?
2480 &XRCID_Records[index] : &oldrec->next;
2481 *rec_var = new XRCID_record;
2482 (*rec_var)->key = wxStrdup(str_id);
2483 (*rec_var)->next = NULL;
2484
2485 char *end;
2486 if (value_if_not_found != wxID_NONE)
2487 (*rec_var)->id = value_if_not_found;
2488 else
2489 {
2490 int asint = wxStrtol(str_id, &end, 10);
2491 if (*str_id && *end == 0)
2492 {
2493 // if str_id was integer, keep it verbosely:
2494 (*rec_var)->id = asint;
2495 }
2496 else
2497 {
2498 (*rec_var)->id = wxWindowBase::NewControlId();
2499 }
2500 }
2501
2502 return (*rec_var)->id;
2503 }
2504
2505 namespace
2506 {
2507
2508 // flag indicating whether standard XRC ids were already initialized
2509 static bool gs_stdIDsAdded = false;
2510
2511 void AddStdXRCID_Records()
2512 {
2513 #define stdID(id) XRCID_Lookup(#id, id)
2514 stdID(-1);
2515
2516 stdID(wxID_ANY);
2517 stdID(wxID_SEPARATOR);
2518
2519 stdID(wxID_OPEN);
2520 stdID(wxID_CLOSE);
2521 stdID(wxID_NEW);
2522 stdID(wxID_SAVE);
2523 stdID(wxID_SAVEAS);
2524 stdID(wxID_REVERT);
2525 stdID(wxID_EXIT);
2526 stdID(wxID_UNDO);
2527 stdID(wxID_REDO);
2528 stdID(wxID_HELP);
2529 stdID(wxID_PRINT);
2530 stdID(wxID_PRINT_SETUP);
2531 stdID(wxID_PAGE_SETUP);
2532 stdID(wxID_PREVIEW);
2533 stdID(wxID_ABOUT);
2534 stdID(wxID_HELP_CONTENTS);
2535 stdID(wxID_HELP_COMMANDS);
2536 stdID(wxID_HELP_PROCEDURES);
2537 stdID(wxID_HELP_CONTEXT);
2538 stdID(wxID_CLOSE_ALL);
2539 stdID(wxID_PREFERENCES);
2540 stdID(wxID_EDIT);
2541 stdID(wxID_CUT);
2542 stdID(wxID_COPY);
2543 stdID(wxID_PASTE);
2544 stdID(wxID_CLEAR);
2545 stdID(wxID_FIND);
2546 stdID(wxID_DUPLICATE);
2547 stdID(wxID_SELECTALL);
2548 stdID(wxID_DELETE);
2549 stdID(wxID_REPLACE);
2550 stdID(wxID_REPLACE_ALL);
2551 stdID(wxID_PROPERTIES);
2552 stdID(wxID_VIEW_DETAILS);
2553 stdID(wxID_VIEW_LARGEICONS);
2554 stdID(wxID_VIEW_SMALLICONS);
2555 stdID(wxID_VIEW_LIST);
2556 stdID(wxID_VIEW_SORTDATE);
2557 stdID(wxID_VIEW_SORTNAME);
2558 stdID(wxID_VIEW_SORTSIZE);
2559 stdID(wxID_VIEW_SORTTYPE);
2560 stdID(wxID_FILE1);
2561 stdID(wxID_FILE2);
2562 stdID(wxID_FILE3);
2563 stdID(wxID_FILE4);
2564 stdID(wxID_FILE5);
2565 stdID(wxID_FILE6);
2566 stdID(wxID_FILE7);
2567 stdID(wxID_FILE8);
2568 stdID(wxID_FILE9);
2569 stdID(wxID_OK);
2570 stdID(wxID_CANCEL);
2571 stdID(wxID_APPLY);
2572 stdID(wxID_YES);
2573 stdID(wxID_NO);
2574 stdID(wxID_STATIC);
2575 stdID(wxID_FORWARD);
2576 stdID(wxID_BACKWARD);
2577 stdID(wxID_DEFAULT);
2578 stdID(wxID_MORE);
2579 stdID(wxID_SETUP);
2580 stdID(wxID_RESET);
2581 stdID(wxID_CONTEXT_HELP);
2582 stdID(wxID_YESTOALL);
2583 stdID(wxID_NOTOALL);
2584 stdID(wxID_ABORT);
2585 stdID(wxID_RETRY);
2586 stdID(wxID_IGNORE);
2587 stdID(wxID_ADD);
2588 stdID(wxID_REMOVE);
2589 stdID(wxID_UP);
2590 stdID(wxID_DOWN);
2591 stdID(wxID_HOME);
2592 stdID(wxID_REFRESH);
2593 stdID(wxID_STOP);
2594 stdID(wxID_INDEX);
2595 stdID(wxID_BOLD);
2596 stdID(wxID_ITALIC);
2597 stdID(wxID_JUSTIFY_CENTER);
2598 stdID(wxID_JUSTIFY_FILL);
2599 stdID(wxID_JUSTIFY_RIGHT);
2600 stdID(wxID_JUSTIFY_LEFT);
2601 stdID(wxID_UNDERLINE);
2602 stdID(wxID_INDENT);
2603 stdID(wxID_UNINDENT);
2604 stdID(wxID_ZOOM_100);
2605 stdID(wxID_ZOOM_FIT);
2606 stdID(wxID_ZOOM_IN);
2607 stdID(wxID_ZOOM_OUT);
2608 stdID(wxID_UNDELETE);
2609 stdID(wxID_REVERT_TO_SAVED);
2610 stdID(wxID_SYSTEM_MENU);
2611 stdID(wxID_CLOSE_FRAME);
2612 stdID(wxID_MOVE_FRAME);
2613 stdID(wxID_RESIZE_FRAME);
2614 stdID(wxID_MAXIMIZE_FRAME);
2615 stdID(wxID_ICONIZE_FRAME);
2616 stdID(wxID_RESTORE_FRAME);
2617 stdID(wxID_CDROM);
2618 stdID(wxID_CONVERT);
2619 stdID(wxID_EXECUTE);
2620 stdID(wxID_FLOPPY);
2621 stdID(wxID_HARDDISK);
2622 stdID(wxID_BOTTOM);
2623 stdID(wxID_FIRST);
2624 stdID(wxID_LAST);
2625 stdID(wxID_TOP);
2626 stdID(wxID_INFO);
2627 stdID(wxID_JUMP_TO);
2628 stdID(wxID_NETWORK);
2629 stdID(wxID_SELECT_COLOR);
2630 stdID(wxID_SELECT_FONT);
2631 stdID(wxID_SORT_ASCENDING);
2632 stdID(wxID_SORT_DESCENDING);
2633 stdID(wxID_SPELL_CHECK);
2634 stdID(wxID_STRIKETHROUGH);
2635
2636 #undef stdID
2637 }
2638
2639 } // anonymous namespace
2640
2641
2642 /*static*/
2643 int wxXmlResource::DoGetXRCID(const char *str_id, int value_if_not_found)
2644 {
2645 if ( !gs_stdIDsAdded )
2646 {
2647 gs_stdIDsAdded = true;
2648 AddStdXRCID_Records();
2649 }
2650
2651 return XRCID_Lookup(str_id, value_if_not_found);
2652 }
2653
2654 /* static */
2655 wxString wxXmlResource::FindXRCIDById(int numId)
2656 {
2657 for ( int i = 0; i < XRCID_TABLE_SIZE; i++ )
2658 {
2659 for ( XRCID_record *rec = XRCID_Records[i]; rec; rec = rec->next )
2660 {
2661 if ( rec->id == numId )
2662 return wxString(rec->key);
2663 }
2664 }
2665
2666 return wxString();
2667 }
2668
2669 /* static */
2670 void wxIdRangeManager::RemoveXRCIDEntry(const wxString& idstr)
2671 {
2672 const char *str_id = idstr.mb_str();
2673
2674 const unsigned index = XRCIdHash(str_id);
2675
2676 XRCID_record **p_previousrec = &XRCID_Records[index];
2677 for (XRCID_record *rec = XRCID_Records[index]; rec; rec = rec->next)
2678 {
2679 if (wxStrcmp(rec->key, str_id) == 0)
2680 {
2681 // Found the item to be removed so delete its record; but first
2682 // remove it from the linked list.
2683 *p_previousrec = rec->next;
2684 free(rec->key);
2685 delete rec;
2686 return;
2687 }
2688
2689 p_previousrec = &rec->next;
2690 }
2691 }
2692
2693 static void CleanXRCID_Record(XRCID_record *rec)
2694 {
2695 if (rec)
2696 {
2697 CleanXRCID_Record(rec->next);
2698
2699 free(rec->key);
2700 delete rec;
2701 }
2702 }
2703
2704 static void CleanXRCID_Records()
2705 {
2706 for (int i = 0; i < XRCID_TABLE_SIZE; i++)
2707 {
2708 CleanXRCID_Record(XRCID_Records[i]);
2709 XRCID_Records[i] = NULL;
2710 }
2711
2712 gs_stdIDsAdded = false;
2713 }
2714
2715
2716 //-----------------------------------------------------------------------------
2717 // module and globals
2718 //-----------------------------------------------------------------------------
2719
2720 // normally we would do the cleanup from wxXmlResourceModule::OnExit() but it
2721 // can happen that some XRC records have been created because of the use of
2722 // XRCID() in event tables, which happens during static objects initialization,
2723 // but then the application initialization failed and so the wx modules were
2724 // neither initialized nor cleaned up -- this static object does the cleanup in
2725 // this case
2726 static struct wxXRCStaticCleanup
2727 {
2728 ~wxXRCStaticCleanup() { CleanXRCID_Records(); }
2729 } s_staticCleanup;
2730
2731 class wxXmlResourceModule: public wxModule
2732 {
2733 DECLARE_DYNAMIC_CLASS(wxXmlResourceModule)
2734 public:
2735 wxXmlResourceModule() {}
2736 bool OnInit()
2737 {
2738 wxXmlResource::AddSubclassFactory(new wxXmlSubclassFactoryCXX);
2739 return true;
2740 }
2741 void OnExit()
2742 {
2743 delete wxXmlResource::Set(NULL);
2744 delete wxIdRangeManager::Set(NULL);
2745 if(wxXmlResource::ms_subclassFactories)
2746 {
2747 for ( wxXmlSubclassFactories::iterator i = wxXmlResource::ms_subclassFactories->begin();
2748 i != wxXmlResource::ms_subclassFactories->end(); ++i )
2749 {
2750 delete *i;
2751 }
2752 wxDELETE(wxXmlResource::ms_subclassFactories);
2753 }
2754 CleanXRCID_Records();
2755 }
2756 };
2757
2758 IMPLEMENT_DYNAMIC_CLASS(wxXmlResourceModule, wxModule)
2759
2760
2761 // When wxXml is loaded dynamically after the application is already running
2762 // then the built-in module system won't pick this one up. Add it manually.
2763 void wxXmlInitResourceModule()
2764 {
2765 wxModule* module = new wxXmlResourceModule;
2766 module->Init();
2767 wxModule::RegisterModule(module);
2768 }
2769
2770 #endif // wxUSE_XRC