add public wxXmlResource::GetResourceNode() which can be used directly instead of...
[wxWidgets.git] / include / wx / xrc / xmlres.h
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: wx/xrc/xmlres.h
3 // Purpose: XML 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 #ifndef _WX_XMLRES_H_
12 #define _WX_XMLRES_H_
13
14 #include "wx/defs.h"
15
16 #if wxUSE_XRC
17
18 #include "wx/string.h"
19 #include "wx/dynarray.h"
20 #include "wx/arrstr.h"
21 #include "wx/datetime.h"
22 #include "wx/list.h"
23 #include "wx/gdicmn.h"
24 #include "wx/filesys.h"
25 #include "wx/bitmap.h"
26 #include "wx/icon.h"
27 #include "wx/artprov.h"
28 #include "wx/colour.h"
29 #include "wx/animate.h"
30 #include "wx/vector.h"
31
32 #include "wx/xml/xml.h"
33
34 class WXDLLIMPEXP_FWD_CORE wxMenu;
35 class WXDLLIMPEXP_FWD_CORE wxMenuBar;
36 class WXDLLIMPEXP_FWD_CORE wxDialog;
37 class WXDLLIMPEXP_FWD_CORE wxPanel;
38 class WXDLLIMPEXP_FWD_CORE wxWindow;
39 class WXDLLIMPEXP_FWD_CORE wxFrame;
40 class WXDLLIMPEXP_FWD_CORE wxToolBar;
41
42 class WXDLLIMPEXP_FWD_XRC wxXmlResourceHandler;
43 class WXDLLIMPEXP_FWD_XRC wxXmlSubclassFactory;
44 class wxXmlSubclassFactories;
45 class wxXmlResourceModule;
46 class wxXmlResourceDataRecords;
47
48 // These macros indicate current version of XML resources (this information is
49 // encoded in root node of XRC file as "version" property).
50 //
51 // Rules for increasing version number:
52 // - change it only if you made incompatible change to the format. Addition
53 // of new attribute to control handler is _not_ incompatible change, because
54 // older versions of the library may ignore it.
55 // - if you change version number, follow these steps:
56 // - set major, minor and release numbers to respective version numbers of
57 // the wxWidgets library (see wx/version.h)
58 // - reset revision to 0 unless the first three are same as before,
59 // in which case you should increase revision by one
60 #define WX_XMLRES_CURRENT_VERSION_MAJOR 2
61 #define WX_XMLRES_CURRENT_VERSION_MINOR 5
62 #define WX_XMLRES_CURRENT_VERSION_RELEASE 3
63 #define WX_XMLRES_CURRENT_VERSION_REVISION 0
64 #define WX_XMLRES_CURRENT_VERSION_STRING _T("2.5.3.0")
65
66 #define WX_XMLRES_CURRENT_VERSION \
67 (WX_XMLRES_CURRENT_VERSION_MAJOR * 256*256*256 + \
68 WX_XMLRES_CURRENT_VERSION_MINOR * 256*256 + \
69 WX_XMLRES_CURRENT_VERSION_RELEASE * 256 + \
70 WX_XMLRES_CURRENT_VERSION_REVISION)
71
72 enum wxXmlResourceFlags
73 {
74 wxXRC_USE_LOCALE = 1,
75 wxXRC_NO_SUBCLASSING = 2,
76 wxXRC_NO_RELOADING = 4
77 };
78
79 // This class holds XML resources from one or more .xml files
80 // (or derived forms, either binary or zipped -- see manual for
81 // details).
82 class WXDLLIMPEXP_XRC wxXmlResource : public wxObject
83 {
84 public:
85 // Constructor.
86 // Flags: wxXRC_USE_LOCALE
87 // translatable strings will be translated via _()
88 // using the given domain if specified
89 // wxXRC_NO_SUBCLASSING
90 // subclass property of object nodes will be ignored
91 // (useful for previews in XRC editors)
92 // wxXRC_NO_RELOADING
93 // don't check the modification time of the XRC files and
94 // reload them if they have changed on disk
95 wxXmlResource(int flags = wxXRC_USE_LOCALE,
96 const wxString& domain = wxEmptyString);
97
98 // Constructor.
99 // Flags: wxXRC_USE_LOCALE
100 // translatable strings will be translated via _()
101 // using the given domain if specified
102 // wxXRC_NO_SUBCLASSING
103 // subclass property of object nodes will be ignored
104 // (useful for previews in XRC editors)
105 wxXmlResource(const wxString& filemask, int flags = wxXRC_USE_LOCALE,
106 const wxString& domain = wxEmptyString);
107
108 // Destructor.
109 virtual ~wxXmlResource();
110
111 // Loads resources from XML files that match given filemask.
112 // This method understands VFS (see filesys.h).
113 bool Load(const wxString& filemask);
114
115 // Unload resource from the given XML file (wildcards not allowed)
116 bool Unload(const wxString& filename);
117
118 // Initialize handlers for all supported controls/windows. This will
119 // make the executable quite big because it forces linking against
120 // most of the wxWidgets library.
121 void InitAllHandlers();
122
123 // Initialize only a specific handler (or custom handler). Convention says
124 // that handler name is equal to the control's name plus 'XmlHandler', for
125 // example wxTextCtrlXmlHandler, wxHtmlWindowXmlHandler. The XML resource
126 // compiler (xmlres) can create include file that contains initialization
127 // code for all controls used within the resource.
128 void AddHandler(wxXmlResourceHandler *handler);
129
130 // Add a new handler at the begining of the handler list
131 void InsertHandler(wxXmlResourceHandler *handler);
132
133 // Removes all handlers
134 void ClearHandlers();
135
136 // Registers subclasses factory for use in XRC. This function is not meant
137 // for public use, please see the comment above wxXmlSubclassFactory
138 // definition.
139 static void AddSubclassFactory(wxXmlSubclassFactory *factory);
140
141 // Loads menu from resource. Returns NULL on failure.
142 wxMenu *LoadMenu(const wxString& name);
143
144 // Loads menubar from resource. Returns NULL on failure.
145 wxMenuBar *LoadMenuBar(wxWindow *parent, const wxString& name);
146
147 // Loads menubar from resource. Returns NULL on failure.
148 wxMenuBar *LoadMenuBar(const wxString& name) { return LoadMenuBar(NULL, name); }
149
150 #if wxUSE_TOOLBAR
151 // Loads a toolbar.
152 wxToolBar *LoadToolBar(wxWindow *parent, const wxString& name);
153 #endif
154
155 // Loads a dialog. dlg points to parent window (if any).
156 wxDialog *LoadDialog(wxWindow *parent, const wxString& name);
157
158 // Loads a dialog. dlg points to parent window (if any). This form
159 // is used to finish creation of already existing instance (main reason
160 // for this is that you may want to use derived class with new event table)
161 // Example (typical usage):
162 // MyDialog dlg;
163 // wxTheXmlResource->LoadDialog(&dlg, mainFrame, "my_dialog");
164 // dlg->ShowModal();
165 bool LoadDialog(wxDialog *dlg, wxWindow *parent, const wxString& name);
166
167 // Loads a panel. panel points to parent window (if any).
168 wxPanel *LoadPanel(wxWindow *parent, const wxString& name);
169
170 // Loads a panel. panel points to parent window (if any). This form
171 // is used to finish creation of already existing instance.
172 bool LoadPanel(wxPanel *panel, wxWindow *parent, const wxString& name);
173
174 // Loads a frame.
175 wxFrame *LoadFrame(wxWindow* parent, const wxString& name);
176 bool LoadFrame(wxFrame* frame, wxWindow *parent, const wxString& name);
177
178 // Load an object from the resource specifying both the resource name and
179 // the classname. This lets you load nonstandard container windows.
180 wxObject *LoadObject(wxWindow *parent, const wxString& name,
181 const wxString& classname);
182
183 // Load an object from the resource specifying both the resource name and
184 // the classname. This form lets you finish the creation of an existing
185 // instance.
186 bool LoadObject(wxObject *instance, wxWindow *parent, const wxString& name,
187 const wxString& classname);
188
189 // Loads a bitmap resource from a file.
190 wxBitmap LoadBitmap(const wxString& name);
191
192 // Loads an icon resource from a file.
193 wxIcon LoadIcon(const wxString& name);
194
195 // Attaches an unknown control to the given panel/window/dialog.
196 // Unknown controls are used in conjunction with <object class="unknown">.
197 bool AttachUnknownControl(const wxString& name, wxWindow *control,
198 wxWindow *parent = NULL);
199
200 // Returns a numeric ID that is equivalent to the string ID used in an XML
201 // resource. If an unknown str_id is requested (i.e. other than wxID_XXX
202 // or integer), a new record is created which associates the given string
203 // with a number. If value_if_not_found == wxID_NONE, the number is obtained via
204 // wxWindow::NewControlId(). Otherwise value_if_not_found is used.
205 // Macro XRCID(name) is provided for convenient use in event tables.
206 static int GetXRCID(const wxString& str_id, int value_if_not_found = wxID_NONE)
207 { return DoGetXRCID(str_id.mb_str(), value_if_not_found); }
208
209 // version for internal use only
210 static int DoGetXRCID(const char *str_id, int value_if_not_found = wxID_NONE);
211
212
213 // Find the string ID with the given numeric value, returns an empty string
214 // if no such ID is found.
215 //
216 // Notice that unlike GetXRCID(), which is fast, this operation is slow as
217 // it checks all the IDs used in XRC.
218 static wxString FindXRCIDById(int numId);
219
220
221 // Returns version information (a.b.c.d = d+ 256*c + 256^2*b + 256^3*a).
222 long GetVersion() const { return m_version; }
223
224 // Compares resources version to argument. Returns -1 if resources version
225 // is less than the argument, +1 if greater and 0 if they equal.
226 int CompareVersion(int major, int minor, int release, int revision) const
227 { return GetVersion() -
228 (major*256*256*256 + minor*256*256 + release*256 + revision); }
229
230 //// Singleton accessors.
231
232 // Gets the global resources object or creates one if none exists.
233 static wxXmlResource *Get();
234
235 // Sets the global resources object and returns a pointer to the previous one (may be NULL).
236 static wxXmlResource *Set(wxXmlResource *res);
237
238 // Returns flags, which may be a bitlist of wxXRC_USE_LOCALE and wxXRC_NO_SUBCLASSING.
239 int GetFlags() const { return m_flags; }
240 // Set flags after construction.
241 void SetFlags(int flags) { m_flags = flags; }
242
243 // Get/Set the domain to be passed to the translation functions, defaults
244 // to empty string (no domain).
245 const wxString& GetDomain() const { return m_domain; }
246 void SetDomain(const wxString& domain);
247
248
249 // This function returns the wxXmlNode containing the definition of the
250 // object with the given name or NULL.
251 //
252 // It can be used to access additional information defined in the XRC file
253 // and not used by wxXmlResource itself.
254 const wxXmlNode *GetResourceNode(const wxString& name) const
255 { return GetResourceNodeAndLocation(name, wxString(), true); }
256
257 protected:
258 // Scans the resources list for unloaded files and loads them. Also reloads
259 // files that have been modified since last loading.
260 bool UpdateResources();
261
262
263 // Common implementation of GetResourceNode() and FindResource(): searches
264 // all top-level or all (if recursive == true) nodes if all loaded XRC
265 // files and returns the node, if found, as well as the path of the file it
266 // was found in if path is non-NULL
267 wxXmlNode *GetResourceNodeAndLocation(const wxString& name,
268 const wxString& classname,
269 bool recursive = false,
270 wxString *path = NULL) const;
271
272
273 // Note that these functions are used outside of wxWidgets itself, e.g.
274 // there are several known cases of inheriting from wxXmlResource just to
275 // be able to call FindResource() so we keep them for compatibility even if
276 // their names are not really consistent with GetResourceNode() public
277 // function and FindResource() is also non-const because it changes the
278 // current path of m_curFileSystem to ensure that relative paths work
279 // correctly when CreateResFromNode() is called immediately afterwards
280 // (something const public function intentionally does not do)
281
282 // Returns the node containing the resource with the given name and class
283 // name unless it's empty (then any class matches) or NULL if not found.
284 wxXmlNode *FindResource(const wxString& name, const wxString& classname,
285 bool recursive = false);
286
287 // Helper function used by FindResource() to look under the given node.
288 wxXmlNode *DoFindResource(wxXmlNode *parent, const wxString& name,
289 const wxString& classname, bool recursive) const;
290
291 // Creates a resource from information in the given node
292 // (Uses only 'handlerToUse' if != NULL)
293 wxObject *CreateResFromNode(wxXmlNode *node, wxObject *parent,
294 wxObject *instance = NULL,
295 wxXmlResourceHandler *handlerToUse = NULL);
296
297 // Helper of Load() and Unload(): returns the URL corresponding to the
298 // given file if it's indeed a file, otherwise returns the original string
299 // unmodified
300 static wxString ConvertFileNameToURL(const wxString& filename);
301
302 // loading resources from archives is impossible without wxFileSystem
303 #if wxUSE_FILESYSTEM
304 // Another helper: detect if the filename is a ZIP or XRS file
305 static bool IsArchive(const wxString& filename);
306 #endif // wxUSE_FILESYSTEM
307
308 private:
309 wxXmlResourceDataRecords& Data() { return *m_data; }
310 const wxXmlResourceDataRecords& Data() const { return *m_data; }
311
312 private:
313 long m_version;
314
315 int m_flags;
316 wxVector<wxXmlResourceHandler*> m_handlers;
317 wxXmlResourceDataRecords *m_data;
318 #if wxUSE_FILESYSTEM
319 wxFileSystem m_curFileSystem;
320 wxFileSystem& GetCurFileSystem() { return m_curFileSystem; }
321 #endif
322
323 // domain to pass to translation functions, if any.
324 wxString m_domain;
325
326 friend class wxXmlResourceHandler;
327 friend class wxXmlResourceModule;
328
329 static wxXmlSubclassFactories *ms_subclassFactories;
330
331 // singleton instance:
332 static wxXmlResource *ms_instance;
333 };
334
335
336 // This macro translates string identifier (as used in XML resource,
337 // e.g. <menuitem id="my_menu">...</menuitem>) to integer id that is needed by
338 // wxWidgets event tables.
339 // Example:
340 // BEGIN_EVENT_TABLE(MyFrame, wxFrame)
341 // EVT_MENU(XRCID("quit"), MyFrame::OnQuit)
342 // EVT_MENU(XRCID("about"), MyFrame::OnAbout)
343 // EVT_MENU(XRCID("new"), MyFrame::OnNew)
344 // EVT_MENU(XRCID("open"), MyFrame::OnOpen)
345 // END_EVENT_TABLE()
346
347 #define XRCID(str_id) \
348 wxXmlResource::DoGetXRCID(str_id)
349
350
351 // This macro returns pointer to particular control in dialog
352 // created using XML resources. You can use it to set/get values from
353 // controls.
354 // Example:
355 // wxDialog dlg;
356 // wxXmlResource::Get()->LoadDialog(&dlg, mainFrame, "my_dialog");
357 // XRCCTRL(dlg, "my_textctrl", wxTextCtrl)->SetValue(wxT("default value"));
358
359 #define XRCCTRL(window, id, type) \
360 (wxStaticCast((window).FindWindow(XRCID(id)), type))
361
362 // This macro returns pointer to sizer item
363 // Example:
364 //
365 // <object class="spacer" name="area">
366 // <size>400, 300</size>
367 // </object>
368 //
369 // wxSizerItem* item = XRCSIZERITEM(*this, "area")
370
371 #define XRCSIZERITEM(window, id) \
372 ((window).GetSizer() ? (window).GetSizer()->GetItemById(XRCID(id)) : NULL)
373
374 // wxXmlResourceHandler is an abstract base class for resource handlers
375 // capable of creating a control from an XML node.
376
377 class WXDLLIMPEXP_XRC wxXmlResourceHandler : public wxObject
378 {
379 DECLARE_ABSTRACT_CLASS(wxXmlResourceHandler)
380 public:
381 // Constructor.
382 wxXmlResourceHandler();
383
384 // Destructor.
385 virtual ~wxXmlResourceHandler() {}
386
387 // Creates an object (menu, dialog, control, ...) from an XML node.
388 // Should check for validity.
389 // parent is a higher-level object (usually window, dialog or panel)
390 // that is often necessary to create the resource.
391 // If instance is non-NULL it should not create a new instance via 'new' but
392 // should rather use this one, and call its Create method.
393 wxObject *CreateResource(wxXmlNode *node, wxObject *parent,
394 wxObject *instance);
395
396 // This one is called from CreateResource after variables
397 // were filled.
398 virtual wxObject *DoCreateResource() = 0;
399
400 // Returns true if it understands this node and can create
401 // a resource from it, false otherwise.
402 virtual bool CanHandle(wxXmlNode *node) = 0;
403
404 // Sets the parent resource.
405 void SetParentResource(wxXmlResource *res) { m_resource = res; }
406
407 protected:
408 wxXmlResource *m_resource;
409 wxArrayString m_styleNames;
410 wxArrayInt m_styleValues;
411
412 // Variables (filled by CreateResource)
413 wxXmlNode *m_node;
414 wxString m_class;
415 wxObject *m_parent, *m_instance;
416 wxWindow *m_parentAsWindow;
417
418 // --- Handy methods:
419
420 // Returns true if the node has a property class equal to classname,
421 // e.g. <object class="wxDialog">.
422 bool IsOfClass(wxXmlNode *node, const wxString& classname);
423
424 // Gets node content from wxXML_ENTITY_NODE
425 // The problem is, <tag>content<tag> is represented as
426 // wxXML_ENTITY_NODE name="tag", content=""
427 // |-- wxXML_TEXT_NODE or
428 // wxXML_CDATA_SECTION_NODE name="" content="content"
429 wxString GetNodeContent(wxXmlNode *node);
430
431 // Check to see if a parameter exists.
432 bool HasParam(const wxString& param);
433
434 // Finds the node or returns NULL.
435 wxXmlNode *GetParamNode(const wxString& param);
436
437 // Finds the parameter value or returns the empty string.
438 wxString GetParamValue(const wxString& param);
439
440 // Add a style flag (e.g. wxMB_DOCKABLE) to the list of flags
441 // understood by this handler.
442 void AddStyle(const wxString& name, int value);
443
444 // Add styles common to all wxWindow-derived classes.
445 void AddWindowStyles();
446
447 // Gets style flags from text in form "flag | flag2| flag3 |..."
448 // Only understands flags added with AddStyle
449 int GetStyle(const wxString& param = wxT("style"), int defaults = 0);
450
451 // Gets text from param and does some conversions:
452 // - replaces \n, \r, \t by respective chars (according to C syntax)
453 // - replaces _ by & and __ by _ (needed for _File => &File because of XML)
454 // - calls wxGetTranslations (unless disabled in wxXmlResource)
455 wxString GetText(const wxString& param, bool translate = true);
456
457 // Returns the XRCID.
458 int GetID();
459
460 // Returns the resource name.
461 wxString GetName();
462
463 // Gets a bool flag (1, t, yes, on, true are true, everything else is false).
464 bool GetBool(const wxString& param, bool defaultv = false);
465
466 // Gets an integer value from the parameter.
467 long GetLong(const wxString& param, long defaultv = 0);
468
469 // Gets a float value from the parameter.
470 float GetFloat(const wxString& param, float defaultv = 0);
471
472 // Gets colour in HTML syntax (#RRGGBB).
473 wxColour GetColour(const wxString& param, const wxColour& defaultv = wxNullColour);
474
475 // Gets the size (may be in dialog units).
476 wxSize GetSize(const wxString& param = wxT("size"),
477 wxWindow *windowToUse = NULL);
478
479 // Gets the position (may be in dialog units).
480 wxPoint GetPosition(const wxString& param = wxT("pos"));
481
482 // Gets a dimension (may be in dialog units).
483 wxCoord GetDimension(const wxString& param, wxCoord defaultv = 0,
484 wxWindow *windowToUse = NULL);
485
486 // Gets a bitmap.
487 wxBitmap GetBitmap(const wxString& param = wxT("bitmap"),
488 const wxArtClient& defaultArtClient = wxART_OTHER,
489 wxSize size = wxDefaultSize);
490
491 // Gets an icon.
492 wxIcon GetIcon(const wxString& param = wxT("icon"),
493 const wxArtClient& defaultArtClient = wxART_OTHER,
494 wxSize size = wxDefaultSize);
495
496 #if wxUSE_ANIMATIONCTRL
497 // Gets an animation.
498 wxAnimation GetAnimation(const wxString& param = wxT("animation"));
499 #endif
500
501 // Gets a font.
502 wxFont GetFont(const wxString& param = wxT("font"));
503
504 // Gets the value of a boolean attribute (only "0" and "1" are valid values)
505 bool GetBoolAttr(const wxString& attr, bool defaultv);
506
507
508 // Sets common window options.
509 void SetupWindow(wxWindow *wnd);
510
511 // Creates children.
512 void CreateChildren(wxObject *parent, bool this_hnd_only = false);
513
514 // Helper function.
515 void CreateChildrenPrivately(wxObject *parent, wxXmlNode *rootnode = NULL);
516
517 // Creates a resource from a node.
518 wxObject *CreateResFromNode(wxXmlNode *node,
519 wxObject *parent, wxObject *instance = NULL)
520 { return m_resource->CreateResFromNode(node, parent, instance); }
521
522 // helper
523 #if wxUSE_FILESYSTEM
524 wxFileSystem& GetCurFileSystem() { return m_resource->GetCurFileSystem(); }
525 #endif
526 };
527
528
529 // Programmer-friendly macros for writing XRC handlers:
530
531 #define XRC_ADD_STYLE(style) AddStyle(wxT(#style), style)
532
533 #define XRC_MAKE_INSTANCE(variable, classname) \
534 classname *variable = NULL; \
535 if (m_instance) \
536 variable = wxStaticCast(m_instance, classname); \
537 if (!variable) \
538 variable = new classname;
539
540
541 // FIXME -- remove this $%^#$%#$@# as soon as Ron checks his changes in!!
542 WXDLLIMPEXP_XRC void wxXmlInitResourceModule();
543
544
545 // This class is used to create instances of XRC "object" nodes with "subclass"
546 // property. It is _not_ supposed to be used by XRC users, you should instead
547 // register your subclasses via wxWidgets' RTTI mechanism. This class is useful
548 // only for language bindings developer who need a way to implement subclassing
549 // in wxWidgets ports that don't support wxRTTI (e.g. wxPython).
550 class WXDLLIMPEXP_XRC wxXmlSubclassFactory
551 {
552 public:
553 // Try to create instance of given class and return it, return NULL on
554 // failure:
555 virtual wxObject *Create(const wxString& className) = 0;
556 virtual ~wxXmlSubclassFactory() {}
557 };
558
559
560 /* -------------------------------------------------------------------------
561 Backward compatibility macros. Do *NOT* use, they may disappear in future
562 versions of the XRC library!
563 ------------------------------------------------------------------------- */
564
565 #endif // wxUSE_XRC
566
567 #endif // _WX_XMLRES_H_