]> git.saurik.com Git - wxWidgets.git/blob - src/xrc/xmlres.cpp
Deprecate second parameter of wxSlider::SetTickFreq().
[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 if ( !node.GetChildren() )
987 {
988 // In the typical, simple case, <object_ref> is used to link
989 // to another node and doesn't have any content of its own that
990 // would overwrite linked object's properties. In this case,
991 // we can simply create the resource from linked node.
992
993 return DoCreateResFromNode(*refNode, parent, instance);
994 }
995 else
996 {
997 // In the more complicated (but rare) case, <object_ref> has
998 // subnodes that partially overwrite content of the referenced
999 // object. In this case, we need to merge both XML trees and
1000 // load the resource from result of the merge.
1001
1002 wxXmlNode copy(*refNode);
1003 MergeNodesOver(copy, node, GetFileNameFromNode(&node, Data()));
1004
1005 // remember referenced object's file, see GetFileNameFromNode()
1006 copy.AddAttribute(ATTR_INPUT_FILENAME,
1007 GetFileNameFromNode(refNode, Data()));
1008
1009 return DoCreateResFromNode(copy, parent, instance);
1010 }
1011 }
1012
1013 if (handlerToUse)
1014 {
1015 if (handlerToUse->CanHandle(&node))
1016 {
1017 return handlerToUse->CreateResource(&node, parent, instance);
1018 }
1019 }
1020 else if (node.GetName() == wxT("object"))
1021 {
1022 for ( wxVector<wxXmlResourceHandler*>::iterator h = m_handlers.begin();
1023 h != m_handlers.end(); ++h )
1024 {
1025 wxXmlResourceHandler *handler = *h;
1026 if (handler->CanHandle(&node))
1027 return handler->CreateResource(&node, parent, instance);
1028 }
1029 }
1030
1031 ReportError
1032 (
1033 &node,
1034 wxString::Format
1035 (
1036 "no handler found for XML node \"%s\" (class \"%s\")",
1037 node.GetName(),
1038 node.GetAttribute("class", wxEmptyString)
1039 )
1040 );
1041 return NULL;
1042 }
1043
1044 wxIdRange::wxIdRange(const wxXmlNode* node,
1045 const wxString& rname,
1046 const wxString& startno,
1047 const wxString& rsize)
1048 : m_name(rname),
1049 m_start(0),
1050 m_size(0),
1051 m_item_end_found(0),
1052 m_finalised(0)
1053 {
1054 long l;
1055 if ( startno.ToLong(&l) )
1056 {
1057 if ( l >= 0 )
1058 {
1059 m_start = l;
1060 }
1061 else
1062 {
1063 wxXmlResource::Get()->ReportError
1064 (
1065 node,
1066 "a negative id-range start parameter was given"
1067 );
1068 }
1069 }
1070 else
1071 {
1072 wxXmlResource::Get()->ReportError
1073 (
1074 node,
1075 "the id-range start parameter was malformed"
1076 );
1077 }
1078
1079 unsigned long ul;
1080 if ( rsize.ToULong(&ul) )
1081 {
1082 m_size = ul;
1083 }
1084 else
1085 {
1086 wxXmlResource::Get()->ReportError
1087 (
1088 node,
1089 "the id-range size parameter was malformed"
1090 );
1091 }
1092 }
1093
1094 void wxIdRange::NoteItem(const wxXmlNode* node, const wxString& item)
1095 {
1096 // Nothing gets added here, but the existence of each item is noted
1097 // thus getting an accurate count. 'item' will be either an integer e.g.
1098 // [0] [123]: will eventually create an XRCID as start+integer or [start]
1099 // or [end] which are synonyms for [0] or [range_size-1] respectively.
1100 wxString content(item.Mid(1, item.length()-2));
1101
1102 // Check that basename+item wasn't foo[]
1103 if (content.empty())
1104 {
1105 wxXmlResource::Get()->ReportError(node, "an empty id-range item found");
1106 return;
1107 }
1108
1109 if (content=="start")
1110 {
1111 // "start" means [0], so store that in the set
1112 if (m_indices.count(0) == 0)
1113 {
1114 m_indices.insert(0);
1115 }
1116 else
1117 {
1118 wxXmlResource::Get()->ReportError
1119 (
1120 node,
1121 "duplicate id-range item found"
1122 );
1123 }
1124 }
1125 else if (content=="end")
1126 {
1127 // We can't yet be certain which XRCID this will be equivalent to, so
1128 // just note that there's an item with this name, in case we need to
1129 // inc the range size
1130 m_item_end_found = true;
1131 }
1132 else
1133 {
1134 // Anything else will be an integer, or rubbish
1135 unsigned long l;
1136 if ( content.ToULong(&l) )
1137 {
1138 if (m_indices.count(l) == 0)
1139 {
1140 m_indices.insert(l);
1141 // Check that this item wouldn't fall outside the current range
1142 // extent
1143 if (l >= m_size)
1144 {
1145 m_size = l + 1;
1146 }
1147 }
1148 else
1149 {
1150 wxXmlResource::Get()->ReportError
1151 (
1152 node,
1153 "duplicate id-range item found"
1154 );
1155 }
1156
1157 }
1158 else
1159 {
1160 wxXmlResource::Get()->ReportError
1161 (
1162 node,
1163 "an id-range item had a malformed index"
1164 );
1165 }
1166 }
1167 }
1168
1169 void wxIdRange::Finalise(const wxXmlNode* node)
1170 {
1171 wxCHECK_RET( !IsFinalised(),
1172 "Trying to finalise an already-finalised range" );
1173
1174 // Now we know about all the items, we can get an accurate range size
1175 // Expand any requested range-size if there were more items than would fit
1176 m_size = wxMax(m_size, m_indices.size());
1177
1178 // If an item is explicitly called foo[end], ensure it won't clash with
1179 // another item
1180 if ( m_item_end_found && m_indices.count(m_size-1) )
1181 ++m_size;
1182 if (m_size == 0)
1183 {
1184 // This will happen if someone creates a range but no items in this xrc
1185 // file Report the error and abort, but don't finalise, in case items
1186 // appear later
1187 wxXmlResource::Get()->ReportError
1188 (
1189 node,
1190 "trying to create an empty id-range"
1191 );
1192 return;
1193 }
1194
1195 if (m_start==0)
1196 {
1197 // This is the usual case, where the user didn't specify a start ID
1198 // So get the range using NewControlId().
1199 //
1200 // NB: negative numbers, but NewControlId already returns the most
1201 // negative
1202 m_start = wxWindow::NewControlId(m_size);
1203 wxCHECK_RET( m_start != wxID_NONE,
1204 "insufficient IDs available to create range" );
1205 m_end = m_start + m_size - 1;
1206 }
1207 else
1208 {
1209 // The user already specified a start value, which must be positive
1210 m_end = m_start + m_size - 1;
1211 }
1212
1213 // Create the XRCIDs
1214 for (int i=m_start; i <= m_end; ++i)
1215 {
1216 // First clear any pre-existing XRCID
1217 // Necessary for wxXmlResource::Unload() followed by Load()
1218 wxIdRangeManager::RemoveXRCIDEntry(
1219 m_name + wxString::Format("[%i]", i-m_start));
1220
1221 // Use the second parameter of GetXRCID to force it to take the value i
1222 wxXmlResource::GetXRCID(m_name + wxString::Format("[%i]", i-m_start), i);
1223 wxLogTrace("xrcrange",
1224 "integer = %i %s now returns %i",
1225 i,
1226 m_name + wxString::Format("[%i]", i-m_start),
1227 XRCID((m_name + wxString::Format("[%i]", i-m_start)).mb_str()));
1228 }
1229 // and these special ones
1230 wxIdRangeManager::RemoveXRCIDEntry(m_name + "[start]");
1231 wxXmlResource::GetXRCID(m_name + "[start]", m_start);
1232 wxIdRangeManager::RemoveXRCIDEntry(m_name + "[end]");
1233 wxXmlResource::GetXRCID(m_name + "[end]", m_end);
1234 wxLogTrace("xrcrange","%s[start] = %i %s[end] = %i",
1235 m_name.mb_str(),XRCID(wxString(m_name+"[start]").mb_str()),
1236 m_name.mb_str(),XRCID(wxString(m_name+"[end]").mb_str()));
1237
1238 m_finalised = true;
1239 }
1240
1241 wxIdRangeManager *wxIdRangeManager::ms_instance = NULL;
1242
1243 /*static*/ wxIdRangeManager *wxIdRangeManager::Get()
1244 {
1245 if ( !ms_instance )
1246 ms_instance = new wxIdRangeManager;
1247 return ms_instance;
1248 }
1249
1250 /*static*/ wxIdRangeManager *wxIdRangeManager::Set(wxIdRangeManager *res)
1251 {
1252 wxIdRangeManager *old = ms_instance;
1253 ms_instance = res;
1254 return old;
1255 }
1256
1257 wxIdRangeManager::~wxIdRangeManager()
1258 {
1259 for ( wxVector<wxIdRange*>::iterator i = m_IdRanges.begin();
1260 i != m_IdRanges.end(); ++i )
1261 {
1262 delete *i;
1263 }
1264 m_IdRanges.clear();
1265
1266 delete ms_instance;
1267 }
1268
1269 void wxIdRangeManager::AddRange(const wxXmlNode* node)
1270 {
1271 wxString name = node->GetAttribute("name");
1272 wxString start = node->GetAttribute("start", "0");
1273 wxString size = node->GetAttribute("size", "0");
1274 if (name.empty())
1275 {
1276 wxXmlResource::Get()->ReportError
1277 (
1278 node,
1279 "xrc file contains an id-range without a name"
1280 );
1281 return;
1282 }
1283
1284 int index = Find(name);
1285 if (index == wxNOT_FOUND)
1286 {
1287 wxLogTrace("xrcrange",
1288 "Adding ID range, name=%s start=%s size=%s",
1289 name, start, size);
1290
1291 m_IdRanges.push_back(new wxIdRange(node, name, start, size));
1292 }
1293 else
1294 {
1295 // There was already a range with this name. Let's hope this is
1296 // from an Unload()/(re)Load(), not an unintentional duplication
1297 wxLogTrace("xrcrange",
1298 "Replacing ID range, name=%s start=%s size=%s",
1299 name, start, size);
1300
1301 wxIdRange* oldrange = m_IdRanges.at(index);
1302 m_IdRanges.at(index) = new wxIdRange(node, name, start, size);
1303 delete oldrange;
1304 }
1305 }
1306
1307 wxIdRange *
1308 wxIdRangeManager::FindRangeForItem(const wxXmlNode* node,
1309 const wxString& item,
1310 wxString& value) const
1311 {
1312 wxString basename = item.BeforeFirst('[');
1313 wxCHECK_MSG( !basename.empty(), NULL,
1314 "an id-range item without a range name" );
1315
1316 int index = Find(basename);
1317 if (index == wxNOT_FOUND)
1318 {
1319 // Don't assert just because we've found an unexpected foo[123]
1320 // Someone might just want such a name, nothing to do with ranges
1321 return NULL;
1322 }
1323
1324 value = item.Mid(basename.Len());
1325 if (value.at(value.length()-1)==']')
1326 {
1327 return m_IdRanges.at(index);
1328 }
1329 wxXmlResource::Get()->ReportError(node, "a malformed id-range item");
1330 return NULL;
1331 }
1332
1333 void
1334 wxIdRangeManager::NotifyRangeOfItem(const wxXmlNode* node,
1335 const wxString& item) const
1336 {
1337 wxString value;
1338 wxIdRange* range = FindRangeForItem(node, item, value);
1339 if (range)
1340 range->NoteItem(node, value);
1341 }
1342
1343 int wxIdRangeManager::Find(const wxString& rangename) const
1344 {
1345 for ( int i=0; i < (int)m_IdRanges.size(); ++i )
1346 {
1347 if (m_IdRanges.at(i)->GetName() == rangename)
1348 return i;
1349 }
1350
1351 return wxNOT_FOUND;
1352 }
1353
1354 void wxIdRangeManager::FinaliseRanges(const wxXmlNode* node) const
1355 {
1356 for ( wxVector<wxIdRange*>::const_iterator i = m_IdRanges.begin();
1357 i != m_IdRanges.end(); ++i )
1358 {
1359 // Check if this range has already been finalised. Quite possible,
1360 // as FinaliseRanges() gets called for each .xrc file loaded
1361 if (!(*i)->IsFinalised())
1362 {
1363 wxLogTrace("xrcrange", "Finalising ID range %s", (*i)->GetName());
1364 (*i)->Finalise(node);
1365 }
1366 }
1367 }
1368
1369
1370 class wxXmlSubclassFactories : public wxVector<wxXmlSubclassFactory*>
1371 {
1372 // this is a class so that it can be forward-declared
1373 };
1374
1375 wxXmlSubclassFactories *wxXmlResource::ms_subclassFactories = NULL;
1376
1377 /*static*/ void wxXmlResource::AddSubclassFactory(wxXmlSubclassFactory *factory)
1378 {
1379 if (!ms_subclassFactories)
1380 {
1381 ms_subclassFactories = new wxXmlSubclassFactories;
1382 }
1383 ms_subclassFactories->push_back(factory);
1384 }
1385
1386 class wxXmlSubclassFactoryCXX : public wxXmlSubclassFactory
1387 {
1388 public:
1389 ~wxXmlSubclassFactoryCXX() {}
1390
1391 wxObject *Create(const wxString& className)
1392 {
1393 wxClassInfo* classInfo = wxClassInfo::FindClass(className);
1394
1395 if (classInfo)
1396 return classInfo->CreateObject();
1397 else
1398 return NULL;
1399 }
1400 };
1401
1402
1403
1404
1405 wxXmlResourceHandler::wxXmlResourceHandler()
1406 : m_node(NULL), m_parent(NULL), m_instance(NULL),
1407 m_parentAsWindow(NULL)
1408 {}
1409
1410
1411
1412 wxObject *wxXmlResourceHandler::CreateResource(wxXmlNode *node, wxObject *parent, wxObject *instance)
1413 {
1414 wxXmlNode *myNode = m_node;
1415 wxString myClass = m_class;
1416 wxObject *myParent = m_parent, *myInstance = m_instance;
1417 wxWindow *myParentAW = m_parentAsWindow;
1418
1419 m_instance = instance;
1420 if (!m_instance && node->HasAttribute(wxT("subclass")) &&
1421 !(m_resource->GetFlags() & wxXRC_NO_SUBCLASSING))
1422 {
1423 wxString subclass = node->GetAttribute(wxT("subclass"), wxEmptyString);
1424 if (!subclass.empty())
1425 {
1426 for (wxXmlSubclassFactories::iterator i = wxXmlResource::ms_subclassFactories->begin();
1427 i != wxXmlResource::ms_subclassFactories->end(); ++i)
1428 {
1429 m_instance = (*i)->Create(subclass);
1430 if (m_instance)
1431 break;
1432 }
1433
1434 if (!m_instance)
1435 {
1436 wxString name = node->GetAttribute(wxT("name"), wxEmptyString);
1437 ReportError
1438 (
1439 node,
1440 wxString::Format
1441 (
1442 "subclass \"%s\" not found for resource \"%s\", not subclassing",
1443 subclass, name
1444 )
1445 );
1446 }
1447 }
1448 }
1449
1450 m_node = node;
1451 m_class = node->GetAttribute(wxT("class"), wxEmptyString);
1452 m_parent = parent;
1453 m_parentAsWindow = wxDynamicCast(m_parent, wxWindow);
1454
1455 wxObject *returned = DoCreateResource();
1456
1457 m_node = myNode;
1458 m_class = myClass;
1459 m_parent = myParent; m_parentAsWindow = myParentAW;
1460 m_instance = myInstance;
1461
1462 return returned;
1463 }
1464
1465
1466 void wxXmlResourceHandler::AddStyle(const wxString& name, int value)
1467 {
1468 m_styleNames.Add(name);
1469 m_styleValues.Add(value);
1470 }
1471
1472
1473
1474 void wxXmlResourceHandler::AddWindowStyles()
1475 {
1476 XRC_ADD_STYLE(wxCLIP_CHILDREN);
1477
1478 // the border styles all have the old and new names, recognize both for now
1479 XRC_ADD_STYLE(wxSIMPLE_BORDER); XRC_ADD_STYLE(wxBORDER_SIMPLE);
1480 XRC_ADD_STYLE(wxSUNKEN_BORDER); XRC_ADD_STYLE(wxBORDER_SUNKEN);
1481 XRC_ADD_STYLE(wxDOUBLE_BORDER); XRC_ADD_STYLE(wxBORDER_DOUBLE); // deprecated
1482 XRC_ADD_STYLE(wxBORDER_THEME);
1483 XRC_ADD_STYLE(wxRAISED_BORDER); XRC_ADD_STYLE(wxBORDER_RAISED);
1484 XRC_ADD_STYLE(wxSTATIC_BORDER); XRC_ADD_STYLE(wxBORDER_STATIC);
1485 XRC_ADD_STYLE(wxNO_BORDER); XRC_ADD_STYLE(wxBORDER_NONE);
1486
1487 XRC_ADD_STYLE(wxTRANSPARENT_WINDOW);
1488 XRC_ADD_STYLE(wxWANTS_CHARS);
1489 XRC_ADD_STYLE(wxTAB_TRAVERSAL);
1490 XRC_ADD_STYLE(wxNO_FULL_REPAINT_ON_RESIZE);
1491 XRC_ADD_STYLE(wxFULL_REPAINT_ON_RESIZE);
1492 XRC_ADD_STYLE(wxALWAYS_SHOW_SB);
1493 XRC_ADD_STYLE(wxWS_EX_BLOCK_EVENTS);
1494 XRC_ADD_STYLE(wxWS_EX_VALIDATE_RECURSIVELY);
1495 }
1496
1497
1498
1499 bool wxXmlResourceHandler::HasParam(const wxString& param)
1500 {
1501 return (GetParamNode(param) != NULL);
1502 }
1503
1504
1505 int wxXmlResourceHandler::GetStyle(const wxString& param, int defaults)
1506 {
1507 wxString s = GetParamValue(param);
1508
1509 if (!s) return defaults;
1510
1511 wxStringTokenizer tkn(s, wxT("| \t\n"), wxTOKEN_STRTOK);
1512 int style = 0;
1513 int index;
1514 wxString fl;
1515 while (tkn.HasMoreTokens())
1516 {
1517 fl = tkn.GetNextToken();
1518 index = m_styleNames.Index(fl);
1519 if (index != wxNOT_FOUND)
1520 {
1521 style |= m_styleValues[index];
1522 }
1523 else
1524 {
1525 ReportParamError
1526 (
1527 param,
1528 wxString::Format("unknown style flag \"%s\"", fl)
1529 );
1530 }
1531 }
1532 return style;
1533 }
1534
1535
1536
1537 wxString wxXmlResourceHandler::GetText(const wxString& param, bool translate)
1538 {
1539 wxXmlNode *parNode = GetParamNode(param);
1540 wxString str1(GetNodeContent(parNode));
1541 wxString str2;
1542
1543 // "\\" wasn't translated to "\" prior to 2.5.3.0:
1544 const bool escapeBackslash = (m_resource->CompareVersion(2,5,3,0) >= 0);
1545
1546 // VS: First version of XRC resources used $ instead of & (which is
1547 // illegal in XML), but later I realized that '_' fits this purpose
1548 // much better (because &File means "File with F underlined").
1549 const wxChar amp_char = (m_resource->CompareVersion(2,3,0,1) < 0)
1550 ? '$' : '_';
1551
1552 for ( wxString::const_iterator dt = str1.begin(); dt != str1.end(); ++dt )
1553 {
1554 // Remap amp_char to &, map double amp_char to amp_char (for things
1555 // like "&File..." -- this is illegal in XML, so we use "_File..."):
1556 if ( *dt == amp_char )
1557 {
1558 if ( *(++dt) == amp_char )
1559 str2 << amp_char;
1560 else
1561 str2 << wxT('&') << *dt;
1562 }
1563 // Remap \n to CR, \r to LF, \t to TAB, \\ to \:
1564 else if ( *dt == wxT('\\') )
1565 {
1566 switch ( (*(++dt)).GetValue() )
1567 {
1568 case wxT('n'):
1569 str2 << wxT('\n');
1570 break;
1571
1572 case wxT('t'):
1573 str2 << wxT('\t');
1574 break;
1575
1576 case wxT('r'):
1577 str2 << wxT('\r');
1578 break;
1579
1580 case wxT('\\') :
1581 // "\\" wasn't translated to "\" prior to 2.5.3.0:
1582 if ( escapeBackslash )
1583 {
1584 str2 << wxT('\\');
1585 break;
1586 }
1587 // else fall-through to default: branch below
1588
1589 default:
1590 str2 << wxT('\\') << *dt;
1591 break;
1592 }
1593 }
1594 else
1595 {
1596 str2 << *dt;
1597 }
1598 }
1599
1600 if (m_resource->GetFlags() & wxXRC_USE_LOCALE)
1601 {
1602 if (translate && parNode &&
1603 parNode->GetAttribute(wxT("translate"), wxEmptyString) != wxT("0"))
1604 {
1605 return wxGetTranslation(str2, m_resource->GetDomain());
1606 }
1607 else
1608 {
1609 #if wxUSE_UNICODE
1610 return str2;
1611 #else
1612 // The string is internally stored as UTF-8, we have to convert
1613 // it into system's default encoding so that it can be displayed:
1614 return wxString(str2.wc_str(wxConvUTF8), wxConvLocal);
1615 #endif
1616 }
1617 }
1618
1619 // If wxXRC_USE_LOCALE is not set, then the string is already in
1620 // system's default encoding in ANSI build, so we don't have to
1621 // do anything special here.
1622 return str2;
1623 }
1624
1625
1626
1627 long wxXmlResourceHandler::GetLong(const wxString& param, long defaultv)
1628 {
1629 long value;
1630 wxString str1 = GetParamValue(param);
1631
1632 if (!str1.ToLong(&value))
1633 value = defaultv;
1634
1635 return value;
1636 }
1637
1638 float wxXmlResourceHandler::GetFloat(const wxString& param, float defaultv)
1639 {
1640 wxString str = GetParamValue(param);
1641
1642 // strings in XRC always use C locale so make sure to use the
1643 // locale-independent wxString::ToCDouble() and not ToDouble() which uses
1644 // the current locale with a potentially different decimal point character
1645 double value;
1646 if (!str.ToCDouble(&value))
1647 value = defaultv;
1648
1649 return wx_truncate_cast(float, value);
1650 }
1651
1652
1653 int wxXmlResourceHandler::GetID()
1654 {
1655 return wxXmlResource::GetXRCID(GetName());
1656 }
1657
1658
1659
1660 wxString wxXmlResourceHandler::GetName()
1661 {
1662 return m_node->GetAttribute(wxT("name"), wxT("-1"));
1663 }
1664
1665
1666
1667 bool wxXmlResourceHandler::GetBoolAttr(const wxString& attr, bool defaultv)
1668 {
1669 wxString v;
1670 return m_node->GetAttribute(attr, &v) ? v == '1' : defaultv;
1671 }
1672
1673 bool wxXmlResourceHandler::GetBool(const wxString& param, bool defaultv)
1674 {
1675 const wxString v = GetParamValue(param);
1676
1677 return v.empty() ? defaultv : (v == '1');
1678 }
1679
1680
1681 static wxColour GetSystemColour(const wxString& name)
1682 {
1683 if (!name.empty())
1684 {
1685 #define SYSCLR(clr) \
1686 if (name == wxT(#clr)) return wxSystemSettings::GetColour(clr);
1687 SYSCLR(wxSYS_COLOUR_SCROLLBAR)
1688 SYSCLR(wxSYS_COLOUR_BACKGROUND)
1689 SYSCLR(wxSYS_COLOUR_DESKTOP)
1690 SYSCLR(wxSYS_COLOUR_ACTIVECAPTION)
1691 SYSCLR(wxSYS_COLOUR_INACTIVECAPTION)
1692 SYSCLR(wxSYS_COLOUR_MENU)
1693 SYSCLR(wxSYS_COLOUR_WINDOW)
1694 SYSCLR(wxSYS_COLOUR_WINDOWFRAME)
1695 SYSCLR(wxSYS_COLOUR_MENUTEXT)
1696 SYSCLR(wxSYS_COLOUR_WINDOWTEXT)
1697 SYSCLR(wxSYS_COLOUR_CAPTIONTEXT)
1698 SYSCLR(wxSYS_COLOUR_ACTIVEBORDER)
1699 SYSCLR(wxSYS_COLOUR_INACTIVEBORDER)
1700 SYSCLR(wxSYS_COLOUR_APPWORKSPACE)
1701 SYSCLR(wxSYS_COLOUR_HIGHLIGHT)
1702 SYSCLR(wxSYS_COLOUR_HIGHLIGHTTEXT)
1703 SYSCLR(wxSYS_COLOUR_BTNFACE)
1704 SYSCLR(wxSYS_COLOUR_3DFACE)
1705 SYSCLR(wxSYS_COLOUR_BTNSHADOW)
1706 SYSCLR(wxSYS_COLOUR_3DSHADOW)
1707 SYSCLR(wxSYS_COLOUR_GRAYTEXT)
1708 SYSCLR(wxSYS_COLOUR_BTNTEXT)
1709 SYSCLR(wxSYS_COLOUR_INACTIVECAPTIONTEXT)
1710 SYSCLR(wxSYS_COLOUR_BTNHIGHLIGHT)
1711 SYSCLR(wxSYS_COLOUR_BTNHILIGHT)
1712 SYSCLR(wxSYS_COLOUR_3DHIGHLIGHT)
1713 SYSCLR(wxSYS_COLOUR_3DHILIGHT)
1714 SYSCLR(wxSYS_COLOUR_3DDKSHADOW)
1715 SYSCLR(wxSYS_COLOUR_3DLIGHT)
1716 SYSCLR(wxSYS_COLOUR_INFOTEXT)
1717 SYSCLR(wxSYS_COLOUR_INFOBK)
1718 SYSCLR(wxSYS_COLOUR_LISTBOX)
1719 SYSCLR(wxSYS_COLOUR_HOTLIGHT)
1720 SYSCLR(wxSYS_COLOUR_GRADIENTACTIVECAPTION)
1721 SYSCLR(wxSYS_COLOUR_GRADIENTINACTIVECAPTION)
1722 SYSCLR(wxSYS_COLOUR_MENUHILIGHT)
1723 SYSCLR(wxSYS_COLOUR_MENUBAR)
1724 #undef SYSCLR
1725 }
1726
1727 return wxNullColour;
1728 }
1729
1730 wxColour wxXmlResourceHandler::GetColour(const wxString& param, const wxColour& defaultv)
1731 {
1732 wxString v = GetParamValue(param);
1733
1734 if ( v.empty() )
1735 return defaultv;
1736
1737 wxColour clr;
1738
1739 // wxString -> wxColour conversion
1740 if (!clr.Set(v))
1741 {
1742 // the colour doesn't use #RRGGBB format, check if it is symbolic
1743 // colour name:
1744 clr = GetSystemColour(v);
1745 if (clr.Ok())
1746 return clr;
1747
1748 ReportParamError
1749 (
1750 param,
1751 wxString::Format("incorrect colour specification \"%s\"", v)
1752 );
1753 return wxNullColour;
1754 }
1755
1756 return clr;
1757 }
1758
1759 namespace
1760 {
1761
1762 // if 'param' has stock_id/stock_client, extracts them and returns true
1763 bool GetStockArtAttrs(const wxXmlNode *paramNode,
1764 const wxString& defaultArtClient,
1765 wxString& art_id, wxString& art_client)
1766 {
1767 if ( paramNode )
1768 {
1769 art_id = paramNode->GetAttribute("stock_id", "");
1770
1771 if ( !art_id.empty() )
1772 {
1773 art_id = wxART_MAKE_ART_ID_FROM_STR(art_id);
1774
1775 art_client = paramNode->GetAttribute("stock_client", "");
1776 if ( art_client.empty() )
1777 art_client = defaultArtClient;
1778 else
1779 art_client = wxART_MAKE_CLIENT_ID_FROM_STR(art_client);
1780
1781 return true;
1782 }
1783 }
1784
1785 return false;
1786 }
1787
1788 } // anonymous namespace
1789
1790 wxBitmap wxXmlResourceHandler::GetBitmap(const wxString& param,
1791 const wxArtClient& defaultArtClient,
1792 wxSize size)
1793 {
1794 // it used to be possible to pass an empty string here to indicate that the
1795 // bitmap name should be read from this node itself but this is not
1796 // supported any more because GetBitmap(m_node) can be used directly
1797 // instead
1798 wxASSERT_MSG( !param.empty(), "bitmap parameter name can't be empty" );
1799
1800 const wxXmlNode* const node = GetParamNode(param);
1801
1802 if ( !node )
1803 {
1804 // this is not an error as bitmap parameter could be optional
1805 return wxNullBitmap;
1806 }
1807
1808 return GetBitmap(node, defaultArtClient, size);
1809 }
1810
1811 wxBitmap wxXmlResourceHandler::GetBitmap(const wxXmlNode* node,
1812 const wxArtClient& defaultArtClient,
1813 wxSize size)
1814 {
1815 wxCHECK_MSG( node, wxNullBitmap, "bitmap node can't be NULL" );
1816
1817 /* If the bitmap is specified as stock item, query wxArtProvider for it: */
1818 wxString art_id, art_client;
1819 if ( GetStockArtAttrs(node, defaultArtClient,
1820 art_id, art_client) )
1821 {
1822 wxBitmap stockArt(wxArtProvider::GetBitmap(art_id, art_client, size));
1823 if ( stockArt.Ok() )
1824 return stockArt;
1825 }
1826
1827 /* ...or load the bitmap from file: */
1828 wxString name = GetParamValue(node);
1829 if (name.empty()) return wxNullBitmap;
1830 #if wxUSE_FILESYSTEM
1831 wxFSFile *fsfile = GetCurFileSystem().OpenFile(name, wxFS_READ | wxFS_SEEKABLE);
1832 if (fsfile == NULL)
1833 {
1834 ReportParamError
1835 (
1836 node->GetName(),
1837 wxString::Format("cannot open bitmap resource \"%s\"", name)
1838 );
1839 return wxNullBitmap;
1840 }
1841 wxImage img(*(fsfile->GetStream()));
1842 delete fsfile;
1843 #else
1844 wxImage img(name);
1845 #endif
1846
1847 if (!img.Ok())
1848 {
1849 ReportParamError
1850 (
1851 node->GetName(),
1852 wxString::Format("cannot create bitmap from \"%s\"", name)
1853 );
1854 return wxNullBitmap;
1855 }
1856 if (!(size == wxDefaultSize)) img.Rescale(size.x, size.y);
1857 return wxBitmap(img);
1858 }
1859
1860
1861 wxIcon wxXmlResourceHandler::GetIcon(const wxString& param,
1862 const wxArtClient& defaultArtClient,
1863 wxSize size)
1864 {
1865 // see comment in GetBitmap(wxString) overload
1866 wxASSERT_MSG( !param.empty(), "icon parameter name can't be empty" );
1867
1868 const wxXmlNode* const node = GetParamNode(param);
1869
1870 if ( !node )
1871 {
1872 // this is not an error as icon parameter could be optional
1873 return wxIcon();
1874 }
1875
1876 return GetIcon(node, defaultArtClient, size);
1877 }
1878
1879 wxIcon wxXmlResourceHandler::GetIcon(const wxXmlNode* node,
1880 const wxArtClient& defaultArtClient,
1881 wxSize size)
1882 {
1883 wxIcon icon;
1884 icon.CopyFromBitmap(GetBitmap(node, defaultArtClient, size));
1885 return icon;
1886 }
1887
1888
1889 wxIconBundle wxXmlResourceHandler::GetIconBundle(const wxString& param,
1890 const wxArtClient& defaultArtClient)
1891 {
1892 wxString art_id, art_client;
1893 if ( GetStockArtAttrs(GetParamNode(param), defaultArtClient,
1894 art_id, art_client) )
1895 {
1896 wxIconBundle stockArt(wxArtProvider::GetIconBundle(art_id, art_client));
1897 if ( stockArt.IsOk() )
1898 return stockArt;
1899 }
1900
1901 const wxString name = GetParamValue(param);
1902 if ( name.empty() )
1903 return wxNullIconBundle;
1904
1905 #if wxUSE_FILESYSTEM
1906 wxFSFile *fsfile = GetCurFileSystem().OpenFile(name, wxFS_READ | wxFS_SEEKABLE);
1907 if ( fsfile == NULL )
1908 {
1909 ReportParamError
1910 (
1911 param,
1912 wxString::Format("cannot open icon resource \"%s\"", name)
1913 );
1914 return wxNullIconBundle;
1915 }
1916
1917 wxIconBundle bundle(*(fsfile->GetStream()));
1918 delete fsfile;
1919 #else
1920 wxIconBundle bundle(name);
1921 #endif
1922
1923 if ( !bundle.IsOk() )
1924 {
1925 ReportParamError
1926 (
1927 param,
1928 wxString::Format("cannot create icon from \"%s\"", name)
1929 );
1930 return wxNullIconBundle;
1931 }
1932
1933 return bundle;
1934 }
1935
1936
1937 wxImageList *wxXmlResourceHandler::GetImageList(const wxString& param)
1938 {
1939 wxXmlNode * const imagelist_node = GetParamNode(param);
1940 if ( !imagelist_node )
1941 return NULL;
1942
1943 wxXmlNode * const oldnode = m_node;
1944 m_node = imagelist_node;
1945
1946 // Get the size if we have it, otherwise we will use the size of the first
1947 // list element.
1948 wxSize size = GetSize();
1949
1950 // Start adding images, we'll create the image list when adding the first
1951 // one.
1952 wxImageList * imagelist = NULL;
1953 wxString parambitmap = wxT("bitmap");
1954 if ( HasParam(parambitmap) )
1955 {
1956 wxXmlNode *n = m_node->GetChildren();
1957 while (n)
1958 {
1959 if (n->GetType() == wxXML_ELEMENT_NODE && n->GetName() == parambitmap)
1960 {
1961 wxIcon icon = GetIcon(n);
1962 if ( !imagelist )
1963 {
1964 // We need the real image list size to create it.
1965 if ( size == wxDefaultSize )
1966 size = icon.GetSize();
1967
1968 // We use the mask by default.
1969 bool mask = !HasParam(wxS("mask")) || GetBool(wxS("mask"));
1970
1971 imagelist = new wxImageList(size.x, size.y, mask);
1972 }
1973
1974 // add icon instead of bitmap to keep the bitmap mask
1975 imagelist->Add(icon);
1976 }
1977 n = n->GetNext();
1978 }
1979 }
1980
1981 m_node = oldnode;
1982 return imagelist;
1983 }
1984
1985 wxXmlNode *wxXmlResourceHandler::GetParamNode(const wxString& param)
1986 {
1987 wxCHECK_MSG(m_node, NULL, wxT("You can't access handler data before it was initialized!"));
1988
1989 wxXmlNode *n = m_node->GetChildren();
1990
1991 while (n)
1992 {
1993 if (n->GetType() == wxXML_ELEMENT_NODE && n->GetName() == param)
1994 {
1995 // TODO: check that there are no other properties/parameters with
1996 // the same name and log an error if there are (can't do this
1997 // right now as I'm not sure if it's not going to break code
1998 // using this function in unintentional way (i.e. for
1999 // accessing other things than properties), for example
2000 // wxBitmapComboBoxXmlHandler almost surely does
2001 return n;
2002 }
2003 n = n->GetNext();
2004 }
2005 return NULL;
2006 }
2007
2008 /* static */
2009 bool wxXmlResourceHandler::IsOfClass(wxXmlNode *node, const wxString& classname)
2010 {
2011 return node->GetAttribute(wxT("class")) == classname;
2012 }
2013
2014
2015
2016 wxString wxXmlResourceHandler::GetNodeContent(const wxXmlNode *node)
2017 {
2018 const wxXmlNode *n = node;
2019 if (n == NULL) return wxEmptyString;
2020 n = n->GetChildren();
2021
2022 while (n)
2023 {
2024 if (n->GetType() == wxXML_TEXT_NODE ||
2025 n->GetType() == wxXML_CDATA_SECTION_NODE)
2026 return n->GetContent();
2027 n = n->GetNext();
2028 }
2029 return wxEmptyString;
2030 }
2031
2032
2033
2034 wxString wxXmlResourceHandler::GetParamValue(const wxString& param)
2035 {
2036 if (param.empty())
2037 return GetNodeContent(m_node);
2038 else
2039 return GetNodeContent(GetParamNode(param));
2040 }
2041
2042 wxString wxXmlResourceHandler::GetParamValue(const wxXmlNode* node)
2043 {
2044 return GetNodeContent(node);
2045 }
2046
2047
2048 wxSize wxXmlResourceHandler::GetSize(const wxString& param,
2049 wxWindow *windowToUse)
2050 {
2051 wxString s = GetParamValue(param);
2052 if (s.empty()) s = wxT("-1,-1");
2053 bool is_dlg;
2054 long sx, sy = 0;
2055
2056 is_dlg = s[s.length()-1] == wxT('d');
2057 if (is_dlg) s.RemoveLast();
2058
2059 if (!s.BeforeFirst(wxT(',')).ToLong(&sx) ||
2060 !s.AfterLast(wxT(',')).ToLong(&sy))
2061 {
2062 ReportParamError
2063 (
2064 param,
2065 wxString::Format("cannot parse coordinates value \"%s\"", s)
2066 );
2067 return wxDefaultSize;
2068 }
2069
2070 if (is_dlg)
2071 {
2072 if (windowToUse)
2073 {
2074 return wxDLG_UNIT(windowToUse, wxSize(sx, sy));
2075 }
2076 else if (m_parentAsWindow)
2077 {
2078 return wxDLG_UNIT(m_parentAsWindow, wxSize(sx, sy));
2079 }
2080 else
2081 {
2082 ReportParamError
2083 (
2084 param,
2085 "cannot convert dialog units: dialog unknown"
2086 );
2087 return wxDefaultSize;
2088 }
2089 }
2090
2091 return wxSize(sx, sy);
2092 }
2093
2094
2095
2096 wxPoint wxXmlResourceHandler::GetPosition(const wxString& param)
2097 {
2098 wxSize sz = GetSize(param);
2099 return wxPoint(sz.x, sz.y);
2100 }
2101
2102
2103
2104 wxCoord wxXmlResourceHandler::GetDimension(const wxString& param,
2105 wxCoord defaultv,
2106 wxWindow *windowToUse)
2107 {
2108 wxString s = GetParamValue(param);
2109 if (s.empty()) return defaultv;
2110 bool is_dlg;
2111 long sx;
2112
2113 is_dlg = s[s.length()-1] == wxT('d');
2114 if (is_dlg) s.RemoveLast();
2115
2116 if (!s.ToLong(&sx))
2117 {
2118 ReportParamError
2119 (
2120 param,
2121 wxString::Format("cannot parse dimension value \"%s\"", s)
2122 );
2123 return defaultv;
2124 }
2125
2126 if (is_dlg)
2127 {
2128 if (windowToUse)
2129 {
2130 return wxDLG_UNIT(windowToUse, wxSize(sx, 0)).x;
2131 }
2132 else if (m_parentAsWindow)
2133 {
2134 return wxDLG_UNIT(m_parentAsWindow, wxSize(sx, 0)).x;
2135 }
2136 else
2137 {
2138 ReportParamError
2139 (
2140 param,
2141 "cannot convert dialog units: dialog unknown"
2142 );
2143 return defaultv;
2144 }
2145 }
2146
2147 return sx;
2148 }
2149
2150
2151 // Get system font index using indexname
2152 static wxFont GetSystemFont(const wxString& name)
2153 {
2154 if (!name.empty())
2155 {
2156 #define SYSFNT(fnt) \
2157 if (name == wxT(#fnt)) return wxSystemSettings::GetFont(fnt);
2158 SYSFNT(wxSYS_OEM_FIXED_FONT)
2159 SYSFNT(wxSYS_ANSI_FIXED_FONT)
2160 SYSFNT(wxSYS_ANSI_VAR_FONT)
2161 SYSFNT(wxSYS_SYSTEM_FONT)
2162 SYSFNT(wxSYS_DEVICE_DEFAULT_FONT)
2163 SYSFNT(wxSYS_SYSTEM_FIXED_FONT)
2164 SYSFNT(wxSYS_DEFAULT_GUI_FONT)
2165 #undef SYSFNT
2166 }
2167
2168 return wxNullFont;
2169 }
2170
2171 wxFont wxXmlResourceHandler::GetFont(const wxString& param)
2172 {
2173 wxXmlNode *font_node = GetParamNode(param);
2174 if (font_node == NULL)
2175 {
2176 ReportError(
2177 wxString::Format("cannot find font node \"%s\"", param));
2178 return wxNullFont;
2179 }
2180
2181 wxXmlNode *oldnode = m_node;
2182 m_node = font_node;
2183
2184 // font attributes:
2185
2186 // size
2187 int isize = -1;
2188 bool hasSize = HasParam(wxT("size"));
2189 if (hasSize)
2190 isize = GetLong(wxT("size"), -1);
2191
2192 // style
2193 int istyle = wxNORMAL;
2194 bool hasStyle = HasParam(wxT("style"));
2195 if (hasStyle)
2196 {
2197 wxString style = GetParamValue(wxT("style"));
2198 if (style == wxT("italic"))
2199 istyle = wxITALIC;
2200 else if (style == wxT("slant"))
2201 istyle = wxSLANT;
2202 }
2203
2204 // weight
2205 int iweight = wxNORMAL;
2206 bool hasWeight = HasParam(wxT("weight"));
2207 if (hasWeight)
2208 {
2209 wxString weight = GetParamValue(wxT("weight"));
2210 if (weight == wxT("bold"))
2211 iweight = wxBOLD;
2212 else if (weight == wxT("light"))
2213 iweight = wxLIGHT;
2214 }
2215
2216 // underline
2217 bool hasUnderlined = HasParam(wxT("underlined"));
2218 bool underlined = hasUnderlined ? GetBool(wxT("underlined"), false) : false;
2219
2220 // family and facename
2221 int ifamily = wxDEFAULT;
2222 bool hasFamily = HasParam(wxT("family"));
2223 if (hasFamily)
2224 {
2225 wxString family = GetParamValue(wxT("family"));
2226 if (family == wxT("decorative")) ifamily = wxDECORATIVE;
2227 else if (family == wxT("roman")) ifamily = wxROMAN;
2228 else if (family == wxT("script")) ifamily = wxSCRIPT;
2229 else if (family == wxT("swiss")) ifamily = wxSWISS;
2230 else if (family == wxT("modern")) ifamily = wxMODERN;
2231 else if (family == wxT("teletype")) ifamily = wxTELETYPE;
2232 }
2233
2234
2235 wxString facename;
2236 bool hasFacename = HasParam(wxT("face"));
2237 if (hasFacename)
2238 {
2239 wxString faces = GetParamValue(wxT("face"));
2240 wxStringTokenizer tk(faces, wxT(","));
2241 #if wxUSE_FONTENUM
2242 wxArrayString facenames(wxFontEnumerator::GetFacenames());
2243 while (tk.HasMoreTokens())
2244 {
2245 int index = facenames.Index(tk.GetNextToken(), false);
2246 if (index != wxNOT_FOUND)
2247 {
2248 facename = facenames[index];
2249 break;
2250 }
2251 }
2252 #else // !wxUSE_FONTENUM
2253 // just use the first face name if we can't check its availability:
2254 if (tk.HasMoreTokens())
2255 facename = tk.GetNextToken();
2256 #endif // wxUSE_FONTENUM/!wxUSE_FONTENUM
2257 }
2258
2259 // encoding
2260 wxFontEncoding enc = wxFONTENCODING_DEFAULT;
2261 bool hasEncoding = HasParam(wxT("encoding"));
2262 #if wxUSE_FONTMAP
2263 if (hasEncoding)
2264 {
2265 wxString encoding = GetParamValue(wxT("encoding"));
2266 wxFontMapper mapper;
2267 if (!encoding.empty())
2268 enc = mapper.CharsetToEncoding(encoding);
2269 if (enc == wxFONTENCODING_SYSTEM)
2270 enc = wxFONTENCODING_DEFAULT;
2271 }
2272 #endif // wxUSE_FONTMAP
2273
2274 // is this font based on a system font?
2275 wxFont font = GetSystemFont(GetParamValue(wxT("sysfont")));
2276
2277 if (font.Ok())
2278 {
2279 if (hasSize && isize != -1)
2280 font.SetPointSize(isize);
2281 else if (HasParam(wxT("relativesize")))
2282 font.SetPointSize(int(font.GetPointSize() *
2283 GetFloat(wxT("relativesize"))));
2284
2285 if (hasStyle)
2286 font.SetStyle(istyle);
2287 if (hasWeight)
2288 font.SetWeight(iweight);
2289 if (hasUnderlined)
2290 font.SetUnderlined(underlined);
2291 if (hasFamily)
2292 font.SetFamily(ifamily);
2293 if (hasFacename)
2294 font.SetFaceName(facename);
2295 if (hasEncoding)
2296 font.SetDefaultEncoding(enc);
2297 }
2298 else // not based on system font
2299 {
2300 font = wxFont(isize == -1 ? wxNORMAL_FONT->GetPointSize() : isize,
2301 ifamily, istyle, iweight,
2302 underlined, facename, enc);
2303 }
2304
2305 m_node = oldnode;
2306 return font;
2307 }
2308
2309
2310 void wxXmlResourceHandler::SetupWindow(wxWindow *wnd)
2311 {
2312 //FIXME : add cursor
2313
2314 if (HasParam(wxT("exstyle")))
2315 // Have to OR it with existing style, since
2316 // some implementations (e.g. wxGTK) use the extra style
2317 // during creation
2318 wnd->SetExtraStyle(wnd->GetExtraStyle() | GetStyle(wxT("exstyle")));
2319 if (HasParam(wxT("bg")))
2320 wnd->SetBackgroundColour(GetColour(wxT("bg")));
2321 if (HasParam(wxT("ownbg")))
2322 wnd->SetOwnBackgroundColour(GetColour(wxT("ownbg")));
2323 if (HasParam(wxT("fg")))
2324 wnd->SetForegroundColour(GetColour(wxT("fg")));
2325 if (HasParam(wxT("ownfg")))
2326 wnd->SetOwnForegroundColour(GetColour(wxT("ownfg")));
2327 if (GetBool(wxT("enabled"), 1) == 0)
2328 wnd->Enable(false);
2329 if (GetBool(wxT("focused"), 0) == 1)
2330 wnd->SetFocus();
2331 if (GetBool(wxT("hidden"), 0) == 1)
2332 wnd->Show(false);
2333 #if wxUSE_TOOLTIPS
2334 if (HasParam(wxT("tooltip")))
2335 wnd->SetToolTip(GetText(wxT("tooltip")));
2336 #endif
2337 if (HasParam(wxT("font")))
2338 wnd->SetFont(GetFont(wxT("font")));
2339 if (HasParam(wxT("ownfont")))
2340 wnd->SetOwnFont(GetFont(wxT("ownfont")));
2341 if (HasParam(wxT("help")))
2342 wnd->SetHelpText(GetText(wxT("help")));
2343 }
2344
2345
2346 void wxXmlResourceHandler::CreateChildren(wxObject *parent, bool this_hnd_only)
2347 {
2348 for ( wxXmlNode *n = m_node->GetChildren(); n; n = n->GetNext() )
2349 {
2350 if ( IsObjectNode(n) )
2351 {
2352 m_resource->DoCreateResFromNode(*n, parent, NULL,
2353 this_hnd_only ? this : NULL);
2354 }
2355 }
2356 }
2357
2358
2359 void wxXmlResourceHandler::CreateChildrenPrivately(wxObject *parent, wxXmlNode *rootnode)
2360 {
2361 wxXmlNode *root;
2362 if (rootnode == NULL) root = m_node; else root = rootnode;
2363 wxXmlNode *n = root->GetChildren();
2364
2365 while (n)
2366 {
2367 if (n->GetType() == wxXML_ELEMENT_NODE && CanHandle(n))
2368 {
2369 CreateResource(n, parent, NULL);
2370 }
2371 n = n->GetNext();
2372 }
2373 }
2374
2375
2376 //-----------------------------------------------------------------------------
2377 // errors reporting
2378 //-----------------------------------------------------------------------------
2379
2380 void wxXmlResourceHandler::ReportError(const wxString& message)
2381 {
2382 m_resource->ReportError(m_node, message);
2383 }
2384
2385 void wxXmlResourceHandler::ReportError(wxXmlNode *context,
2386 const wxString& message)
2387 {
2388 m_resource->ReportError(context ? context : m_node, message);
2389 }
2390
2391 void wxXmlResourceHandler::ReportParamError(const wxString& param,
2392 const wxString& message)
2393 {
2394 m_resource->ReportError(GetParamNode(param), message);
2395 }
2396
2397 void wxXmlResource::ReportError(const wxXmlNode *context, const wxString& message)
2398 {
2399 if ( !context )
2400 {
2401 DoReportError("", NULL, message);
2402 return;
2403 }
2404
2405 // We need to find out the file that 'context' is part of. Performance of
2406 // this code is not critical, so we simply find the root XML node and
2407 // compare it with all loaded XRC files.
2408 const wxString filename = GetFileNameFromNode(context, Data());
2409
2410 DoReportError(filename, context, message);
2411 }
2412
2413 void wxXmlResource::DoReportError(const wxString& xrcFile, const wxXmlNode *position,
2414 const wxString& message)
2415 {
2416 const int line = position ? position->GetLineNumber() : -1;
2417
2418 wxString loc;
2419 if ( !xrcFile.empty() )
2420 loc = xrcFile + ':';
2421 if ( line != -1 )
2422 loc += wxString::Format("%d:", line);
2423 if ( !loc.empty() )
2424 loc += ' ';
2425
2426 wxLogError("XRC error: %s%s", loc, message);
2427 }
2428
2429
2430 //-----------------------------------------------------------------------------
2431 // XRCID implementation
2432 //-----------------------------------------------------------------------------
2433
2434 #define XRCID_TABLE_SIZE 1024
2435
2436
2437 struct XRCID_record
2438 {
2439 /* Hold the id so that once an id is allocated for a name, it
2440 does not get created again by NewControlId at least
2441 until we are done with it */
2442 wxWindowIDRef id;
2443 char *key;
2444 XRCID_record *next;
2445 };
2446
2447 static XRCID_record *XRCID_Records[XRCID_TABLE_SIZE] = {NULL};
2448
2449 // Extremely simplistic hash function which probably ought to be replaced with
2450 // wxStringHash::stringHash().
2451 static inline unsigned XRCIdHash(const char *str_id)
2452 {
2453 unsigned index = 0;
2454
2455 for (const char *c = str_id; *c != '\0'; c++) index += (unsigned int)*c;
2456 index %= XRCID_TABLE_SIZE;
2457
2458 return index;
2459 }
2460
2461 static int XRCID_Lookup(const char *str_id, int value_if_not_found = wxID_NONE)
2462 {
2463 const unsigned index = XRCIdHash(str_id);
2464
2465
2466 XRCID_record *oldrec = NULL;
2467 for (XRCID_record *rec = XRCID_Records[index]; rec; rec = rec->next)
2468 {
2469 if (wxStrcmp(rec->key, str_id) == 0)
2470 {
2471 return rec->id;
2472 }
2473 oldrec = rec;
2474 }
2475
2476 XRCID_record **rec_var = (oldrec == NULL) ?
2477 &XRCID_Records[index] : &oldrec->next;
2478 *rec_var = new XRCID_record;
2479 (*rec_var)->key = wxStrdup(str_id);
2480 (*rec_var)->next = NULL;
2481
2482 char *end;
2483 if (value_if_not_found != wxID_NONE)
2484 (*rec_var)->id = value_if_not_found;
2485 else
2486 {
2487 int asint = wxStrtol(str_id, &end, 10);
2488 if (*str_id && *end == 0)
2489 {
2490 // if str_id was integer, keep it verbosely:
2491 (*rec_var)->id = asint;
2492 }
2493 else
2494 {
2495 (*rec_var)->id = wxWindowBase::NewControlId();
2496 }
2497 }
2498
2499 return (*rec_var)->id;
2500 }
2501
2502 namespace
2503 {
2504
2505 // flag indicating whether standard XRC ids were already initialized
2506 static bool gs_stdIDsAdded = false;
2507
2508 void AddStdXRCID_Records()
2509 {
2510 #define stdID(id) XRCID_Lookup(#id, id)
2511 stdID(-1);
2512
2513 stdID(wxID_ANY);
2514 stdID(wxID_SEPARATOR);
2515
2516 stdID(wxID_OPEN);
2517 stdID(wxID_CLOSE);
2518 stdID(wxID_NEW);
2519 stdID(wxID_SAVE);
2520 stdID(wxID_SAVEAS);
2521 stdID(wxID_REVERT);
2522 stdID(wxID_EXIT);
2523 stdID(wxID_UNDO);
2524 stdID(wxID_REDO);
2525 stdID(wxID_HELP);
2526 stdID(wxID_PRINT);
2527 stdID(wxID_PRINT_SETUP);
2528 stdID(wxID_PAGE_SETUP);
2529 stdID(wxID_PREVIEW);
2530 stdID(wxID_ABOUT);
2531 stdID(wxID_HELP_CONTENTS);
2532 stdID(wxID_HELP_COMMANDS);
2533 stdID(wxID_HELP_PROCEDURES);
2534 stdID(wxID_HELP_CONTEXT);
2535 stdID(wxID_CLOSE_ALL);
2536 stdID(wxID_PREFERENCES);
2537 stdID(wxID_EDIT);
2538 stdID(wxID_CUT);
2539 stdID(wxID_COPY);
2540 stdID(wxID_PASTE);
2541 stdID(wxID_CLEAR);
2542 stdID(wxID_FIND);
2543 stdID(wxID_DUPLICATE);
2544 stdID(wxID_SELECTALL);
2545 stdID(wxID_DELETE);
2546 stdID(wxID_REPLACE);
2547 stdID(wxID_REPLACE_ALL);
2548 stdID(wxID_PROPERTIES);
2549 stdID(wxID_VIEW_DETAILS);
2550 stdID(wxID_VIEW_LARGEICONS);
2551 stdID(wxID_VIEW_SMALLICONS);
2552 stdID(wxID_VIEW_LIST);
2553 stdID(wxID_VIEW_SORTDATE);
2554 stdID(wxID_VIEW_SORTNAME);
2555 stdID(wxID_VIEW_SORTSIZE);
2556 stdID(wxID_VIEW_SORTTYPE);
2557 stdID(wxID_FILE1);
2558 stdID(wxID_FILE2);
2559 stdID(wxID_FILE3);
2560 stdID(wxID_FILE4);
2561 stdID(wxID_FILE5);
2562 stdID(wxID_FILE6);
2563 stdID(wxID_FILE7);
2564 stdID(wxID_FILE8);
2565 stdID(wxID_FILE9);
2566 stdID(wxID_OK);
2567 stdID(wxID_CANCEL);
2568 stdID(wxID_APPLY);
2569 stdID(wxID_YES);
2570 stdID(wxID_NO);
2571 stdID(wxID_STATIC);
2572 stdID(wxID_FORWARD);
2573 stdID(wxID_BACKWARD);
2574 stdID(wxID_DEFAULT);
2575 stdID(wxID_MORE);
2576 stdID(wxID_SETUP);
2577 stdID(wxID_RESET);
2578 stdID(wxID_CONTEXT_HELP);
2579 stdID(wxID_YESTOALL);
2580 stdID(wxID_NOTOALL);
2581 stdID(wxID_ABORT);
2582 stdID(wxID_RETRY);
2583 stdID(wxID_IGNORE);
2584 stdID(wxID_ADD);
2585 stdID(wxID_REMOVE);
2586 stdID(wxID_UP);
2587 stdID(wxID_DOWN);
2588 stdID(wxID_HOME);
2589 stdID(wxID_REFRESH);
2590 stdID(wxID_STOP);
2591 stdID(wxID_INDEX);
2592 stdID(wxID_BOLD);
2593 stdID(wxID_ITALIC);
2594 stdID(wxID_JUSTIFY_CENTER);
2595 stdID(wxID_JUSTIFY_FILL);
2596 stdID(wxID_JUSTIFY_RIGHT);
2597 stdID(wxID_JUSTIFY_LEFT);
2598 stdID(wxID_UNDERLINE);
2599 stdID(wxID_INDENT);
2600 stdID(wxID_UNINDENT);
2601 stdID(wxID_ZOOM_100);
2602 stdID(wxID_ZOOM_FIT);
2603 stdID(wxID_ZOOM_IN);
2604 stdID(wxID_ZOOM_OUT);
2605 stdID(wxID_UNDELETE);
2606 stdID(wxID_REVERT_TO_SAVED);
2607 stdID(wxID_SYSTEM_MENU);
2608 stdID(wxID_CLOSE_FRAME);
2609 stdID(wxID_MOVE_FRAME);
2610 stdID(wxID_RESIZE_FRAME);
2611 stdID(wxID_MAXIMIZE_FRAME);
2612 stdID(wxID_ICONIZE_FRAME);
2613 stdID(wxID_RESTORE_FRAME);
2614 stdID(wxID_CDROM);
2615 stdID(wxID_CONVERT);
2616 stdID(wxID_EXECUTE);
2617 stdID(wxID_FLOPPY);
2618 stdID(wxID_HARDDISK);
2619 stdID(wxID_BOTTOM);
2620 stdID(wxID_FIRST);
2621 stdID(wxID_LAST);
2622 stdID(wxID_TOP);
2623 stdID(wxID_INFO);
2624 stdID(wxID_JUMP_TO);
2625 stdID(wxID_NETWORK);
2626 stdID(wxID_SELECT_COLOR);
2627 stdID(wxID_SELECT_FONT);
2628 stdID(wxID_SORT_ASCENDING);
2629 stdID(wxID_SORT_DESCENDING);
2630 stdID(wxID_SPELL_CHECK);
2631 stdID(wxID_STRIKETHROUGH);
2632
2633 #undef stdID
2634 }
2635
2636 } // anonymous namespace
2637
2638
2639 /*static*/
2640 int wxXmlResource::DoGetXRCID(const char *str_id, int value_if_not_found)
2641 {
2642 if ( !gs_stdIDsAdded )
2643 {
2644 gs_stdIDsAdded = true;
2645 AddStdXRCID_Records();
2646 }
2647
2648 return XRCID_Lookup(str_id, value_if_not_found);
2649 }
2650
2651 /* static */
2652 wxString wxXmlResource::FindXRCIDById(int numId)
2653 {
2654 for ( int i = 0; i < XRCID_TABLE_SIZE; i++ )
2655 {
2656 for ( XRCID_record *rec = XRCID_Records[i]; rec; rec = rec->next )
2657 {
2658 if ( rec->id == numId )
2659 return wxString(rec->key);
2660 }
2661 }
2662
2663 return wxString();
2664 }
2665
2666 /* static */
2667 void wxIdRangeManager::RemoveXRCIDEntry(const wxString& idstr)
2668 {
2669 const char *str_id = idstr.mb_str();
2670
2671 const unsigned index = XRCIdHash(str_id);
2672
2673 XRCID_record **p_previousrec = &XRCID_Records[index];
2674 for (XRCID_record *rec = XRCID_Records[index]; rec; rec = rec->next)
2675 {
2676 if (wxStrcmp(rec->key, str_id) == 0)
2677 {
2678 // Found the item to be removed so delete its record; but first
2679 // remove it from the linked list.
2680 *p_previousrec = rec->next;
2681 free(rec->key);
2682 delete rec;
2683 return;
2684 }
2685
2686 p_previousrec = &rec->next;
2687 }
2688 }
2689
2690 static void CleanXRCID_Record(XRCID_record *rec)
2691 {
2692 if (rec)
2693 {
2694 CleanXRCID_Record(rec->next);
2695
2696 free(rec->key);
2697 delete rec;
2698 }
2699 }
2700
2701 static void CleanXRCID_Records()
2702 {
2703 for (int i = 0; i < XRCID_TABLE_SIZE; i++)
2704 {
2705 CleanXRCID_Record(XRCID_Records[i]);
2706 XRCID_Records[i] = NULL;
2707 }
2708
2709 gs_stdIDsAdded = false;
2710 }
2711
2712
2713 //-----------------------------------------------------------------------------
2714 // module and globals
2715 //-----------------------------------------------------------------------------
2716
2717 // normally we would do the cleanup from wxXmlResourceModule::OnExit() but it
2718 // can happen that some XRC records have been created because of the use of
2719 // XRCID() in event tables, which happens during static objects initialization,
2720 // but then the application initialization failed and so the wx modules were
2721 // neither initialized nor cleaned up -- this static object does the cleanup in
2722 // this case
2723 static struct wxXRCStaticCleanup
2724 {
2725 ~wxXRCStaticCleanup() { CleanXRCID_Records(); }
2726 } s_staticCleanup;
2727
2728 class wxXmlResourceModule: public wxModule
2729 {
2730 DECLARE_DYNAMIC_CLASS(wxXmlResourceModule)
2731 public:
2732 wxXmlResourceModule() {}
2733 bool OnInit()
2734 {
2735 wxXmlResource::AddSubclassFactory(new wxXmlSubclassFactoryCXX);
2736 return true;
2737 }
2738 void OnExit()
2739 {
2740 delete wxXmlResource::Set(NULL);
2741 delete wxIdRangeManager::Set(NULL);
2742 if(wxXmlResource::ms_subclassFactories)
2743 {
2744 for ( wxXmlSubclassFactories::iterator i = wxXmlResource::ms_subclassFactories->begin();
2745 i != wxXmlResource::ms_subclassFactories->end(); ++i )
2746 {
2747 delete *i;
2748 }
2749 wxDELETE(wxXmlResource::ms_subclassFactories);
2750 }
2751 CleanXRCID_Records();
2752 }
2753 };
2754
2755 IMPLEMENT_DYNAMIC_CLASS(wxXmlResourceModule, wxModule)
2756
2757
2758 // When wxXml is loaded dynamically after the application is already running
2759 // then the built-in module system won't pick this one up. Add it manually.
2760 void wxXmlInitResourceModule()
2761 {
2762 wxModule* module = new wxXmlResourceModule;
2763 module->Init();
2764 wxModule::RegisterModule(module);
2765 }
2766
2767 #endif // wxUSE_XRC