]> git.saurik.com Git - wxWidgets.git/blob - docs/latex/wx/txrc.tex
Typo fix
[wxWidgets.git] / docs / latex / wx / txrc.tex
1 % Note: -e/C++ header generation documentation added by
2 % Eduardo Marques <edrdo@netcabo.pt>
3 %
4 \section{XML-based resource system overview}\label{xrcoverview}
5
6 Classes: \helpref{wxXmlResource}{wxxmlresource}, \helpref{wxXmlResourceHandler}{wxxmlresourcehandler}
7
8 The XML-based resource system, known as XRC, allows user interface elements such as
9 dialogs, menu bars and toolbars, to be stored in text files and loaded into
10 the application at run-time. XRC files can also be compiled into binary XRS files or C++
11 code (the former makes it possible to store all resources in a single file and the latter
12 is useful when you want to embed the resources into the executable).
13
14 There are several advantages to using XRC resources.
15
16 \begin{itemize}\itemsep=0pt
17 \item Recompiling and linking an application is not necessary if the
18 resources change.
19 \item If you use a dialog designer that generates C++ code, it can be hard
20 to reintegrate this into existing C++ code. Separation of resources and code
21 is a more elegant solution.
22 \item You can choose between different alternative resource files at run time, if necessary.
23 \item The XRC format uses sizers for flexibility, allowing dialogs to be resizable
24 and highly portable.
25 \item The XRC format is a wxWidgets standard,
26 and can be generated or postprocessed by any program that understands it. As it is based
27 on the XML standard, existing XML editors can be used for simple editing purposes.
28 \end{itemize}
29
30 XRC was written by Vaclav Slavik.
31
32 \subsection{XRC concepts}\label{xrcconcepts}
33
34 These are the typical steps for using XRC files in your application.
35
36 \begin{itemize}\itemsep=0pt
37 \item Include the appropriate headers: normally "wx/xrc/xmlres.h" will suffice;
38 \item If you are going to use \helpref{XRS files}{binaryresourcefiles}, install
39 wxFileSystem archive handler first with {\tt wxFileSystem::AddHandler(new wxArchiveFSHandler);}
40 \item call {\tt wxXmlResource::Get()->InitAllHandlers()} from your wxApp::OnInit function,
41 and then call {\tt wxXmlResource::Get()->Load("myfile.xrc")} to load the resource file;
42 \item to create a dialog from a resource, create it using the default constructor, and then
43 load it using for example {\tt wxXmlResource::Get()->LoadDialog(\&dlg, this, "dlg1");}
44 \item set up event tables as usual but use the {\tt XRCID(str)} macro to translate from XRC string names
45 to a suitable integer identifier, for example {\tt EVT\_MENU(XRCID("quit"), MyFrame::OnQuit)}.
46 \end{itemize}
47
48 To create an XRC file, you can use one of the following methods.
49
50 \begin{itemize}\itemsep=0pt
51 \item Create the file by hand;
52 \item use \urlref{wxDesigner}{http://www.roebling.de}, a commercial dialog designer/RAD tool;
53 \item use \urlref{DialogBlocks}{http://www.anthemion.co.uk/dialogblocks}, a commercial dialog editor;
54 \item use \urlref{XRCed}{http://xrced.sf.net}, a wxPython-based
55 dialog editor that you can find in the {\tt wxPython/tools} subdirectory of the wxWidgets
56 CVS archive;
57 \item use \urlref{wxGlade}{http://wxglade.sf.net}, a GUI designer written in wxPython. At the moment it can generate Python, C++ and XRC;
58 \end{itemize}
59
60 A complete list of third-party tools that write to XRC can be found at \urlref{www.wxwidgets.org/lnk\_tool.htm}{http://www.wxwidgets.org/lnk\_tool.htm}.
61
62 It is highly recommended that you use a resource editing tool, since it's fiddly writing
63 XRC files by hand.
64
65 You can use \helpref{wxXmlResource::Load}{wxxmlresourceload} in a number of ways.
66 You can pass an XRC file (XML-based text resource file)
67 or a \helpref{zip-compressed file}{binaryresourcefiles} (extension ZIP or XRS) containing other XRC.
68
69 You can also use \helpref{embedded C++ resources}{embeddedresource}
70
71 \subsection{Using binary resource files}\label{binaryresourcefiles}
72
73 To compile binary resource files, use the command-line wxrc utility. It takes one or more file parameters
74 (the input XRC files) and the following switches and options:
75 \begin{itemize}\itemsep=0pt
76 \item -h (--help): show a help message
77 \item -v (--verbose): show verbose logging information
78 \item -c (--cpp-code): write C++ source rather than a XRS file
79 \item -e (--extra-cpp-code): if used together with -c, generates C++ header file
80 containing class definitions for the windows defined by the XRC file (see special subsection)
81 \item -u (--uncompressed): do not compress XML files (C++ only)
82 \item -g (--gettext): output underscore-wrapped strings that poEdit or gettext can scan. Outputs to stdout, or a file if -o is used
83 \item -n (--function) <name>: specify C++ function name (use with -c)
84 \item -o (--output) <filename>: specify the output file, such as resource.xrs or resource.cpp
85 \item -l (--list-of-handlers) <filename>: output a list of necessary handlers to this file
86 \end{itemize}
87
88 For example:
89 \begin{verbatim}
90 % wxrc resource.xrc
91 % wxrc resource.xrc -o resource.xrs
92 % wxrc resource.xrc -v -c -o resource.cpp
93 \end{verbatim}
94
95 \wxheading{Note}
96
97 XRS file is essentially a renamed ZIP archive which means that you can manipulate
98 it with standard ZIP tools. Note that if you are using XRS files, you have
99 to initialize the \helpref{wxFileSystem}{wxfilesystem} archive handler first! It is a simple
100 thing to do:
101
102 \begin{verbatim}
103 #include <wx/filesys.h>
104 #include <wx/fs_arc.h>
105 ...
106 wxFileSystem::AddHandler(new wxArchiveFSHandler);
107 \end{verbatim}
108
109 \subsection{Using embedded resources}\label{embeddedresource}
110
111 It is sometimes useful to embed resources in the executable itself instead
112 of loading an external file (e.g. when your app is small and consists only of one
113 exe file). XRC provides means to convert resources into regular C++ file that
114 can be compiled and included in the executable.
115
116 Use the {\tt -c} switch to
117 {\tt wxrc} utility to produce C++ file with embedded resources. This file will
118 contain a function called {\it InitXmlResource} (unless you override this with
119 a command line switch). Use it to load the resource:
120
121 \begin{verbatim}
122 extern void InitXmlResource(); // defined in generated file
123 ...
124 wxXmlResource::Get()->InitAllHandlers();
125 InitXmlResource();
126 ...
127 \end{verbatim}
128
129 \subsection{XRC C++ sample}\label{xrccppsample}
130
131 This is the C++ source file (xrcdemo.cpp) for the XRC sample.
132
133 \begin{verbatim}
134 #include "wx/wx.h"
135 #include "wx/image.h"
136 #include "wx/xrc/xmlres.h"
137
138 // the application icon
139 #if defined(__WXGTK__) || defined(__WXMOTIF__) || defined(__WXMAC__)
140 #include "rc/appicon.xpm"
141 #endif
142
143 // ----------------------------------------------------------------------------
144 // private classes
145 // ----------------------------------------------------------------------------
146
147 // Define a new application type, each program should derive a class from wxApp
148 class MyApp : public wxApp
149 {
150 public:
151 // override base class virtuals
152 // ----------------------------
153
154 // this one is called on application startup and is a good place for the app
155 // initialization (doing it here and not in the ctor allows to have an error
156 // return: if OnInit() returns false, the application terminates)
157 virtual bool OnInit();
158 };
159
160 // Define a new frame type: this is going to be our main frame
161 class MyFrame : public wxFrame
162 {
163 public:
164 // ctor(s)
165 MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
166
167 // event handlers (these functions should _not_ be virtual)
168 void OnQuit(wxCommandEvent& event);
169 void OnAbout(wxCommandEvent& event);
170 void OnDlg1(wxCommandEvent& event);
171 void OnDlg2(wxCommandEvent& event);
172
173 private:
174 // any class wishing to process wxWidgets events must use this macro
175 DECLARE_EVENT_TABLE()
176 };
177
178 // ----------------------------------------------------------------------------
179 // event tables and other macros for wxWidgets
180 // ----------------------------------------------------------------------------
181
182 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
183 EVT_MENU(XRCID("menu_quit"), MyFrame::OnQuit)
184 EVT_MENU(XRCID("menu_about"), MyFrame::OnAbout)
185 EVT_MENU(XRCID("menu_dlg1"), MyFrame::OnDlg1)
186 EVT_MENU(XRCID("menu_dlg2"), MyFrame::OnDlg2)
187 END_EVENT_TABLE()
188
189 IMPLEMENT_APP(MyApp)
190
191 // ----------------------------------------------------------------------------
192 // the application class
193 // ----------------------------------------------------------------------------
194
195 // 'Main program' equivalent: the program execution "starts" here
196 bool MyApp::OnInit()
197 {
198 wxImage::AddHandler(new wxGIFHandler);
199 wxXmlResource::Get()->InitAllHandlers();
200 wxXmlResource::Get()->Load("rc/resource.xrc");
201
202 MyFrame *frame = new MyFrame("XML resources demo",
203 wxPoint(50, 50), wxSize(450, 340));
204 frame->Show(true);
205 return true;
206 }
207
208 // ----------------------------------------------------------------------------
209 // main frame
210 // ----------------------------------------------------------------------------
211
212 // frame constructor
213 MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
214 : wxFrame((wxFrame *)NULL, -1, title, pos, size)
215 {
216 SetIcon(wxICON(appicon));
217
218 SetMenuBar(wxXmlResource::Get()->LoadMenuBar("mainmenu"));
219 SetToolBar(wxXmlResource::Get()->LoadToolBar(this, "toolbar"));
220 }
221
222 // event handlers
223 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
224 {
225 // true is to force the frame to close
226 Close(true);
227 }
228
229 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
230 {
231 wxString msg;
232 msg.Printf( _T("This is the about dialog of XML resources demo.\n")
233 _T("Welcome to %s"), wxVERSION_STRING);
234
235 wxMessageBox(msg, "About XML resources demo", wxOK | wxICON_INFORMATION, this);
236 }
237
238 void MyFrame::OnDlg1(wxCommandEvent& WXUNUSED(event))
239 {
240 wxDialog dlg;
241 wxXmlResource::Get()->LoadDialog(&dlg, this, "dlg1");
242 dlg.ShowModal();
243 }
244
245 void MyFrame::OnDlg2(wxCommandEvent& WXUNUSED(event))
246 {
247 wxDialog dlg;
248 wxXmlResource::Get()->LoadDialog(&dlg, this, "dlg2");
249 dlg.ShowModal();
250 }
251 \end{verbatim}
252
253 \subsection{XRC resource file sample}\label{xrcsample}
254
255 This is the XML file (resource.xrc) for the XRC sample.
256
257 \begin{verbatim}
258 <?xml version="1.0"?>
259 <resource version="2.3.0.1">
260 <object class="wxMenuBar" name="mainmenu">
261 <style>wxMB_DOCKABLE</style>
262 <object class="wxMenu" name="menu_file">
263 <label>_File</label>
264 <style>wxMENU_TEAROFF</style>
265 <object class="wxMenuItem" name="menu_about">
266 <label>_About...</label>
267 <bitmap>filesave.gif</bitmap>
268 </object>
269 <object class="separator"/>
270 <object class="wxMenuItem" name="menu_dlg1">
271 <label>Dialog 1</label>
272 </object>
273 <object class="wxMenuItem" name="menu_dlg2">
274 <label>Dialog 2</label>
275 </object>
276 <object class="separator"/>
277 <object class="wxMenuItem" name="menu_quit">
278 <label>E_xit\tAlt-X</label>
279 </object>
280 </object>
281 </object>
282 <object class="wxToolBar" name="toolbar">
283 <style>wxTB_FLAT|wxTB_DOCKABLE</style>
284 <margins>2,2</margins>
285 <object class="tool" name="menu_open">
286 <bitmap>fileopen.gif</bitmap>
287 <tooltip>Open catalog</tooltip>
288 </object>
289 <object class="tool" name="menu_save">
290 <bitmap>filesave.gif</bitmap>
291 <tooltip>Save catalog</tooltip>
292 </object>
293 <object class="tool" name="menu_update">
294 <bitmap>update.gif</bitmap>
295 <tooltip>Update catalog - synchronize it with sources</tooltip>
296 </object>
297 <separator/>
298 <object class="tool" name="menu_quotes">
299 <bitmap>quotes.gif</bitmap>
300 <toggle>1</toggle>
301 <tooltip>Display quotes around the string?</tooltip>
302 </object>
303 <object class="separator"/>
304 <object class="tool" name="menu_fuzzy">
305 <bitmap>fuzzy.gif</bitmap>
306 <tooltip>Toggled if selected string is fuzzy translation</tooltip>
307 <toggle>1</toggle>
308 </object>
309 </object>
310 <object class="wxDialog" name="dlg1">
311 <object class="wxBoxSizer">
312 <object class="sizeritem">
313 <object class="wxBitmapButton">
314 <bitmap>fuzzy.gif</bitmap>
315 <focus>fileopen.gif</focus>
316 </object>
317 </object>
318 <object class="sizeritem">
319 <object class="wxPanel">
320 <object class="wxStaticText">
321 <label>fdgdfgdfgdfg</label>
322 </object>
323 <style>wxBORDER\_SUNKEN</style>
324 </object>
325 <flag>wxALIGN_CENTER</flag>
326 </object>
327 <object class="sizeritem">
328 <object class="wxButton">
329 <label>Buttonek</label>
330 </object>
331 <border>10d</border>
332 <flag>wxALL</flag>
333 </object>
334 <object class="sizeritem">
335 <object class="wxHtmlWindow">
336 <htmlcode>&lt;h1&gt;Hi,&lt;/h1&gt;man</htmlcode>
337 <size>100,45d</size>
338 </object>
339 </object>
340 <object class="sizeritem">
341 <object class="wxNotebook">
342 <object class="notebookpage">
343 <object class="wxPanel">
344 <object class="wxBoxSizer">
345 <object class="sizeritem">
346 <object class="wxHtmlWindow">
347 <htmlcode>Hello, we are inside a &lt;u&gt;NOTEBOOK&lt;/u&gt;...</htmlcode>
348 <size>50,50d</size>
349 </object>
350 <option>1</option>
351 </object>
352 </object>
353 </object>
354 <label>Page</label>
355 </object>
356 <object class="notebookpage">
357 <object class="wxPanel">
358 <object class="wxBoxSizer">
359 <object class="sizeritem">
360 <object class="wxHtmlWindow">
361 <htmlcode>Hello, we are inside a &lt;u&gt;NOTEBOOK&lt;/u&gt;...</htmlcode>
362 <size>50,50d</size>
363 </object>
364 </object>
365 </object>
366 </object>
367 <label>Page 2</label>
368 </object>
369 <usenotebooksizer>1</usenotebooksizer>
370 </object>
371 <flag>wxEXPAND</flag>
372 </object>
373 <orient>wxVERTICAL</orient>
374 </object>
375 </object>
376 <object class="wxDialog" name="dlg2">
377 <object class="wxBoxSizer">
378 <orient>wxVERTICAL</orient>
379 <object class="sizeritem" name="dfgdfg">
380 <object class="wxTextCtrl">
381 <size>200,200d</size>
382 <style>wxTE_MULTILINE|wxBORDER_SUNKEN</style>
383 <value>Hello, this is an ordinary multiline\n textctrl....</value>
384 </object>
385 <option>1</option>
386 <flag>wxEXPAND|wxALL</flag>
387 <border>10</border>
388 </object>
389 <object class="sizeritem">
390 <object class="wxBoxSizer">
391 <object class="sizeritem">
392 <object class="wxButton" name="wxID_OK">
393 <label>Ok</label>
394 <default>1</default>
395 </object>
396 </object>
397 <object class="sizeritem">
398 <object class="wxButton" name="wxID_CANCEL">
399 <label>Cancel</label>
400 </object>
401 <border>10</border>
402 <flag>wxLEFT</flag>
403 </object>
404 </object>
405 <flag>wxLEFT|wxRIGHT|wxBOTTOM|wxALIGN_RIGHT</flag>
406 <border>10</border>
407 </object>
408 </object>
409 <title>Second testing dialog</title>
410 </object>
411 </resource>
412 \end{verbatim}
413
414 \subsection{XRC file format}\label{xrcfileformat}
415
416 Please see Technical Note 14 (docs/tech/tn0014.txt) in your wxWidgets
417 distribution.
418
419 \subsection{C++ header file generation}\label{xrccppheader}
420
421 Using the {\tt -e} switch together with {\tt -c}, a C++ header file is written
422 containing class definitions for the GUI windows defined in the XRC file.
423 This code generation can make it easier to use XRC and automate program
424 development.
425 The classes can be used as basis for development, freeing the
426 programmer from dealing with most of the XRC specifics (e.g. {\tt XRCCTRL}).
427
428 For each top level window defined in the XRC file a C++ class definition is
429 generated, containing as class members the named widgets of the window.
430 A default constructor for each class is also generated. Inside the constructor
431 all XRC loading is done and all class members representing widgets are initialized.
432
433 A simple example will help understand how the scheme works. Suppose you have
434 a XRC file defining a top level window {\tt TestWnd\_Base}, which subclasses {\tt wxFrame} (any
435 other class like {\tt wxDialog} will do also), and has subwidgets {\tt wxTextCtrl} A and {\tt wxButton} B.
436 The XRC file and corresponding class definition in the header file will be something like:
437
438 \begin{verbatim}
439 <?xml version="1.0"?>
440 <resource version="2.3.0.1">
441 <object class="wxFrame" name="TestWnd_Base">
442 <size>-1,-1</size>
443 <title>Test</title>
444 <object class="wxBoxSizer">
445 <orient>wxHORIZONTAL</orient>
446 <object class="sizeritem">
447 <object class="wxTextCtrl" name="A">
448 <label>Test label</label>
449 </object>
450 </object>
451 <object class="sizeritem">
452 <object class="wxButton" name="B">
453 <label>Test button</label>
454 </object>
455 </object>
456 </object>
457 </object>
458 </resource>
459
460
461 class TestWnd_Base : public wxFrame {
462 protected:
463 wxTextCtrl* A;
464 wxButton* B;
465
466 private:
467 void InitWidgetsFromXRC(){
468 wxXmlResource::Get()->LoadObject(this,NULL,"TestWnd","wxFrame");
469 A = XRCCTRL(*this,"A",wxTextCtrl);
470 B = XRCCTRL(*this,"B",wxButton);
471 }
472 public:
473 TestWnd::TestWnd(){
474 InitWidgetsFromXRC();
475 }
476 };
477 \end{verbatim}
478
479 The generated window class can be used as basis for the full window class. The
480 class members which represent widgets may be accessed by name instead of using
481 {\tt XRCCTRL} every time you wish to reference them (note that they are {\tt protected} class members),
482 though you must still use {\tt XRCID} to refer to widget IDs in the event
483 table.
484
485 Example:
486
487 \begin{verbatim}
488 #include "resource.h"
489
490 class TestWnd : public TestWnd_Base {
491 public:
492 TestWnd(){
493 // A, B already initialised at this point
494 A->SetValue("Updated in TestWnd::TestWnd");
495 B->SetValue("Nice :)");
496 }
497 void OnBPressed(wxEvent& event){
498 Close();
499 }
500 DECLARE_EVENT_TABLE();
501 };
502
503 BEGIN_EVENT_TABLE(TestWnd,TestWnd_Base)
504 EVT_BUTTON(XRCID("B"),TestWnd::OnBPressed)
505 END_EVENT_TABLE()
506
507 \end{verbatim}
508
509
510
511 \subsection{Adding new resource handlers}\label{newresourcehandlers}
512
513 Adding a new resource handler is pretty easy.
514 Typically, to add an handler for the {\tt MyControl} class, you'll want to create
515 the {\tt xh\_mycontrol.h} {\tt xh\_mycontrol.cpp} files.
516
517 The header needs to contains the {\tt MyControlXmlHandler} class definition:
518
519 \begin{verbatim}
520 class MyControlXmlHandler : public wxXmlResourceHandler
521 {
522 public:
523
524 // Constructor.
525 MyControlXmlHandler();
526
527 // Creates the control and returns a pointer to it.
528 virtual wxObject *DoCreateResource();
529
530 // Returns true if we know how to create a control for the given node.
531 virtual bool CanHandle(wxXmlNode *node);
532
533 // Register with wxWidgets' dynamic class subsystem.
534 DECLARE_DYNAMIC_CLASS(MyControlXmlHandler)
535 };
536 \end{verbatim}
537
538 The implementation of your custom XML handler will typically look as:
539
540 \begin{verbatim}
541 // Register with wxWidgets' dynamic class subsystem.
542 IMPLEMENT_DYNAMIC_CLASS(MyControlXmlHandler, wxXmlResourceHandler)
543
544 MyControlXmlHandler::MyControlXmlHandler()
545 {
546 // this call adds support for all wxWindows class styles
547 // (e.g. wxBORDER_SIMPLE, wxBORDER_SUNKEN, wxWS_EX_* etc etc)
548 AddWindowStyles();
549
550 // if MyControl class supports e.g. MYCONTROL_DEFAULT_STYLE
551 // you should use:
552 // XRC_ADD_STYLE(MYCONTROL_DEFAULT_STYLE);
553 }
554
555 wxObject *MyControlXmlHandler::DoCreateResource()
556 {
557 // the following macro will init a pointer named "control"
558 // with a new instance of the MyControl class, but will NOT
559 // Create() it!
560 XRC_MAKE_INSTANCE(control, MyControl)
561
562 // this is the point where you'll typically need to do the most
563 // important changes: here the control is created and initialized.
564 // You'll want to use the wxXmlResourceHandler's getters to
565 // do most of your work.
566 // If e.g. the MyControl::Create function looks like:
567 //
568 // bool MyControl::Create(wxWindow *parent, int id,
569 // const wxBitmap &first, const wxPoint &posFirst,
570 // const wxBitmap &second, const wxPoint &posSecond,
571 // const wxString &theTitle, const wxFont &titleFont,
572 // const wxPoint &pos, const wxSize &size,
573 // long style = MYCONTROL_DEFAULT_STYLE,
574 // const wxString &name = wxT("MyControl"));
575 //
576 // then the XRC for your component should look like:
577 //
578 // <object class="MyControl" name="some_name">
579 // <first-bitmap>first.xpm</first-bitmap>
580 // <second-bitmap>text.xpm</second-bitmap>
581 // <first-pos>3,3</first-pos>
582 // <second-pos>4,4</second-pos>
583 // <the-title>a title</the-title>
584 // <title-font>
585 // <!-- the standard XRC tags for describing a font: <size>, <style>, <weight>, etc -->
586 // </title-font>
587 // <!-- XRC also accepts other usual tags for wxWindow-derived classes:
588 // like e.g. <name>, <style>, <size>, <position>, etc -->
589 // </object>
590 //
591 // and the code to read your custom tags from the XRC file is just:
592 control->Create(m_parentAsWindow, GetID(),
593 GetBitmap(wxT("first-bitmap")),
594 GetPosition(wxT("first-pos")),
595 GetBitmap(wxT("second-bitmap")),
596 GetPosition(wxT("second-pos")),
597 GetText(wxT("the-title")),
598 GetFont(wxT("title-font")),
599 GetPosition(), GetSize(), GetStyle(), GetName());
600
601 SetupWindow(control);
602
603 return control;
604 }
605
606 bool MyControlXmlHandler::CanHandle(wxXmlNode *node)
607 {
608 // this function tells XRC system that this handler can parse
609 // the <object class="MyControl"> tags
610 return IsOfClass(node, wxT("MyControl"));
611 }
612 \end{verbatim}
613
614 You may want to check the \helpref{wxXmlResourceHandler}{wxxmlresourcehandler} documentation
615 to see how many built-in getters it contains. It's very easy to retrieve also complex structures
616 out of XRC files using them.
617